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?
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:
$array = array("a","b","c","d");
echo json_encode( $array );
$.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");
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With