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()
{
    $.ajax
    ({
        type: "POST",
        url: "myphpfile.php",
        data: {"myJSArray" : JSON.stringify(myJSArray)},
        success: function (data) 
        {
            alert(data); //count of array elements
        }
    });
}

myphpfile.php

<?php 
    $myPHPArray = json_decode($_POST["myJSArray"]);
    echo count($myPHPArray);
 ?>

Post a Comment