0

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?

1

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.