Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); ?> 
like image 262
Pieter Avatar asked Mar 12 '12 23:03

Pieter


People also ask

How do I return data after ajax call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

What is success and error function in ajax?

success and Error : A success callback that gets invoked upon successful completion of an Ajax request. A failure callback that gets invoked in case there is any error while making the request.

Why is ajax success not working?

ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.


Video Answer


2 Answers

You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.

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

Additional fix, you should check whether the query succeed 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 it helps.

like image 165
Muhammad Abrar Avatar answered Oct 05 '22 23:10

Muhammad Abrar


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);     } } 
like image 32
Alex Avatar answered Oct 05 '22 22:10

Alex