Souza
Souza

Reputation: 1143

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, to pass the values to be sent via AJAX:

I never used the for loop in JS, but seems familiar anyway.

The way the loop is made, obviously wont work:

for (i=0;i<required.length;i++) {
        var required[i] = $('#'+required[i]).attr('value');

This will create the variables i want, how to use them?

HOPEFULLY, you guys can help me!!! Thank you very much!

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


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

Upvotes: 0

Views: 23070

Answers (3)

Robert
Robert

Reputation: 8767

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'];

function ajaxrequest() {
    var params = {}; // initialize object

    //loop through input array
    for (var i=0; i < required.length; i++) {             
        // set the key/property (input element) for your object
        var 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/

Upvotes: 4

Oliver Gray
Oliver Gray

Reputation: 864

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');
       var val = $(this).val();

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

       obj[key] = val;
}

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

Upvotes: 2

Kalel Wade
Kalel Wade

Reputation: 7792

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'];              

function ajaxrequest() {
  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");
    }
});

}

Upvotes: 1

Related Questions