i have this little code to post to my server
$.ajax({
type: 'POST',
url: 'post.php',
data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: '' },
success: function(data){
alert (data)
}
});
Wondering how i can "catch" the different errors for ajax request:
for eg, post.php return 'token error' when invalid token has been posted, or 'invalid title' for missing title.
Thanks in advance
If the server sends something else than 200 status code you could use the error handler:
$.ajax({
type: 'POST',
url: 'post.php',
data: {
token: '123456',
title: 'some title',
url: 'http://somedomain.com',
data: ''
},
success: function(data){
alert(data);
},
error: function() {
alert('some error occurred');
}
});
If your server performs some validation on the request arguments maybe it could return a JSON object containing the error information (and set the proper Content-Type: application/json):
{ error: 'some error message' }
In this case you could handle this in the success callback:
success: function(data) {
if (data.error != null && data.error != '') {
// TODO: the server returned an error message
alert(data.error);
} else {
// TODO: handle the success case as normally
}
}
// build the initial response object with no error specified
$response = array(
'error' => null
);
// the data checks went fine, process as normal
if (data is ok) {
$response['some_object'] = value;
// something is bad with the token
} else if (bad token) {
$response['error'] = 'token error';
// something is bad with the title
} else if (bad title) {
$response['error'] = 'bad title';
// some other error occured
} else {
$response['error'] = 'unspecified error';
}
// output, specifying that it's JSON data being returned
header('Content-Type: application/json');
echo json_encode($response);
and....
// $.ajax({ ...
success: function(data){
if (!data.error){
alert('OK!');
}else{
alert('Error: '+data.error);
}
}
// });
Something like that perhaps? (Unless you're talking legitimate AJAX errors, in which case supply the error: function(x,t,e){} ajax option or use .ajaxError)
What I like to do is set the dataType for the $.ajax() to 'json' and then in the PHP page you can just echo a json_encode()ed associative array. This will let you reference the values via your function parameter data (i.e. data.success, data.message). Let me know if you need some examples.
You probably want to set the 'error' handler function, which would treat the error you received.
Take a look at http://api.jquery.com/jQuery.ajax/ in the error setting.
Related
i want to show toaster on success or failer so i tried this code
$.ajax({
type: "GET",
dataType: "json",
url: '{{ route('users.update.visit_clear') }}',
data: {'visit_clear': visit_clear, 'user_id': userId , 'location': location , 'cs_location': cslocation },
success: function (data) {
if (data.message != ""){
toastr.success(data.message);
}
}
error: function (data) {
toastr.error(data.message1);
}
});
and in controller i have condition
if($var <= 1){
return response()->json(['message' => 'User status updated successfully.' ]);
}
else{
return response()->json(['message1' => 'Visit Failed Distance is too long' ]);
}
if i use error:function it doesnot response me
To be in the error ajax callback you have to return an http error code (ex: 500, 400 etc).
You can check the different http error codes here https://en.wikipedia.org/wiki/List_of_HTTP_status_codes.
You can add a status code as a second argument in your else response
ex: return response()->json(['message1' => 'Visit Failed Distance is too long' ],500);
I've a such js-function, which sends data to file, which contains a function, which sends back JSON-response:
function deleteCategory(id){
console.log(id);
$.ajax({
url: '<?php echo $cfg['options']['siteurl']; ?>/gears/ajax.deletePkgCatAsideMenu.php',
type: 'POST',
dataType: 'JSON',
data: {idItem:id},
success: function(data) {
console.log(data);
if (data.type=='error') {
notify(data.type, data.type, data.text);
} else{
document.location.reload();
}
},
error: function(v1,v2,v3) {
alert('Ошибка!\nПопробуйте позже.');//in english it will be: alert('Error!\nTry again later.');
console.log(v1,v2,v3);
}
});
}
In the end of that file these actions take place:
$q = 'DELETE FROM `pkg_cat_aside_menu` WHERE pkg_cat_ddlist_id='.$idItem;
$db->query($q);
exit(json_encode(array('type'=>'ok','text'=>'Удаление произведено!')));
//or in english: exit(json_encode(array('type'=>'ok','text'=>'Deleted!')));
This is a response text:
"int(13) {"type":"ok","text":"\u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u043e!"}"
And error syntax error: unexpected token i(...)
I think, it take place, because I did actions with data base (delete), which response a deleted record number (13), and it has been included to json-respose. How to fix it?
int(13) makes me think that you have a var_dump( $idItem ); somewhere earlier in your PHP code, which is causing the response to be invalid.
I have an ajax function which updates my database.. The function works perfectly well and after updating the the database I call the successAlert() function I have created.. however now I want to call the error function in case of error however on testing purposely to break code I still get the successAlert().
Ajax / Javascript:
var share = "test"
var custid = "test"
$.ajax({
url: "assets/ajax/customer-rec.php",
type: "POST",
data: {UpdateAccount: "yes",custid: custid,share: share},
success: function(result){
successAlert()
},
error: function(result){
errorAlert()
}
});
PHP to update Database
if (isset($_POST['UpdateAccount'])){
$custid = $_POST['custid'];
$share = $_POST['share'];
$query="UPDATE `users` SET `share_ord`='$share' WHERE id= $custid";
$stmt = mysql_query($query);
if($stmt === false){
return false
}
}
return false is not an error. If you want to send the error use headers like
header('X-PHP-Response-Code: 404', true, 404);
you can call the same errorAlert() function in success also so that
$.ajax({
url: "assets/ajax/customer-rec.php",
type: "POST",
data: {UpdateAccount: "yes",custid: custid,share: share},
success: function(result){
if(result === false){
errorAlert()
} else {
successAlert()
}
},
error: function(result){
errorAlert()
}
});
To get error you need to return the status code '404' from the php function which is serving your request.
The error callback is fired when the server returns a HTTP status code that indicates an error, as such you should send one, ex HTTP 500
if($stmt === false){
header('HTTP/1.1 500 Server error');
}
See here a list of HTTP status codes
.ajax() will call on success method because, once your request is processed successfully by the server then it reruns HTTP_OK to the client and if .ajax not received HTTP_OK, then it will call error. According to your code, it will call success, because url is exists and server will send HTTP_OK to the browser.
If you want to generate error: then give wrong url or disconnect internet or simply change
In PHP:
if($stmt === false){
//If you want really generate some http error.
header('X-PHP-Response-Code: 500', true, 500);
exit(0);
//or else continue as per code
// return false;
}
In your JS:
$.ajax({
url: "assets/ajax/customer-rec.php",
type: "POST",
data: {UpdateAccount: "yes",custid: custid,share: share},
success: function(result){
if(!result){
showErrorAlert()
} else {
showSuccessAlert()
}
},
error: function(result){
showErrorAlert()
}
});
I have a problem retrieving the posted data from an ajax call, not sure what is wrong. The console output from the script below shows everything as expectred before the ajax call, but the data is not available in the connector
function updateOptions(data){
console.log(data);
console.log(data.id);
console.log(data.action);
var data = {id: data.id, action : data.action};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.connector.php?action=updateOptions',
data: JSON.stringify(data),
cache: false,
dataType : "json",
success: function(data, status) {
if(data.status == 'success'){
console.log('success');
console.log(data);
}else if(data.status == 'error'){
console.log('selects not updated');
}
},
error: function(data){
console.log('an error has occurred');
},
});
}
So the first 4 console.log entries show the data correctly, the first console.log in the success condition shows correctly. The second, shows:
Object {status: "success", msg: "Category added successfully", id: null, action: null, post: Array[0]}
the connector [more like a director]
case 'updateOptions':
error_log('Running updateOptions function ' . print_r($_POST, TRUE), 0);
$output = $sbb->updateOptions($_POST);
break;
Logs this:
Running updateOptions function Array\n(\n)\n,
if I try to echo $_POST['action'] or $_POST['data'] or something to the log I get an undefined index.
I am forcing the ajax call to return success in the class that the php case function is calling:
public function updateOptions($data){
$output = array(
'status' => 'success',
'msg' => 'Category added successfully',
'id' => $data['id'],
'action' => $data['action'],
'post' => $data,
);
return $output;
}
So the ajax call itself does work, it's the data that's not being passed.
Somehow I am not getting [or correctly retrieving] the data from the ajax post.
What is the problem here?
You're posting JSON, $_POST is populated with key=value pairs, don't mix up JSON with application/x-www-form-urlencoded or multipart/form-data (which is what php uses to populate $_POST.
To send application/x-www-form-urlencoded data with jQuery.ajax pass an object with the data as the data parameter
data: data, // removed JSON.stringify
I am trying the access the json response from the server, using the following code. According to firebug, my server is outputting what looks like a valid json response as follows:
{"result":"error","message":"This group is not empty"}
my JavaScript is as below, but when I try to alert() the data from json response, I get nothing
$.ajax({
type: 'post',
url: data_ajax_url,
dataType: 'json',
data: 'data_mysql_record_id=' + data_mysql_record_id + '&data_mysql_table_name=' + data_mysql_table_name,
//success, annimate and remove row
success: function(data){
alert(data.result);
//get a json message from server if one exists
$ajax_response = data.message;
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Request has been completed';
}
//slide up table row
parent.slideUp(300, function(){
parent.remove();
});
//show noty notification 1 sec later
setTimeout(function(){
noty({
text: $ajax_response,
layout: 'bottomRight',
type: 'information',
timeout: 1300
});
}, 1000);
},
//error - alert
error: function(data){
alert(data.result); //my test
//get a json message from server if one exists
$ajax_response = data.message; //where 'message' is key in php jason output
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Error!- This request could not be completed';
}
//fire up a noty message
noty({
text: ''+$ajax_response,
layout: 'bottomRight',
type: 'warning',
timeout: 1300
});
}
UPDATE:
//data = jQuery.parseJSON(data);
console.log(data);
Console.log is giving me this
readyState
4
responseJSON
Object { result="error", message="This group is not empty"}
responseText
"{"result":"error","mess...is group is not empty"}"
status
400
statusText
"Bad Request"
and
data = jQuery.parseJSON(data);
console.log(data);
is giving this error
SyntaxError: JSON.parse: unexpected character
...nction(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i) {if("string"...
The status 400 and "bad request" is something I am oputiing in my php headers to show that there was an error backend
The error handler of an $.ajax request has the signature
Function( jqXHR jqXHR, String textStatus, String errorThrown )
[…] receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred.
Change your function to
error: function(jqXhr) {
var data = jqXhr.responseJSON; // you saw this in your console.log
if (data) {
…
} else {
// there might be other errors, where you don't get the server message
}
}
The problem is with parsing the JSON data in the javascript :
Before using the json data
data=jQuery.parseJSON(data);
alert(data.result);
Try this.
Use jQuery.parseJSON and might I suggest to use console.log instead of alert, like this:
$.ajax({
type: 'post',
url: data_ajax_url,
dataType: 'json',
data: 'data_mysql_record_id=' + data_mysql_record_id + '&data_mysql_table_name=' + data_mysql_table_name,
//success, annimate and remove row
success: function(data){
data = jQuery.parseJSON(data);
console.log(data.result);
//get a json message from server if one exists
$ajax_response = data.message;
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Request has been completed';
}
//slide up table row
parent.slideUp(300, function(){
parent.remove();
});
//show noty notification 1 sec later
setTimeout(function(){
noty({
text: $ajax_response,
layout: 'bottomRight',
type: 'information',
timeout: 1300
});
}, 1000);
},
//error - alert
error: function(data){
data = jQuery.parseJSON(data);
console.log(data); //my test
//get a json message from server if one exists
$ajax_response = data.message; //where 'message' is key in php jason output
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Error!- This request could not be completed';
}
//fire up a noty message
noty({
text: ''+$ajax_response,
layout: 'bottomRight',
type: 'warning',
timeout: 1300
});
}