Is it possible to force an error state to return to an ajax request from a PHP script?
I am handling the success and error states in an ajax request and I want a way to force the error. The error only seems to be triggered by xhttp error and I want to trigger this when a condition is not met at the server. Its seems confusing to have to return success and have to actually put a flag in the response for an error
You could approach this from two angles:
Force an error to be thrown by outputting an HTTP header such as a 404 or 503.
Force an error to be thrown based on certain condition of the resulting data.
Force an error to be thrown by outputting an HTTP header such as a 404 or 503:
PHP
<?php
if(User::Login($_POST['username'], $_POST['password'])) { // Your logic here
print 'Login successful!';
} else {
header("HTTP/1.0 403 Forbidden");
print 'Bad user name / password';
}
jQuery
$.ajax({
'url': '/some/url',
'type': 'POST',
'data': {
'username': 'someone#example.com',
'password': 'rhd34h3h'
},
'success': function(data) {
alert(data);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + textStatus);
}
});
Force an error to be thrown based on certain condition of the resulting data:
PHP
<?php
$return = array();
if(User::Login($_POST['username'], $_POST['password'])) { // Your logic here
$return['success'] = True;
$return['message'] = 'Login successful!';
} else {
$return['success'] = False;
$return['message'] = 'Bad user name / password';
}
print json_encode($return);
jQuery
$.ajax({
'url': '/some/url',
'type': 'POST',
'dataType': 'json',
'data': {
'username': 'someone#example.com',
'password': 'rhd34h3h'
},
'success': function(data) {
if(data['success']) { // Successful login
alert(data['message']);
} else { // Login failed, call error()
this.error(this.xhr, data['message']);
}
},
'error': function(jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + textStatus);
}
});
You can use header to do this, for example:
header('HTTP/1.1 503 Service Unavailable');
Related
In Ajax, the success part always executes. But if there is an error , I don't want to execute the normal; instead I want to show an error message.If the discount code is present then show/hide some div along with code and then redirect, else display the error message which we get in json response in the error div. How can i achieve this ?
Here is json response :
{result: "fail", msg: "Code is not valid", redirect: 0}
controller :
if($result == 'exp'){
$discount_arr ['result'] = 'fail';
$discount_arr['msg'] = 'Promotion code expired';
$discount_arr['redirect'] = 0;
}else{
$discount_arr ['result'] = 'success';
$discount_arr['msg'] = 'Valid Code';
$discount_arr['url'] = base_url('cart');
$discount_arr['redirect'] = 1;
}
echo json_encode($discount_arr);
HTML :
<div class="cart-secondary cart-discount-code">
<label for="cart_Code">
Discount Code </label>
<input type="text" class="discount-code" name="cart_discountCode" id="cart_discountCode">
<span class="error coupon-error"></span>
<div class="confirm-coupon"></div>
<button type="submit" value="addCoupon" name="addCoupon" id="add-coupon" onclick="checkStatus()">
Apply </button>
Ajax:
function checkStatus(){
var discount_code = $(".cart-secondary .cart-discount-code .discount-code").val();
$.ajax(
{
url : "<?php echo base_url('cart/validate/'); ?>",
type : "POST",
data : {discount_code: discount_code} ,
cache : false,
dataType:'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success:function(data, textStatus, jqXHR)
{
if(textStatus == 'success'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
//if fails
console.log(errorThrown);
}
});
}
Please help
just use an else for your if comparison.
update: you are accessing the wrong variable of your success-callback. you are not interested in the textStatus, you want to read the data you are returning by yourself. the returned json object is saved in the data variable:
if(data.result == 'success'){
/* ... */
}else{
$(".error").text(data.msg);
}
You can access those information in data variable of success callback of the AJAX function.
Use it like this,
success:function(data, textStatus, jqXHR)
{
if(data.result != 'fail'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
} else {
alert(redirect.message);
if(data.redirect==1) {
// redirect here..
}
}
}
So access those data using,
data.message
data.redirect
data.result
It's normally as you access property of any JavaScript object.
If you are getting
{result: "fail", msg: "Code is not valid", redirect: 0} in success block,
then do this
success:function(data, textStatus, jqXHR)
{
if(data.result !== 'fail' && textStatus == 'success'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
}
},
I have the below Ajax function
ajax = function (params, action) {
$.ajax({
type: "POST",
url: "ajax.php",
data : params+"&action="+action,
dataType: "json",
success: function(response) {
switch(action)
{
case "save":
//some stuff
break;
case "del":
var seclastRow = $("."+table+" tr").length;
if(response.success == 1)
{
$("."+table+" tr[id='"+response.id+"']").effect("highlight",{color: '#f4667b'},500,function()
{
$("."+table+" tr[id='"+response.id+"']").remove();
});
}
break;
}
},
error: function() {
alert("Unexpected error, Please try again");
}
});
}
The following is the ajax.php that it calls. The file is a big if-else series, but I am pasting the wrong part only.
else if ($action == "del")
{
$id = $_POST['rid'];
$res = $obj->delete_record($id);
if ($res)
{
echo json_encode(array("success" => "1","id" => $id));
}
else
{
echo $obj->error("delete");
}
}
However, once the result is echoed back, the success function never enters in the Ajax part and I always get the Unexpected error alert.
Any ideas?
I as able to get the error using the callback error: function() and then displaying the response inside console.log. Check the image. response text
I have several requests like this:
$('#some-button').on('click', function(e) {
e.preventDefault();
$this = $(this);
$.ajax({
url: 'some_request.php/?q='+$some_id,
dataType: 'json',
success: function(data) {
alert('success!')
}
});
});
I.e. lots of AJAX requests that get initiated on button clicks. This request stays 'pending' according to Chrome - no JS alert. No HTTP response code comes back. I think it's just sat there waiting on a response and not getting it.
Question is similar to: jquery $.ajax request remains pending but the answer doesn't help. Nowhere in my PHP or HTML code am I using the session.
Any ideas? Many thanks.
I think you need a jQuery Ajax Error Handling Function. Here it is:
// jQuery Ajax Error Handling Function
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
Now call your ajax function:
$.ajax({
url: 'some_request.php/?q=' + $some_id,
dataType: 'json',
success: function(data) {
alert('success!')
}
});
And check what error you are getting.
Are you sure that the Php file you're requesting is on the same domain? Usually this happens when doing cross domain Ajax calls which is not allowed by most web browsers. You'll have to try jsonp instead if that's the case. Here is a nice practical explanation with examples: http://www.jquery4u.com/json/jsonp-examples/
My form is returning data from PHP via jQuery. How can I create conditional statements based on the response in jQuery.
This is the jQuery:
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData,
success: function(data){
$('#message').fadeIn();
$('#message').html(data);
}
});
This is what it is returning from PHP:
if($error) {
echo $error;
}
else {
echo $success;
}
So if the response is success, the message should hide after a few seconds, but if it is an error, it should wait till the user corrects it. Something like this:
success: function(data){
$('#message').fadeIn();
$('#message').html(data);
if (data.response == 'success') {
alert('Success');
setTimeout(function() {
$('#message').fadeOut();
}, 5000 );
} else if (data.response == 'error') {
alert('Error');
}
}
Why don't you use the statusCode setting for your call to ajax() and have even more fine-grained control than just "success" and "error"? There are (or will be) many different ways your script could succeed or fail.
statusCode(added 1.5)Map Default: {}
A map of numeric HTTP codes and
functions to be called when the
response has the corresponding code.
For example, the following will alert
when the response status is a 404:
$.ajax({ statusCode: {
404: function() {
alert('page not found');
} } });If the request is successful, the status code functions
take the same parameters as the
success callback; if it results in an
error, they take the same parameters
as the error callback.
UPDATE:
I've added an example of how to use statusCode instead of success and error settings for ajax() call in Jquery. First, the test UI:
<html>
<head>
<title>jQuery Test Page</title>
<script type="text/javascript" src="jquery-1.6.js"></script>
<script type="text/javascript">
function displayMessage(message){
$('#message').fadeIn();
$('#message').html(message);
}
function successFunction(data){
displayMessage(data);
}
function notFoundFunction(){
displayMessage("Not Found!");
}
function errorFunction(){
displayMessage("An Error Occurred!");
}
function invokeAjax(test){
$.ajax({
type: "POST",
url: "test.php?test="+test,
//data: postData,
statusCode: {
200: successFunction,
404: notFoundFunction,
500: errorFunction,
}
});
}
</script>
</head>
<body>
<h1 id="message" style="display:none;"></h1>
Invoke Ajax - Success (200)<br>
Invoke Ajax - Not Found (404)<br>
Invoke Ajax - Error (500)<br>
</body>
</html>
And here's the PHP script called by the Ajax:
<?php
$test = $_GET['test'];
if($test == 'success'){
echo 'some meaningful data';
} else if($test == 'notfound') {
http_send_status(404);
} else if($test == 'error'){
http_send_status(500);
}
?>
I think it's pretty self-explanatory, but if you have any further questions, don't hesitate to ask.
Of course, to get AJ's solution to work, you need to respond from the server to the client with the correct headers - http://no.php.net/manual/en/function.header.php:
header('HTTP/1.1 404 Not Found');
or
header('HTTP/1.1 500 Internal Server Error');
Here is a list of HTTP codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Hope this helps :)
Thank you for your helpful answers. I solved it using JSON though!
PHP:
if($error) {
echo json_encode(array('success' => false, 'text' => $error));
}
else {
echo json_encode(array('success' => true, 'text' => $success));
}
jQuery:
if (data.success) {
alert('Success');
setTimeout(function() {
$('#message').fadeOut();
}, 5000 );
} else {
alert('Error ' + data.text);
}
I have a PHP script that breaks if a variable is not populated and it isn't added to the database, but jQuery handles this as a success and I get this error:
TypeError: Result of expression 'data' [null] is not an object.
Here's the jQuery script:
$.ajax({
type: "POST",
url: "/clase/do-add",
data: $("#adauga").serialize(),
dataType: "json",
error: function (xhr, textStatus, errorThrown) {
alert('Try again.');
},
success: function(data) {
var dlHTML = '<dl id="' + data.id + '"> [too long] </dl>';
$('form#adauga').after(dlHTML);
$('#main dl:first').hide().fadeIn();
adaugaClasaSubmit.removeAttr('disabled');
adaugaClasa.removeAttr('readonly');
adaugaClasa.val("").focus();
}
});
The problem is that jQuery's concept of "error" is an HTTP error, not an error that you have noted yourself. If the HTTP response code is <400, jQuery will use your success callback. Your options are (a) to use PHP to give an error in your HTTP response
header("HTTP/1.0 500 Internal Server Error");
or (b) to do your error handling in the success handler:
success: function(data) {
if (!data) {
// do your error code here
} else {
// do your success code here
}
}
I prefer the first option, with HTTP response codes, to allow your code to make the best logical sense to a future editor (which may be you!).
success: function(data) {
if(data!=null){
...
}
}
try this