user3049377
user3049377

Reputation:

Return an error to Ajax from PHP

I have a simple Javascript funcion:

function checkParams()
{
  $.ajax(
  {
    url: 'login.php',
    type: "GET",
    contentType: false,
    cache: false,
    processData: false,
    async: true,
    data: 
    {
      user: $("#user").val(),
      pass: $("#pass").val()
    },
    success: function(data)
    {
      $("#mydiv").load("loader.php");
    },
    error: function()
    {
      $("#mydiv").load("index.php");
    }
  }); 
}

And A simple PHP function which checks for the right user & pass string and I should return an error condition if something fails..

I found examples where it's suggested to do something like:

function foo()
{
  /* code ... */

  /*error condition */
  echo "error";
}

But honestly, it's not working..

How can I tell to ajax, from PHP, that I want ro return an 'error condition' ?

Upvotes: 2

Views: 47

Answers (2)

Daniel PurPur
Daniel PurPur

Reputation: 529

In this bit of code change to RETURN SOMETHING

success: function(data)
{
  return true;
},
error: function()
{
  return false;
}

basically $result = your ajax return;

if ($result)
    {
        header('Content-Type: application/json');
    }
else
    {
        header('HTTP/1.1 500 Internal Server Yourserver');
        header('Content-Type: application/json; charset=UTF-8');
        die(json_encode(array('message' => 'ERROR', 'code' => 'whatever you want to call it')));
    }

Upvotes: 0

jbafford
jbafford

Reputation: 5668

The jQuery.ajax() error handler only fires when the HTTP status result indicates an error; that is, the page returns a 4xx or 5xx status code.

You can do one of the two following options:

1) Set the status code with header('HTTP/1.0 400 Bad Request') (or any other relevant HTTP status code) before you echo "error".

2) Rather than using an error status, have both your success and failure conditions emit an array, converted to JSON withjson_encode(), that is then decoded in your javascript and processed into a success or failure as appropriate in your success function.

Upvotes: 3

Related Questions