Here is the JavaScript code:
<script>
var cars = ["Saab", "Volvo", "BMW"];
$.ajax({
type: "POST",
url: "yep.php",
data: { 'cars' : cars},
success: function() {
alert("Success");
}
});
</script>
Here is the PHP code:
<?php
$myArray = $_POST['cars'];
var_dump($myArray);
?>`
It is displaying success message, so it means array was passed to php
then it shows:
Notice: Undefined index: cars in C:xampphtdocsprojectyep.php on line 18
NULL
Why is it returning null for array?
3
Answers
Lets say you a bunch of data and you want to submit all once, then you need to create and empty object and append values to it. This will be the case, if for some reasons you don’t want to use
var form = new FormData(this.form);
For example:
But your case is simple, just do it like this in your
data:
The first one is the direct method, but this one is the JSON method.
in jquery first do this…
Then In PHP do this…
I think you are not firing any event like click event, try this code and let me know is it working or not for you.
The error message comes before the script is even executed! Suggest two small changes so you can see what’s going on.
In the script:
This will show what is being returned from the ajax call. From the jQuery.ajax doc:
In the php:
Now you will notice
Wait for it
is displayed in the browser, instead of the errormessage
yep.php
is being returned. Scroll down to see the dataas you expect.
IMO the place to start is to split this into two scripts. The first an html that does not include the php. The second, the php that will be requested from the script.