Skip to content Skip to sidebar Skip to footer

How To Pass Javascript Array To Php File Using Ajax?

I have to pass a Javascript arry to a PHP file while AJAX call. Below is my js array: var myArray = new Array('Saab','Volvo','BMW'); This JS code has to pass JS array to PHP file

Solution 1:

Convert js array in json format by JSON.stringify

functionProcessAJAXRequest()
{
    $.ajax
    ({
        type: "POST",
        url: "myphpfile.php",
        data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)},
        success: function (data) 
        {
            alert(data);
        }
    });
}

And In the PHP use json_decode function to get value in array

json_decode($_POST["myJSArray"]);

Solution 2:

Use JSON.stringify to converts a value to JSON and send it to server.

data: JSON.stringify({"id" : 1, "myJSArray" : myArray})

Solution 3:

You could use JSON.stringify(array) to encode your array in JavaScript, and then use

$array=json_decode($_POST['jsondata']);

in your PHP script to retrieve it.please check this link

Pass Javascript Array -> PHP

Solution 4:

What seems to me is that your array is not available in the function scope:

functionProcessAJAXRequest(){
   var myArray = newArray("Saab","Volvo","BMW"); // this has to be in fn scope
   $.ajax({
      type: "POST",
      url: "myphpfile.php",
      data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)},  // do the stringify before postingsuccess: function (data){
         alert(data);
      }
   });
}

Post a Comment for "How To Pass Javascript Array To Php File Using Ajax?"