roland luo
roland luo

Reputation: 1631

how to send dynamic data using ajax

normally, we have a ajax request like:

$.ajax({
    type: 'GET',
    url: "/biboundsoptimization",
    data: {
        objects: '2',
    },
    success: function (data) {
        console.log(data);
        alert(data);
    },
    error: function (data, status, er) {
        alert("error: " + data + " status: " + status + " er:" + er);
    }
});

but now I cannot know the number of variables in the data field . For example, when the client enters 2 the data field should be like:

data: {
    objects1: value of objects1,
    objects2: value of objects2,
},

if the client enters 3 the data field should be like:

data: {
    objects1: value of objects1,
    objects2: value of objects2,
    objects3: value of objects3,
},

Before the ajax request, the client has already entered the value of each objects into different input fields. But i don't know the number until he enters it. So i cannot write as above. it is obvious that a loop is required to get all the objects by looping over the number of loops provided by the client. I tried to something like:

for (int i = 1; i < clientValue; i++) {
    'objects' + i: $('#objects' + i).val(),
}

But it doesn't work. Grammatically it is wrong. Can anyone help me with that? Thanks!

Upvotes: 1

Views: 3081

Answers (5)

monkeyhouse
monkeyhouse

Reputation: 2896

try using the $.each jquery function

var data = {};
$('#objects input').each(function(){
    data.push(this.value);
});

Upvotes: 3

Zubair1
Zubair1

Reputation: 2780

If your data is coming from a FORM.. you can use the jquery serialize function to automatically wrap it all up together for you.

       var formData = $('#yourform').serialize();

you can then do some thing like this in your ajax request

       var request = $.ajax({
            type: 'POST',
            url: 'ajaxHandler.php',
            cache: false,
            data: formData, //all the data is automatically ready for you now
            dataType: 'json'
        });

Upvotes: 2

Didin Sino
Didin Sino

Reputation: 306

add class too all your input and use $.each function

<input id="object1" class="object" />
<input id="object2" class="object" />
var data = {};
var id;
$('.object').each(function(){
   id = $(this).attr('id');
   data[id] = $(this).val();
});

Upvotes: 0

NaYaN
NaYaN

Reputation: 1320

var objects = [];

for(int i = 1; i < clientValue; i++){
       objects[i]: $('#objects' + i).val(),
}

Upvotes: 0

zs2020
zs2020

Reputation: 54551

You can dynamically create the object containing all objects like this:

var dataToPost = {};

for(int i = 1; i < clientValue; i++){
     dataToPost['objects' + i] = $('#objects' + i).val();
}

And then pass in the ajax call like this

data: dataToPost,

Upvotes: 1

Related Questions