Skip to content Skip to sidebar Skip to footer

Use A For Loop Within An Ajax Call

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array,

Solution 1:

To help ensure that the appropriate element IDs and values are passed, loop through the various elements and add the data to an object first.

jQuery:

required = ['nome', 'sobrenome', 'endereco', 'codigopostal', 'localidade', 'telemovel', 'email', 'codigopostal2', 'localidade2', 'endereco2', 'nif', 'entidade', 'codigopostal3', 'localidade3', 'endereco3', 'nserie', 'modelo'];

functionajaxrequest() {
    var params = {}; // initialize object//loop through input arrayfor (var i=0; i < required.length; i++) {             
        // set the key/property (input element) for your objectvar ele = required[i]; 
        // add the property to the object and set the value
        params[ele] = $('#' + ele).val(); 
    }
    $.ajax({
        type: "POST",
        url: "ajaxload/como.php",
        data: params,
        success: function() {
            $(".agendarleft").html("SUCESS");
        }
    });
}

Demo:http://jsfiddle.net/kPR69/

Solution 2:

What would be much cleaner would be to put a class on each of the fields you wish to save and use this to iterate through them. Then you wouldn't need to specify the input names either and you could send a json object directly to the Service;

var obj = {};

$('.save').each(function () {

       var key = $(this).attr('id');
       varval = $(this).val();

       if (typeof (val) == "undefined")
           val = "''"

       obj[key] = val;
}

Then send obj as the data property of your AJAX call....

Solution 3:

There are a few issues with your code. 'required' is being overwritten and is also being re-declared inside of the loop.

I would suggest using pre-written library, a few I included below.

http://jquery.malsup.com/form/#validation

https://github.com/posabsolute/jQuery-Validation-Engine

Otherwise the follow would get you close. You may need to covert the array into a string.

var required = ['nome','sobrenome'];              

functionajaxrequest() {
  var values;
  for (i = 0; i < required.length; i++) {
    var values[i] = $('#' + required[i]).attr('value');
  }
  $.ajax({
    type: "POST",
    url: "ajaxload/como.php",
    data: values,
    success: function() {
        $(".agendarleft").html("SUCESS");
    }
});

}

Post a Comment for "Use A For Loop Within An Ajax Call"