简体   繁体   中英

How to check the returned data from php file from ajax request?

I send a post request to a php file with some data:

function addNewPost(){
    $.post('create_post.php', {},
        function(data){
            if(data != 'OK'){
                $('.errorMsg').html(data);
            }else{
                alert('Well Done! Post Is Added Successfully');
            }
         },
    );
}

$(document).on("click",'#create', addNewPost);

The php file connects the DB and insert data to the Database, And if the data is inserted successfully the file returns OK :

$st = $conn->prepare('INSERT INTO  posts() VALUES(?, ?, ?, ?, ?)');
$st->execute(); 
if ($st) {
    echo 'OK';
}

It returns OK, But it's added to the errorMsg element, So the if condition is executed although the returned data = OK .

Also I tried:

if(data == 'OK'){
    alert('Success');
}else{
    $('.errorMsg').html(data);
}

But didn't work neither.

What's wrong? Should I set specific dataType? Should I replace echo with return ?

You can do as:

if ($st) {
        echo 'OK';exit;
   }else{
    echo false;exit;
   }

or try this:

if ($st) {
        echo json_encode(array("message"=>"OK"));exit;
   }else{
    echo json_encode(array("message"=>false));exit;
   }

in js file:

var jsonResp = $.parseJSON(data);
if(jsonResp.message == 'OK'){
    alert('Success');
}else{
  // else case
}

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