1

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:\xampp\htdocs\project\yep.php on line 18
NULL

Why is it returning null for array?

11
  • 3
    You've shown 4 lines of PHP code, but indicated that the error is on line 18. Commented Feb 5, 2020 at 17:39
  • 1
    maybe you should try to debug your code by yourself first ; why var_dump on $myArray and not on $_POST ? maybe your js array is never posted Commented Feb 5, 2020 at 17:46
  • your javascript code and php code is in same file? if yes then put your php code into some check like if(isset($_POST['cars'])){ $myArray = $_POST['cars']; var_dump($myArray); die;} Commented Feb 5, 2020 at 17:50
  • @uditrawat I have putted that in code and then it only gave success message and nothing else means the if condition was false, so somehow js array wasn't send to php Commented Feb 5, 2020 at 18:12
  • @GregSchmidt l have not posted html and head tags. I have wrote all this code in one file yep.php line 18 is $myArray = $_POST['cars']; Commented Feb 5, 2020 at 18:18

3 Answers 3

2

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.

<input type="button" name="button" value="submit">

  <script>      
  var cars = ["Saab", "Volvo", "BMW"];
  $('input[type=button]').click({
      $.ajax({ 
   type: "POST", 
   url: "yep.php", 
   data: { 'cars' : cars}, 
   success: function(data) { 
          alert("Success");
          console.log(data);
          $("body").empty().html('Ajax Response:<br />'+data);
    } 
   }); 
  })
  </script>

 <?php
     $myArray = $_POST['cars'];
     var_dump($myArray);
 ?>` 
Sign up to request clarification or add additional context in comments.

7 Comments

Its not working, its not even giving alert so probably array is not passed from js to php its giving output as Notice: Undefined index: cars in C:\xampp\htdocs\project\firstprogram.php on line 26 which is $myArray = $_POST['cars']; NULL
<html> <head> <script src="ajax.googleapis.com/ajax/libs/jquery/3.4.1/…> </head> <script> var cars = ["Saab", "Volvo", "BMW"]; $.ajax({ type: "POST", url: "yep.php", data: { 'cars' : cars}, success: function() { alert("Success"); } }); </script> </html> <?php $myArray = $_POST['cars']; var_dump($myArray); ?>
@Amateur the code provided in this response is correct, you on the other hand are showing an error from another file, firstprogram.php. If you want the cars to be available in firstprogram.php you must include that file in yep.php. FYI PHP is executed ONCE(per request) and everything included in the main file is processed in a synchronous matter.
@Amateur var_dump($myArray) won't appear in your browser window. To see the output, open Developer Tools from your browser, select the Network tab, click on the request to /yep.php and then click the Response tab
@darklightcode if i want to print it on screen using php then what can I do? usually isn't var_dump() used to print on screen?
|
1

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:

<script>      
  var cars = {};
  cars['value1'] = 'Value 1';
  cars['value2'] = 'Value 2';
  cars['value3'] = 'Value 3';

  $.ajax({ 
  type: "POST", 
  url: "yep.php", 
  data: { cars : cars}, 
  success: function(data) { 
      console.log(data); 
  } 
 }); 
</script>

But your case is simple, just do it like this in your data:

<script>      
  var cars = ["Saab", "Volvo", "BMW"];

  $.ajax({ 
  type: "POST", 
  url: "yep.php", 
  data: { cars : cars}, 
  success: function(data) { 
      console.log(data); 
  } 
 }); 
</script>

The first one is the direct method, but this one is the JSON method.

in jquery first do this...

var array_fields = ["Saab", "Volvo", "BMW"];
var cars = JSON.stringify( array_fields );

Then In PHP do this...

$myArray = json_decode($_POST['cars']);
print_r($myArray);

1 Comment

$myArray = $_POST['cars']; use this instead and check print_r($myArray);
1

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:

success: function(data) { 
          alert(data); 
    } 

This will show what is being returned from the ajax call. From the jQuery.ajax doc:

success

Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server,.....

In the php:

<?php 
  if (!isset($_POST['cars'])) {
      echo "Wait for it";
      } 
  else {
      $myArray = $_POST['cars']; var_dump($myArray);
      } 
  ?>

Now you will notice

  1. That Wait for it is displayed in the browser, instead of the error message
  2. In the alert box you will see the entire output of yep.php is being returned. Scroll down to see the data as 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.

2 Comments

After making above changes it is showing whole code except php part in alert message. Split this into two scripts that means make two files, one with .html extension and one with .php extension I did, but after that on opening html file it was blank, in browser console>Network>yep.php it showed Failed to load response data
I copied the code from a comment posted above. I had to change the <script> line for jquery to this <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>. With the exception of that line, I split the exact code into an html (yep.html) and a php (yep.php). I browsed to yep.html in Firefox. And got expected response data. Local web server is IIS. Opening the html file will be blank, there's nothing to render. Did you check browser console for errors?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.