Friday, 4 April 2014

How to pass a Javascript Array to PHP file using AJAX and JSON?

How to pass a Javascript Array to PHP file using AJAX and JSON?

I have an array in javascript and I need to pass this array to a PHP by using AJAX call to that PHP file. I will get this array in PHP file and assign this javascript array to PHP array. Then I will find out the count of that PHP array elements and return it back to the javascript. I will convert JS array in JSON format by JSON.stringify. This is a very simple example on how to pass javascript array to PHP asynchronously. You can perform a lot of operations on this array which you have passed to PHP file but for simplicity I am just returning its count. Let's have a look at the following code snippet.

Javascript Array

var myJSArray = new Array("Saab","Volvo","BMW");

ProcessAJAXRequest() function wil pass JS array to PHP file using AJAX request and will show count of array elements returned by PHP file.

function ProcessAJAXRequest()
        type: "POST",
        url: "myphpfile.php",
        data: {"myJSArray" : JSON.stringify(myJSArray)},
        success: function (data) 
            alert(data); //count of array elements


    $myPHPArray = json_decode($_POST["myJSArray"]);
    echo count($myPHPArray);


  1. Play the Best Free Games! We've picked out the racing games, cooking games, candy crush, games shooting, fashion games, ...
    Thanks for sharing !
    Kizi 200
    Friv 1

  2. I Discovered Many new things from your article. Thank you for this!

  3. Please visit our website and play exciting games,thank you verry much
    Friv 2|
    Friv 1000|

  4. You'd have time to look these kids active. Please visit our website and let us play the games interesting.
    Thanks you for sharing !
    Friv 100
    Friv 8
    Friv 2

  5. You want to relax after a stressful working hours. Refer to our website. Hope you get the most comfort.
    Thanks for sharing !
    Kizi 100

  6. Free gaming, the best free online games for you
    Friv 2/
    Friv 4