Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery response from post

Problem I have.... I have listener script in php that does this:

  if ($count != 1) {echo 'no';} else { echo "yes";}

So it echoes "yes" or "no" depending if task was success or not and on my page I have this:

   jConfirm('Are you sure you want to delete this publisher?', 'Delete publisher', function (r) {
    if (r) $.post('includes/publishers/delete-publisher.php?publisherid=' + publisherid, 
    function(data) {
            if (data == 'no') {
            $.jGrowl('Error - PUBLISHER WAS ALREDY DELETED !');
            alert("Data Loaded: " + data);
            } else {
            $(element).parents('tr').remove();
            $.jGrowl('Publisher deleted');       
            alert("Data Loaded: " + data);
            }
        });
});

And the problem is that ALTHOUGH delete-publisher.php echoes "no" (I see it echoed in alert box) - JQuery is always processing this as if response was "yes" !? Am I missing something obvious ?

like image 559
Peter Avatar asked Jul 05 '26 00:07

Peter


2 Answers

Save yourself a lot of headaches and use JSON to send responses back to your javascript. do something like this (untested):

PHP Side:

header('Content-type: application/json');
if ($count != 1) {
    echo json_encode(array('success'=>false));
} else { 
    echo json_encode(array('success'=>true))
}

JS Side:

jConfirm('Are you sure you want to delete this publisher?', 'Delete publisher', function (r) {
if (r) $.post('includes/publishers/delete-publisher.php?publisherid=' + publisherid, 
function(data) {
        if (data.success == false) {
            $.jGrowl('Error - PUBLISHER WAS ALREDY DELETED !');
            alert("Data Loaded: " + data);
        } else {
            $(element).parents('tr').remove();
            $.jGrowl('Publisher deleted');       
            alert("Data Loaded: " + data);
        }
    }, 'json');

});

This way you can pass error messages back to the JS too.

You should also get used to using something like Firebug for Firefox so you can look into the details of the network traffic, and post parameters, response headers, etc, set JS breakpoints to help debug.

like image 127
Levi Avatar answered Jul 06 '26 15:07

Levi


Likely there's some whitespace in your response. Try using this instead:

if ($.trim(data) == 'no') {
like image 36
Travesty3 Avatar answered Jul 06 '26 15:07

Travesty3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!