user1054844
user1054844

Reputation: 972

How to send array in AJAX using JSON

I am fairly new to JS and AJAX, and for some reason I can not send my dynamically generated and read data via AJAX. How do I properly send an array via AJAX to PHP script?

I have tried following the instructions but I can not get the AJAX to send the data. The first try was a complete bust, the second gets error:

Uncaught TypeError: Illegal invocation

but it seems to originate from the JS-library instead of my code (though the code is most probably the reason for it!) and I do not know what to do with it.

    //first thing I tried
    var i = 1, j = 0, cu = [], cu2 = [];
     while (i <= tilit ) {
        cu[j] = document.getElementById("til_nro_"+i);
        console.log(cu[j].value);

        i++;
    }
    var dynamic_account_value = JSON.stringify(cu);


 jQuery.ajax({
        type: "POST",
         url: 'http:mysite.php',
        dataType: 'json', 
        data: { dynamic_account_count:tilit, db:cu , id:id, result:dynamic_account_value
            }
        });



    //2nd thing I tried
    var i = 1, j = 0, cu = [], cu2 = [];
     while (i <= tilit ) {

        cu[j] = document.getElementById("til_nro_"+i);
        cu2.push(JSON.parse(cu[j].value));

        i++;
    }
    var tilinrot_lisa = JSON.stringify(cu2);


     jQuery.ajax({
        type: "POST",
         url: 'http:mysite.php',
        dataType: 'json', 
        data: { dynamic_account_count:tilit, db:cu , id:id, result:tilinrot_lisa
            }
        });

Upvotes: 1

Views: 344

Answers (2)

valar morghulis
valar morghulis

Reputation: 2017

Try this code snippet, Try to send just one variable then go for another & use content type. u can use //console.log(JSON.stringify(cu)); to view what's inside.

jQuery.ajax({
   type: 'post',
   dataType: 'json',
   data: {your_var:JSON.stringify(cu)},
   contentType: "application/json"

});

Upvotes: 0

Chris Caviness
Chris Caviness

Reputation: 586

First, give them something that makes selection easier, like a common class. Second, use jquery serialize

$.ajax({
  url : "foo",
  data : $(".bar").serialize(),
  success : function(response) {}
})

Upvotes: 1

Related Questions