Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Why not to calculate the count on client side ? –  KutePHP Apr 1 at 11:31
    
i dont see that var in your function scope. –  Jai Apr 1 at 11:33
    
your code is perfectly fine. I am getting count 3 without any change. I am not getting any error. using PHP 5.3 –  Neeraj Singh Apr 1 at 11:45
add comment

4 Answers

up vote 2 down vote accepted

Convert js array in json format by JSON.stringify

function ProcessAJAXRequest()
{
    $.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"]);
share|improve this answer
add comment

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

data: JSON.stringify({"id" : 1, "myJSArray" : myArray})
share|improve this answer
add comment

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

share|improve this answer
add comment

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

function ProcessAJAXRequest(){
   var myArray = new Array("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 posting
      success: function (data){
         alert(data);
      }
   });
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.