Monday, July 6, 2015

How to work with jQuery AJAX and PHP array return



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!"); 
      }
    }
});

No comments:

Post a Comment