user1735120
user1735120

Reputation: 489

Ajax not working if PHP is not returning a json_encoded format

I have this php that returns an array if an error is triggered, else, it returns a <DIV>

if(!empty($error)) {
   $true = true;
   $res = array('info' => '$error', 'error' => '$true');

   echo json_encode($res);
   die();

} else {
   // no error
   echo "<div> no error </div>";

}

I think my problem lies in the dataType:json parameter because it expects JSON_ENCODED format? I just want to append the <DIV> (non json_encoded) if the else condition is met.

$.ajax
  ({
    type        : 'POST', 
    url         : 'submitForm.php',
    data        : formData,
    dataType    : 'json',
    success     : function(data) {

    if(data.error == true) {
        console.log(data.info); //display error
      } else {
        console.log(data);
        //some jquery to append the <div>
    }
  }
})

Checking the headers appears to be okay, and the preview tab, returns the <DIV> data

Request Method:POST
Status Code:200 OK

But its not appending, Nor the <DIV> being shown in console.log.

Is there a way i could disable the dataType if a certain PHP condition is met? OR, a proper way of handling json_encoded along side with non json_encoded format in the same PHP file?

Upvotes: 0

Views: 55

Answers (2)

plonknimbuzz
plonknimbuzz

Reputation: 2664

just return your html using json too

PHP

if(!empty($error)) {
   $true = true;
   $res = array('info' => $error, 'error' => $true);
} else {
   // no error
   $res = array('html'=>"<div> no error </div>");
}
echo json_encode($res);

HTML

$.ajax
  ({
    type        : 'POST', 
    url         : 'submitForm.php',
    data        : formData,
    dataType    : 'json',
    success     : function(data) {

    if(data.error == true) {
        console.log(data.info); //display error
      } else {
        console.log(data);
        $('div').append(data.html);
    }
  }
})

Upvotes: 1

bitifet
bitifet

Reputation: 3659

Using json for errors and html (or pseudo html) for regular responses struggles a bit to me.

That being said, if you really want to do that, you obviously can't use dataType: 'json' option because this instructs $.ajax() to expect (and parse) json data so, if what is received is not a valid json string, then an exception will be thrown.

But anyway you can emulate it by parsing json data yourself. For example:

dataType: "text",
success: function(data) {
    try {
        data = JSON.parse(data);
        if (! data.error) { // What if you send json witout error flag?
            data.error = true;
            data.info = "Received json without error info."
        };
    } catch (e) {
        data = {
            contents: data,
        };
    };

    if (data.error) {
        console.log(data.info);
    } else {
        console.log(data.contents);
        // Or whatever you want to do wit received STRING
},

Upvotes: 0

Related Questions