Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with jQuery AJAX and PHP array return [duplicate]

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?

like image 348
Alfred Avatar asked Mar 09 '13 13:03

Alfred


1 Answers

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");
      }
    }
});
like image 172
Abu Romaïssae Avatar answered Oct 14 '22 03:10

Abu Romaïssae