How to work with jQuery AJAX and PHP array return

49,300

Solution 1

You will have to return the array encoded in the json form like following

$array = array("a","b","c","d");
echo json_encode($array);

then you can access it in javascript converting it back to an array/object like

var result = eval(retuned_value);

You can also navigate through all array elements using a for loop

for (var index in result){
    // you can show both index and value to know how the array is indexed in javascript (but it should be the same way it was in the php script)
    alert("index:" + index + "\n value" + result[index]);
}

in your code it should look something like:

PHP Code:

$array = array("a","b","c","d");
echo json_encode( $array );

jQuery script

$.ajax({
    type: 'POST',
    url: 'processor.php',
    data: 'data1=testdata1&data2=testdata2&data3=testdata3',
    cache: false,
    success: function(result) {
      if(result){
        resultObj = eval (result);
        alert( resultObj );
      }else{
        alert("error");
      }
    }
});

Solution 2

Return JSON from php http://php.net/manual/en/function.json-encode.php

and in javascript create an object from the json string, you can do this with using getJSON instead of ajax http://api.jquery.com/jQuery.getJSON/

Make sure your php sets the right response header:

 header ("content-type: application/json; charset=utf-8");

Solution 3

I find the best way to return an array from php to Ajax (jscript):

on the php side: echo json_encode($myArray); on the javascript side (e.g. myAjax.responseText) replyVal = JSON.parse(myAjax.responseText);

To send arrays TO php from javascript, use the matching JSON.stringify() to send and php json_decode() to receive

Solution 4

In your PHP code encode the array as JSON object

echo json_encode($array);

Then you need to convert the JSON object into a Javascript/jQuery-compatible object. Afterwards you can convert back to an array

$.ajax({
      success: function(result) {

      jq_json_obj = $.parseJSON(result); //Convert the JSON object to jQuery-compatible

      if(typeof jq_json_obj == 'object'){ //Test if variable is a [JSON] object
        jq_obj = eval (jq_json_obj); 

        //Convert back to an array
        jq_array = [];
        for(elem in jq_obj){
            jq_array.push(jq_obj[elem]);
        }
        console.log(jq_array);
      }else{
        console.log("Error occurred!"); 
      }
    }
});
Share:
49,300
Alfred
Author by

Alfred

I am a Full Stack developer and a DevOps Engineer, who always to learn from, and contribute to, the technology community. I was a beginner in programming once. What all I had was pieces of scattered and crude knowledge (don't know if i can call it knowledge) then. Later, I joined for Master of Computer Applications in a college and there, I got a great teacher. It was her, who taught me when and where to use 'while' and 'for' loops even.What all knowledge I have now, and what all achievements I've made till now, is only because of her. Compared to her, I am ashes. Hats off my dear teacher Sonia Abraham, you are the best of your kind. Sonia Abraham is a professor of the Department of Computer Applications, M.A College of Engineering, Mahatma Gandhi University

Updated on July 19, 2020

Comments

  • Alfred
    Alfred almost 4 years

    I have a jquery ajax request like;

    $.ajax({
        type: 'POST',
        url: 'processor.php',
        data: 'data1=testdata1&data2=testdata2&data3=testdata3',
        cache: false,
        success: function(result) {
          if(result){
            alert(result);
          }else{
            alert("error");
          }
        }
    });
    

    The handler processor.php is set to return an array like;

    $array = array("a","b","c","d");
    echo $array;
    

    I want to do action in client side based on this. Say if array[0] is 'b', I want to alert "hi". Again if array[2] is 'x', I want to alert "hello", and so on. How can I filter array elements in order to grab their data?

  • Ram
    Ram about 11 years
    -1 No need to use eval.
  • Janaka R Rajapaksha
    Janaka R Rajapaksha about 10 years
    i got it worked with eval but not worked without eval. also my php script didnt set to any specific header like HMR says on below answer.