How to return the correct error / error message for jQuery.ajax () using PHP?

I get an error warning. There is nothing wrong with the MYSQL part, the query is executed, and I see the email addresses in the database.

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> 

On 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); ?> 
+70
jquery html ajax php
Mar 12 2018-12-12T00:
source share
7 answers

You need to specify the correct content type if you are using JSON dataType. Before the json echo, put the correct header.

 <?php header('Content-type: application/json'); echo json_encode($response_array); ?> 

An additional fix, you should check if the request is complete or not.

 if(mysql_query($query)){ $response_array['status'] = 'success'; }else { $response_array['status'] = 'error'; } 

On the client side:

 success: function(data) { if(data.status == 'success'){ alert("Thank you for subscribing!"); }else if(data.status == 'error'){ alert("Error on query!"); } }, 

Hope this helps.

+120
Mar 12 2018-12-12T00:
source share

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); } } 
+31
Mar 12 2018-12-12T00:
source share

Some people recommend using HTTP status codes, but I rather despise this practice. for example, if you run a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.

However, I think this is wrong. HTTP status codes apply to the actual server ↔ server connection. Everything regarding the connection is excellent. The browser made a request, the server called your script handler. script returned "no lines". Nothing in this means that "404 page not found" - the WAS page was found.

Instead, I prefer to breed the HTTP layer from the state of your server-side operations. Instead of simply returning some text to the json string, I always return a JSON data structure that encapsulates the request status and requests the results.

eg. in PHP you will have

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

Then in your client code you will have

 if (!data.error) { ... got data, do something with it ... } else { ... invoke error handler ... } 
+21
Mar 12 '12 at 23:18
source share

To create an AJAX web service, you need two files:

  • Javascript caller sending data as POST (maybe as GET) using jQuery AJAX
  • PHP web service that returns a JSON object (it is convenient to return arrays or a large amount of data).

So, first you call your web service using this jQuery syntax in your 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 at the end in order to return the 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)); } ?> 
+7
Nov 28 '16 at 23:16
source share

adding to the top answer: here is a 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 user 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); 
0
Apr 20 '15 at 14:17
source share

I had the same problem. My problem was that my header type was not set correctly.

I just added this before my JSON echo

 header('Content-type: application/json'); 
0
Apr 13 '18 at 17:24
source share

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!"); } 
0
May 23 '19 at 20:31
source share



All Articles