Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment (requires an account with 50 reputation)

2 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");
      }
    }
});
share|improve this answer
-1 No need to use eval. – undefined Mar 9 at 14:02
add comment (requires an account with 50 reputation)

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");
share|improve this answer
add comment (requires an account with 50 reputation)

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.