user1547007
user1547007

Reputation: 267

Get server response after ajax post submission

How do i pass my server side validation to my ajax post methods?, I am trying to get the server http response from the server and based on that thrown success/error messages on the client, current php code is:

$error = 0;

    if($_SERVER["REQUEST_METHOD"] == "POST") {
      if ($condition) {
        //error code
        $error = 0;
      } elseif ($othercondition) {
        //success code
        $error = 1;
      } else {
        //error code
        $error = 0;
      }
    }

and my ajax post looks like

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,         
        })
        .done(function(response) {
            console.log("success " + response);
            //if (condition) {
              //# code...
            //} else {
              //# code...
            //}
        })
        .fail(function(response) {
            console.log("error " + response);
        })
        .always(function() {
            console.log("complete");
        });

Upvotes: 0

Views: 922

Answers (1)

Barmar
Barmar

Reputation: 782148

The server needs to do:

echo $error;

Whatever the PHP script outputs will be in response in the Javascript.

If you want more details, you can use JSON, e.g.

echo json_encode(array('error' => $error, 'message' => $message_string));

Then in the $.ajax options specify

dataType: 'json',

response will then be a Javascript object; response.error will be the error value, response.message will be the string.

Upvotes: 1

Related Questions