Fabio97 Fabio97 - 3 months ago 6
jQuery Question

How to pass simple array to ajax request?

I've got the following code:

$("form").submit(function(e) {
e.preventDefault();
var ris = new Array();
for (var j = 0; j <= i; j++)
ris[j] = [($("[name=ris" + j + "]").val())];
$.ajax({
url: "crea_sondaggio.php",
type: "POST",
data: JSON.stringify({
ris: ris
}),
});
});


with this array:

var ris = new Array();
for (var j = 0; j <= i; j++)
ris[j] = [($("[name=ris" + j + "]").val())];


and I want to send it to Ajax. Is it right:

data: JSON.stringify({
ris: ris
}),


How can I fix?

UPDATE

js/php

<form action="crea_sondaggio.php" method="post">
...other code here....
</form>
$("form").submit(function(e) {
var ris = new Array();
for (var j=0; j<=i; j++)
ris[j] = [($("[name=ris"+j+"]").val())];
$.ajax({
url: "crea_sondaggio.php",
type: "POST",
data: {ris: JSON.stringify(ris)},
dataType: "html",
success: function() {
alert("OK");
},
error: function(err, msg) {
alert ("Chiamata fallita " + msg);
}
});
});


crea_sondaggio.php

$ris = $_POST['ris'];
echo $ris;


But page crea_sondaggio.php is empty and it doesn't appear the output $ris. How can I fix?

Answer

To save all the values of input textboxes in array please use below code.

$(document).ready(function() {
    var ris = new Array();
    $("input[name^='ris']").each(function() {
        ris.push($(this).val());
    });
});

JSON.stringify for array and pass that in the request parameter.

data: {
  ris: JSON.stringify(ris)
},