Api call using Ajax in javascript giving error - javascript

i am getting error on calling ajax request with a code 422(unprocessible entity) , i dont understand what is wrong with my code can someone help me to figure out the error
$.ajax({
url: "/api/v3/email_exists",
method: 'POST',
data: {
email: email_entered
},
success: function (response, status) {
if (response.sent) {
showFlashMessage('Email Sent');
alert(response);
}
else {
showFlashMessage('An error occured, please try again latervrfg.', 'error');
}
},
error: function (response, status) {
showFlashMessage('An error occured, please try again later.', 'error');
}
});
url is returning either true or false in case of false it is giving status 422

Try with a full URL e,g https://Path_to _the controller_method

Related

AJAX: only error callback is been fired

I have declared success and error callbacks, but in case of status code 200 also it calls error callback only.
I have been making curl call to some other php file too inside registry.php.
Here what i tried:
$.ajax({
type: "POST"
,data: {
action: "blah"
,mobileNo: that.mobNo
,token: that.key
}
,url: "http://90.8.41.232/localhost/registry.php"
,cache: false
,dataType: "json"
,success: function (response) {
console.log("success");
}
,error: function () {
console.log("error");
}
});
I have read in documentation that we don't have to call success callback explicitly, hope it's correct.
Any idea how to call success callback when it is 200 status code.
RESPONSE
hope this will help, this I copied from chrome console, not printed by console.log().
bort: (statusText)
always: ()
complete: ()
done: ()
error: ()
fail: ()
getAllResponseHeaders: ()
getResponseHeader: (key)
overrideMimeType: (type)
pipe: ()
progress: ()
promise: (obj)
readyState: 4
responseText: "{"success":"Mobile No 9535746622 is approved"} {"report":true}"
setRequestHeader: (name,value)
state: ()
status: 200
statusCode: (map)
statusText: "OK"
success: ()
then: ()
As you have mentioned that you are making a curl call to some other php, what happens is whenever you make curl call you have to return the response of the curl to the client. So to transfer the return value of curl call, you have to set an option curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);.
This will sort your problem. Hope so.
First, checkout the real error you get (not certain you really get a 200 status ?)
error: function (err) {
console.error("error");
console.log(err);
console.log(err.stack);
throw err;
}
Show us the resulting log please.
I did that a few weeks ago and for me it works if I call it like
$.ajax(
{
type: "POST",
data: { action: "blah", mobileNo: that.mobNo, token: that.key },
url: "http://90.8.41.232/localhost/registry.php",
cache: false,
dataType: json,
})
.success (function (data, status, jqxhr)
{
// do your stuff
})
.error (function(x, status, jqxhr)
{
// handle your errors
});

jquery ajax call not returning as expected

I'm unsure why this jquery ajax call is failing. Basically, I want to authenticate and if the authentication is a success, do something.
I found this but the answer seems to abbreviated to be much use to me (is assumes you already know how to implement the solution). jQuery ajax return value
Here is my ajax call (I have stripped the fluff for getting the username/password):
function authenticate() {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
if(data==='true') {
return "true";
} else {
return "User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data;
}
},
error:function(jqXHR, textStatus, errorThrown){
return "User failed to log into the system. Potential problem with server or connection.";
}
});
And I call it in this function:
function attemptEventSubmit(eKey) {
var authReturn = authenticate();
if(authReturn=="true") {
emailEvent(eKey);
} else {
alert(authReturn);
}
}
When it returns, it always alerts that authReturn is "undefined". I suspect it's defining authReturn as undefined because the authenticate function 'finishes' before the ajax call gets back...
But I'm not sure how to fix this problem.
I suspect I could call separate instead of returning values... (say, in this example, calling the emailEvent function directly in the ajax success function) but that would make the authenticate function specific... and it'd no longer be able to be used for authenticating for other purposes.
You can use your code but will need a callback. A better way would be look into promises.
function authenticate(onsuccess, onfail) {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
onsuccess(data); // you should check if this is a function
},
error:function(jqXHR, textStatus, errorThrown){
onfail(errorThrown);
}
});
function attemptEventSubmit(eKey) {
authenticate(
function(ajaxData){
emailEvent('whatever you want to send');
},
function(errThrown){
alert(errThrown);
});
}
How about pass in a callback function as another argument of the function authenticate().
So the code changes will be
function authenticate(callback) {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
if(data==='true') {
//return "true";
callback("true");
} else {
//return "User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data;
callback("User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data);
}
},
error:function(jqXHR, textStatus, errorThrown){
//return "User failed to log into the system. Potential problem with server or connection.";
callback("User failed to log into the system. Potential problem with server or connection.");
}
});
Calling the function authenticate will become:
function attemptEventSubmit(eKey) {
authenticate(function(authReturn){
if(authReturn=="true") {
emailEvent(eKey);
} else {
alert(authReturn);
}
});
}

alert() does not work for ajax error function

Just want to alert a message when there are some unexpected errors(I changed 'controller/get_data' to 'controller/get_dat') but it does not alert anything. Could you please check what is wrong with my error handling function.
$.get('controller/get_data', function (data) {
if (data.message !== undefined) {
$( "#data_is_not_got").text(data.message);
} else {
//displaying posts
}
}, "json").error(function(jqXHR, textStatus, errorThrown){
alert("Something gone wrong. Please try again later.");
});
.error is not what you expect it to be. Furthermore, it's deprecated. What you want is .fail()
.fail(function(){
alert("Something gone wrong. Please try again later.");
});
I believe you need to try .fail instead of .error.
$.get('controller/get_data', function (data) {
if (data.message !== undefined) {
$( "#data_is_not_got").text(data.message);
} else {
//displaying posts
}
}, "json").fail(function() {
alert("Something gone wrong. Please try again later.");
});
Otherwise, you could use the more basic $.ajax.
$.ajax({
url: 'controller/get_data',
type: 'GET',
success: function(data){
// Do something with data
},
error: function(data) {
alert('Something's gone wrong!');
}
});

How to capture the 500 error message using jquery?

How can i capture the 500 error message using jquery? I want to keep on checking for the 500 error message for sometime until it changes and time out after 50 sec.
I used the code below to try to capture and check the 500 error message but it doesnt seem to catch the 500 error message. I can see it in the firebug
$.ajax({
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
Dispite the accepted answer mentioned by #Danny, you can also do this in newer versions of jQuery.
var xhr = $.ajax({
url: "somewhere"
});
xhr.fail(function(xhr, textStatus, error) {
// Error handling stuff here ...
});
See Deferred Object.
Are you missing url in $.ajax like the one below
$.ajax({
url: "/path to page",
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
You can check the status in error of ajax post please check the below code.
$.ajax({
.....
success: function (data) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e, status) {
if (e.status == 404)
alert("404 error");
}
});
Thanks

ajax catch correct error code

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.

Categories

Resources