[php] How do I return a proper success/error message for JQuery .ajax() using PHP?

I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.

The client side:

<script type="text/javascript">
  $(function() {
    $("form#subsribe_form").submit(function() {
      var email = $("#email").val();

      $.ajax({
        url: "subscribe.php",
        type: "POST",
        data: {email: email},
        dataType: "json",
        success: function() {
          alert("Thank you for subscribing!");
        },
        error: function() {
          alert("There was an error. Try again please!");
        }
      });
      return false;
    });
  });
</script>

The server side:

<?php 
$user="username";
$password="password";
$database="database";

mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");

$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";

if($senderEmail != "")
    $query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();

$response_array['status'] = 'success';    

echo json_encode($response_array);
?>

This question is related to php jquery html ajax

The answer is


I had the same issue. My problem was that my header type wasn't set properly.

I just added this before my json echo

header('Content-type: application/json');

...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.

Typically, right mouse->inspect on your html page. Then look in the error console for errors like

Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


In order to build an AJAX webservice, you need TWO files :

  • A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
  • A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)

So, first you call your webservice using this JQuery syntax, in the JavaScript file :

$.ajax({
     url : 'mywebservice.php',
     type : 'POST',
     data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
     dataType : 'json',
     success: function (data) {
          alert("The file is "+data.fichierZIP);
     },
     error: function(data) {
          //console.log(data);
          var responseText=JSON.parse(data.responseText);
          alert("Error(s) while building the ZIP file:\n"+responseText.messages);
     }
});

Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:

<?php
    //...
    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
    //$errors is a string that may contain an error message while preparing the ZIP file
    //In the end, I check if there has been an error, and if so, I return an error object
    //...

    if ($errors==''){
        //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['ZIPFILENAME'] = basename($filename); 
        print json_encode($result);
    } else {
        //if there is an error, you should return a special header, followed by another JSON object
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['messages'] = $errors;
        //feel free to add other information like $result['errorcode']
        die(json_encode($result));
    }
?>

Server side:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

Client side:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

adding to the top answer: here is some sample code from PHP and Jquery:

$("#button").click(function () {
 $.ajax({
            type: "POST",
            url: "handler.php",
            data: dataString,

                success: function(data) {

                  if(data.status == "success"){

                 /* alert("Thank you for subscribing!");*/

                   $(".title").html("");
                    $(".message").html(data.message)
                    .hide().fadeIn(1000, function() {
                        $(".message").append("");
                        }).delay(1000).fadeOut("fast");

                 /*    setTimeout(function() {
                      window.location.href = "myhome.php";
                    }, 2500);*/


                  }
                  else if(data.status == "error"){
                      alert("Error on query!");
                  }




                    }


        });

        return false;
     }
 });

PHP - send custom message / status:

    $response_array['status'] = 'success'; /* match error string in jquery if/else */ 
    $response_array['message'] = 'RFQ Sent!';   /* add custom message */ 
    header('Content-type: application/json');
    echo json_encode($response_array);

Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you're doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.

However, I consider that wrong. HTTP status codes apply to the actual browser<->server connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned 'no rows'. Nothing in that signifies "404 page not found" - the page WAS found.

Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.

e.g. in PHP you'd have

$results = array(
   'error' => false,
   'error_msg' => 'Everything A-OK',
   'data' => array(....results of request here ...)
);
echo json_encode($results);

Then in your client-side code you'd have

if (!data.error) {
   ... got data, do something with it ...
} else {
   ... invoke error handler ...
}

Just so you know, you can use this for debugging. It helped me a lot, and still does

error:function(x,e) {
    if (x.status==0) {
        alert('You are offline!!\n Please Check Your Network.');
    } else if(x.status==404) {
        alert('Requested URL not found.');
    } else if(x.status==500) {
        alert('Internel Server Error.');
    } else if(e=='parsererror') {
        alert('Error.\nParsing JSON Request failed.');
    } else if(e=='timeout'){
        alert('Request Time out.');
    } else {
        alert('Unknow Error.\n'+x.responseText);
    }
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios