Home:ALL Converter>How to pass Javascript array to PHP file using AJAX?

How to pass Javascript array to PHP file using AJAX?

Ask Time:2014-04-01T19:27:57         Author:user1556433

Json Formatter

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 using AJAX request and will show count of array.

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

This myphpfile.php file has to return the count of the array

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

There is error in PHP file. I am getting undefined index: myPHPArray. How should acheive my required functionality?

Author:user1556433,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/22784515/how-to-pass-javascript-array-to-php-file-using-ajax
yy