user756659
user756659

Reputation: 3512

ajax response error not working as expected

My success/error handling is not working as expected. In this example my php runs as intended, however, the intent of the processing failed. Let's say I was looking up a username in the database... if I found the username I would return $ajax_result['success'] = 'success';, but if I did not find the username I would return nothing. The success call works fine, but the error call is not firing.

The error in firebug I am getting is TypeError: response is null and therefore the error alert I have set does not fire.

What is the best way to solve this without actually returning $ajax_result['success'] = 'whatever';

example return from php would be something like this when processing went as expected:

$ajax_result['success'] = 'success'; // add success info
echo json_encode($ajax_result); // return result array to ajax

for 'errors' I am simply returning :

echo json_encode($ajax_result); // which is null in this case

the ajax:

var showInfo = function() {
    $('#show-user').on('click', function () {
        var $form = $(this).closest('form');
        $.ajax({
            type: 'post',
            url: '/spc_admin/process/p_delete_user_show.php',
            data: $form.serialize(),
            dataType : 'json'
        }).done(function (response) {
            if (response.success == 'success') {            
                alert('success');              
            } 
            else 
            {
                alert('error');
            }
        });
    });

}

Upvotes: 0

Views: 117

Answers (2)

Jite
Jite

Reputation: 5847

You can not json_encode a null value, easiest and cleanest way to make this work would probably be to make success a bool and set it to either true or false depending on if it succeeded or not (This is ususaly what most user expects a 'success' or 'result' parameter in response to be, not a string).

//PHP:
header('Content-Type: application/json'); // To let the client know that its json-data.
$ajax_result['success'] = $wasSuccessfull; // true or false
die(json_encode($ajax_result)); // Exit the script with the json response.


//JavaScript:
if (response.success) {            
  alert('success');              
} else {
  alert('error');
}

Upvotes: 1

user2678106
user2678106

Reputation:

try this one:

  if (!response.success) {            
        alert('error');              
  } 
  else 
  {
        alert('success');
  }

Upvotes: 0

Related Questions