Skip to content Skip to sidebar Skip to footer

How Can I Return An Array And Html Data In An Ajax Response?

I have an array like this in my PHP page named new1.php: $arr = ['value 1', 'value 2', 'value 3']; $html = '
huge data with all tags like a page
'; $response =

Solution 1:

from your php code where you do json_encode add this to the top of the page header("Content-Type: application/json"); then your encode should take in array as parameter instead

json_encode(array("array"=>$arr, "html"=>$html));

it should see your record as json now and please change ur dataType to json from Jquery intelligence guess from the server state (jquery) it will automatically take json instead

dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

Solution 2:

You should be json parse, because you are json encoding from php file, and as there is data type of your ajax is text so you need to parse the json.

 $.ajax({
         url:"new1.php",
         type:"POST",
         data:{somedata:somedata},
         dataType:"text",
         success: function(data){
                data = JSON.parse(data);
                  console.log(data);
                console.log(data.html);
                console.log(data.array);

            }
    });

Post a Comment for "How Can I Return An Array And Html Data In An Ajax Response?"