I've tried the fixes for similar questions but nothing has worked for me.
Trying to send an array to PHP via AJAX when my submit button is pressed.
In the PHP file I get the error - Notice: Undefined index: data
HTML
<form id="email-form" action="add-user.php" method="post">
...
</form>
Javascript
var frm = $('#email-form');
frm.submit(function (ev) {
var cars = ["Saab", "Volvo", "BMW"]; //this is the array i want to send for purposes of this question
var jsonString = JSON.stringify(cars);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: {'data': jsonString},
success: function () {
alert('ok');
}
});
});
PHP (add-user.php)
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
Get same error when trying- data: {data: jsonString}
console.log(jsonString) shows me the array so I know it exists.
Any ideas as to what is causing undefined index error? Thanks in advance.
var_dump($_POST['data'])and see what's coming through. And note that if you DON'T have magic_quotes enabled, thestripslashes()will be highly likely to corrupt the JSON text by removing escape slashes that are required by the JSON syntax rules.{data : jsonString}(note that I am removing the quotations around your data parameter) or'data='+ jsonStringin your ajax. Then do aprint_r($_POST)in your php. What does that tell you?stripslashes()should not be used in this case. Like Marc said, that will just likely create problems for you. Might not affect your code.. but I would suggest seperating the names of your paramaters (data, for instance) from the paramters that are native of the method you are using ($.ajax() also uses a paramater called data). Just makes it clearer!