How to Return a Proper Success/Error Message for Jquery .Ajax() Using PHP

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

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.

AJAX: How to send back a success/error message

I would recommend returning JSON from your PHP code, this can be interpreted directly as an object in the JavaScript if you use dataType: 'json' on your ajax call. For example:

if ($conn->query($query) === TRUE) {
echo json_encode(array('success' => true));
} else {
echo json_encode(array('success' => false,
'message' => "Error: Insert query failed"
)
);
}

Note that in general it's not secure to pass back query details and connection errors to the end user, better to pass back a generic message and log the actual error to a file or other location.

In your JavaScript:

$("a.bgbtb").click(function(){
var btnid = $(this).attr("id").split('newbudbtn-')[1];
var newbudget = $("INPUT[id=newbud-"+btnid+"]").val();
var platform = $("span#"+btnid).text();
$.ajax({
url:"campbdgtedit.php",
method:"POST",
data:{platform:platform, btnid:btnid, newbudget:newbudget},
dataType: 'json',
success:function(data){
if (data.success) {
// all good!
myAlertTop();
}
else {
// problems
alert(data.message);
}
}
});
});

Return success/failure variable with ajax from php script

The $.ajax error function gets called when there is a connection error or the requested page cannot be found

You have to print some text out with the php and the ajax success function gets this output. Then you parse this output to see how it went.

The best practice is this:

php part:

$response = array();
$response['success'] = $success;
$response['general_message'] = $message;
$response['errors'] = $errors;
exit(json_encode($response));

js/html part:

$.post("yourpage.php", a , function (data) {
response = JSON.parse(data);
if(response['success']){
//handle success here
}else{
//handle errors here with response["errors"] as error messages
}
});

Good luck with your project

Returning AJAX Success and Error

You have spaces after ?>

So, the AJAX response is having spaces after true.

Solution:

Remove ?> from the end of PHP file.

It will not affect any PHP functionality.

And you AJAX response will be without spaces.

Excluding closing tag ?> from the end of PHP file is standard practice for modern PHP frameworks and CMSs.

Tips for debugging AJAX:

1) Always use Firefox (with Firebug Add) on Or Chrome.

2) Use Console tab of Firebug, to check which AJAX requests are going.

3) Here, you can see input parameters, headers and most important response.

4) So, in short you can debug a whole AJAX request life cycle.

ajax how to return an error message from a PHP file

Here is exactly how you can do it :

The Very Easy Way :

IN YOUR PHP FILE :

if ($query) {
echo "success"; //anything on success
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}

AT YOUR jQuery AJAX SIDE :

var x = $(this).text();
$.ajax({
type: 'POST',
url: 'process.php',
data: { text1: x },
success:function(data) {
alert(data); //=== Show Success Message==
},
error:function(data){
alert("error occured"); //===Show Error Message====
}
});

Simple success/error return with ajax and php

You are trying to echo your array, which will just spit out "Array".

Instead you need to encode your array as JSON and echo that out.

Change this:

echo $array;

To this:

echo json_encode($array);

Also you probably need to add your dataType in your ajax params so jQuery auto-parses the response:

dataType : 'json' // stick this after "data: $form.serialize()" for example

Also, here's a good post to read on how to properly handle success/errors with your ajax calls (thanks @Shawn):

Jquery checking success of ajax post

jQuery ajax call to php process form page not returning success or error

Ok, so thanks to the advice from @PatrickEvans and @MartyMcKeever above, I solved it by looking at the firebug console to find out that one of my custom PHP functions was missing a required argument. This was causing a parse error which was then making my jQuery throw an error but still allow the PHP to process the email.

If you look at the above PHP code there is a method that says $nextEventDay = getDay();

It should have been $nextEventDay = getDay("today");. This was causing all the problems

give @MartyMcKeever's comment an up vote.

How can I display different success / error PHP messages using AJAX

Here I am posting my entire working script in PHP, AJAX, JSON. I am sure other people will have different type of working scripts for contact form page but this is working fine for me.

I got help of many guys from here to make it working. So this is effort of all of them and I really want to thank them for their help. So I thought that I should post entire script here so it can be useful to other persons like me too.

NOTE#1 : alert(data); will help to alert JSON array response with status and message

NOTE#2: I am not using any ready made captacha script

contact.php

<form name="FormPRegister" id="FormPRegister" novalidate>
.
.
other form fields will come here
.
.
<div class="control-group form-group">
<div class="controls">
<label>Email Address:</label>
<input type="email" class="form-control" id="r_email" name="r_email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Secret Code:</label>
<div class="input-group">
<input type="text" class="form-control" id="r_secretcode" name="r_secretcode" required data-validation-required-message="Please enter secret code from given image."><span class="input-group-addon input-group-addon-no-padding"><img src="./includes/get_unique_image.php" border="0"></span>
</div>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" tabindex="9">Send Message</button>
</form>

contact.js

$.ajax({
url: "./contact_p.php",
type: "POST",
data: {
emailid: emailid,
secretcode: secretcode
},
cache: false,

success: function(data)
{
//alert(data);
var $responseText=JSON.parse(data);
if($responseText.staus == 'SUC')
{
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success').append("<strong> " + $responseText.message + " </strong>");
$('#success > .alert-success').append('</div>');

//clear all fields
$('#FormPRegister').trigger("reset");
}

else if($responseText.status == 'ERR')
{
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong> " + $responseText.message + " ");
$('#success > .alert-danger').append('</div>');
}
},
})

contact_p.php

.
.
other script will come here as per requirements
.
.
if( empty($_POST["r_email"]) )
{
$response['status']='ERR';
$response['message']= "Invalid Email ID!";
echo json_encode($response);
return;
}
if( empty($_POST["r_secretcode"]) || $_SESSION['image_secret_code'] != $_POST["r_secretcode"] )
{
$response['status']='ERR';
$response['message']= "Invalid Secrete Code!";
echo json_encode($response);
return;
}
.
.
other script will come here as per requirements
.
.
if( Invalid data then do this )
{
$response['status']='ERR';
$response['message']= "Invalid Secrete Code!";
echo json_encode($response);
return;
}
if( Valid data then do this )
{
$response['status']='SUC';
$response['message']= "Inquiry submitted successfully";
echo json_encode($response);
return;
}
.
.
other script will come here as per requirements
.
.

Jquery AJAX return from PHP

To invoke the error handler of your $.ajax, you can write the following code in PHP (for FastCGI):

header('Status: 404 Not found');
exit;

Alternatively, use header('HTTP/1.0 404 Not Found') if you're not using FastCGI.

Personally I wouldn't use this approach, because it blurs the line between web server errors and application errors.

You're better off with an error mechanism like:

echo json_encode(array('error' => array(
'message' => 'Error message',
'code' => 123,
)));
exit;

Inside your success handler:

if (data.error) {
alert(data.error.message);
}


Related Topics



Leave a reply



Submit