0

I'm trying to pass an array from .js file to a PHP page using ajax post method. would you help me to understand why it is not working?

//js file
$.ajax({
       type: "POST",
       url: "http://localhost/Project_part3/includes/graph.php",
       datatype: 'JSON',
       data: {'data1' : JSON.stringify(data1)},
       success: function(data){
        console.log("success:", data1);
    },
       failure: function(errMsg) {
        console.error("error:",errMsg);
       }
    });

//PHP page
<?php
  $data1 = json_encode($_POST["data1"]);
  var_dump ($_POST["data1"]);
?>
4
  • 4
    How do you know it is not working? Have you watched the request/response in the browser's developer tools? Have you checked the console for errors? Commented Apr 4, 2019 at 16:22
  • Shouldn't the PHP json_decode to turn the string into an array? Commented Apr 4, 2019 at 16:23
  • @NasimKhaloo, Harvey has right you are sending an string not an array check his answer Commented Apr 4, 2019 at 16:41
  • check console.log("success:", data); <== not data1 to see the var_dump Commented Apr 4, 2019 at 17:50

1 Answer 1

1

If your data1 array in your JS is already a javascript array, you don't need to do JSON.stringify() as this is making it into a string.

You will now be able to just do data: data1

var data1 = {
        yourKey1: "yourValue",
        yourKey2: "moreStuff"
    };

$.ajax({
   type: "POST",
   url: "http://localhost/Project_part3/includes/graph.php",
   datatype: 'JSON',
   data: data1,
   success: function(data){
    console.log("success:", data1);
},
   failure: function(errMsg) {
    console.error("error:",errMsg);
   }
});
Sign up to request clarification or add additional context in comments.

Comments

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.