Bojangles
Bojangles

Reputation: 101483

PHP trigger AJAX error code without using array

I want to be able to get a PHP script called via AJAX to return with an error code that the jQuery AJAX handler error: will handle. I don't want to use a JSON array - I'd like to keep it as clean as possible. Can someone point me in the right direction?

Thanks,

James

Upvotes: 4

Views: 4924

Answers (4)

Regis Zaleman
Regis Zaleman

Reputation: 3240

EDIT: jQuery'ajax'statusCode' method works, but only in jQuery 1.5

I have tried jquery's ajax's 'statusCode' method, works now, with jquery 1.5 but did not get any results... but it should be the way to go...

if my php script does this:

 //localhost/dev/false.php
 header("HTTP/1.0 404 Not Found");  
 exit();

and my javascript does that:

$.ajax({
  url:'http://localhost/dev/false.php',
  statusCode: {
                  404: function() {
                      alert('page not found');
                  }
              }
          });

Upvotes: 0

Groovetrain
Groovetrain

Reputation: 3325

If you want to trigger the AJAX error handler, just pass back something other than a 200! Try this:

<?php
  header("HTTP/1.0 404 Not Found");
  exit();
?>

Just remember to do two things:

  1. Try to send the correct error code to comply with HTTP methods. i.e. if you page throws an error, then you should return a 500, etc. You can see a reference here at the w3.org site.
  2. Make sure you send the header before ANY other content except whitespace.

This should be the clean solution you are going for.

Upvotes: 13

Scott Saunders
Scott Saunders

Reputation: 30394

Try this:

header("HTTP/1.0 404 Not Found");
exit();

Upvotes: 2

Elzo Valugi
Elzo Valugi

Reputation: 27866

Ajax transmission does not have to be JSON. It can be xml, json, script, or html. By default AJAX uses XML (the X from AJAX stands for that). I see that you are using jQuery. If you are using ajax method you have a dataType parameter that you can modify.

As you speak of it JSON is one of cleanest in my opinion, but if you mean simple you can use text instead.

Upvotes: 1

Related Questions