简体   繁体   中英

conditionally parse data returned to ajax call

I'm trying to return associative array to an ajax success method from a php what I'm doing is something like this

if(!empty($error)){
$rs = json_encode(array(
  'TYPE' => '0',
  'ERROR' => "<h5> Opps there was some error(s) </h5> " . $error 
  
));
    print_r($rs);

}

I'm encoding them in my php and parsing them in my ajax like this :

   $.ajax({
        url: url,
        method: "POST",
        data: {name,age,id,submit},          
        success: function (data) { 
            var rs = JSON.parse(data);
            if (rs['TYPE'] == '0') {
                $('.alert').html(rs['ERROR']).show("slow");
            } else {
                console.log(rs);

            }
            
        },
        fail: function (jqXHR, textStatus) {
            alert("Request failed: " + textStatus);
        },
        error: function (xhr, status, error) {
            alert("error" + error)
        }
    });

but when i have a different type of data that i don't want to parse , how can i do that because parsing them throws some uncaught errors my data type is a data retrieved from mysql data base and if im getting them with parsing this error pops up : Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 2 of the JSON data without parsing it works fine here is my php mysql data :

include 'connection.php';
  $sql = "Select * from user";
  if ($result = mysqli_query($link, $sql)) {
    while ($row =  mysqli_fetch_assoc($result)) {

      $output [] =  $row["id"] .":". $row["name"];
    }
}
mysqli_close($link);
header('Content-Type: application/json');
print_r( json_encode($output));

what i want to return from my php is an associative array that has 2 or more keys something like

array( 'error' => 'there was some errors '.$error , 'type' => '0' );

and i want to be able to access them back in my javascript and the type off the data i'm getting back and conditionally parse them or not some thing like this :

success : function(data) {
       if(data['TYPE'] == '0'){ JSON.parse(data) //rest of my code } else{// my rest of code }
   }

but i seem i'm not able to access the returned data by keys before i can parse them

I'm sorry but i'm still a beginner and highly would appreciate any sort of help , thanks in advance

print_r is intended as a debugging tool only. It's inappropriate to use it to output your JSON in the normal course of your script. It adds extra formatting and thus will make the JSON invalid, and un-parseable by the JavaScript code.

Just use echo instead, as per the standard way to output from PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM