SkyeBoniwell
SkyeBoniwell

Reputation: 7112

creating an array and sending to ajax

I'm trying to gather information from all of the textareas on my page, and then put that information into an array so I can send to the server via ajax/json.

Although I am not quite sure how to go about doing it.

I'm not sure how to pull the information I need from the

Here is what I have so far:

Example of my HTML

 "<textarea id='tbObjective_" + counter + "' name='txtObjective' class='objectives' sequence='" + counter + "'></textarea>" 

jQuery:

    var objectiveList = [];
    $('.objectives').each(function (objective) {
        objectiveList.push({
            id: objective.id,
            sequence: objective.sequence,
            text: objective.val()
        });
    });

    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: objectiveList 
    });

Any help would be appreciated

Thanks

Upvotes: 0

Views: 79

Answers (3)

Alok Agarwal
Alok Agarwal

Reputation: 3099

you can proceed with the following procedure. i have used python django and html5 for the purpose

1. make a text box which is hidden and after generating  your json document set it in this text box (suppose id of textbox is "submit_json") than  use
$("#submit_json").val(JSON.stringify(formData, null, '\t')),  // (formData, null, '\t') this is js function that i have written for the ourpose

data = JSON.stringify({"jsonDoc":Generated JSON})

console.log(data);
$.ajax({

url: 'http://127.0.0.1:8000/catchjson/',
type: 'POST',
async: false,
contentType: 'application/json',
data: data,
dataType: 'json',
processData: false,
success: function(data){
alert('Done')
//Goto Next Page

},

error: function(jqXHR, textStatus, errorThrown){
alert("Some Error!")
}
})

Now on server you can catch this json if u have problem creating json from your text box let me know

Upvotes: 2

Rob
Rob

Reputation: 10248

I often use:

var formData = $("form").serialize();

for posting data over ajax, so maybe you could try:

var textareaData = $(".objectives").serialize();

$.ajax({
    type: "POST",
    url: url,
    dataType: "json",
    data: textareaData
});

or alternatively make sure all the fields are in a form element and use the first example.

Upvotes: 1

Robbert
Robbert

Reputation: 345

You can parameterise it with $.param(objectiveList)

see jQuery.param()

Upvotes: 1

Related Questions