Want to alert AJAX feedback responses from this.responseText - ajax

I have been trying to alert this so that it prints two responses
when there is an error or a duplicate entry and
when the response is ok and prints successfully
var response;
try {
response = JSON.parse(xmlhttp.responseText);
} catch (e) {
console.error(this.responseText);
alert(this.responseText);
}
if (response) {
console.log(response);
}
I want it to alert a response both when there is a failure and when the response is successful, but I haven't figured it out yet.

figured it out
at this stage
console.error(this.responseText);
alert(this.responseText);
i needed to insert my error message here like this
var responseText = this.responseText;
alert('Registration failure because ' + responseText );
and below
console.log(response);
alert ('Registration Successful');
At this stage it prints the required outcome.

Related

Catching errors with axios

I can not catch the error response with axios. How to do that?
I use something like:
axios
.post(...)
.then(response => {
console.log('Success: ', response)
}).catch(error => {
console.log('Error: ', error)
})
I see that the result of ajax request has 400 status code and the response body looks like {someField:["This field may not be blank"]} (Django backend). That's ok, I'm ready to process these errors in the catch handler.
But they go to the success handler instead. Why so? I see the following output in the console:
Success: Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
The success handler receives axios error object as the result. Why that may be and what to do next? This error object does not contain any usefull information.
UPD. Actually, the error object does contain the useful information, it contains the response object inside. So we can use:
axios
.post(...)
.then(response => {
if (response && response.response) {
console.log('This is also an error', response.response.status)
} else {
console.log('Success: ', response)
}
}).catch(error => {
console.log('Error: ', error)
})
But that looks super ugly.
The axios version is axios#0.16.2.
That's the big project, but I can not find any axios customizations.
Use Axios interceptors for the response. Check which status you want to force to fail as error so they go through the catch path whenever you receive said status code.
axios.interceptors.response.use(function (response) {
if (response.status === 400) {
return Promise.reject(response);
}
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
If you are not receiving the expected status code, you might change the way you check the response in the interceptor. You can check any of the elements that Axios response is structured.
axios.interceptors.response.use(function (response) {
if (response.statusText !== 'OK') {
return Promise.reject(response);
}
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});

Cloud Code Error in Saving user

I have a function in my cloud code, which works, but I'm not sure how to fix a problem related to it.
Original Problem:
Parse.Cloud.define("assignTokenToUser", function(request, response) {
console.log("Inside assignTokenToUser");
var token = Math.random().toString(30).substring(7);
query = new Parse.Query("User"),
email = request.params.email;
query.equalTo("username", email);
query.find({ useMasterKey: true }).then(function(results) {
query.first({
success: function(user) {
// Successfully retrieved the object.
user.set("emailToken", token);
user.save();
console.log("success...");
response.success(token);
},
error: function(error) {
console.log("error 1...");
response.error(error);
}
});
}, function(error) {
console.log("error 2...");
response.error(error);
});
});
This seemed to be a common problem after scanning the internet, and my analysis is that the useMasterKey needs to be passed each time we use the query object. Correspondingly, my log file shows that when trying to save the user, it gives a Code 206 error.
Log file output:
Inside assignTokenToUser
success...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: "p66qm34jd80p0j6ne03fe1q7f" functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
going to send an email... with result: p66qm34jd80p0j6ne03fe1q7f
fullLink: https://beatthegym.com/emailVerified?username=maryam.zafar#emumba.com&token=p66qm34jd80p0j6ne03fe1q7f
^[[31merror^[[39m: Error generating response. ParseError { code: 206, message: 'Cannot modify user 4m0VZFsKVt.' } code=206, message=Cannot modify user 4m0VZFsKVt.
[object Object]
So I went on to change my code to the following:
Code:
Parse.Cloud.define("assignTokenToUser", function(request, response) {
console.log("Inside assignTokenToUser");
var token = Math.random().toString(30).substring(7);
query = new Parse.Query("User"),
email = request.params.email;
query.equalTo("username", email);
query.find({ useMasterKey: true }).then(function(results) {
console.log("inside query.find...");
query.first(null, { useMasterKey: true }).then(function(user) {
console.log("inside query.first...");
// Successfully retrieved the object.
user.set("emailToken", token);
user.save(null, { useMasterKey: true }).then(function() {
console.log("inside user.save...");
response.success();
}, function(error) {
response.error(error);
});
response.success(token);
},
function(error) {
console.log("error 1...");
response.error(error);
});
}, function(error) {
console.log("error 2...");
response.error(error);
});
});
Log file:
Inside assignTokenToUser
inside query.find...
inside query.first...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: "tqc8m9lo2tcsrqn69c3q0e1q7f" functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
inside user.save...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: undefined functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
[object Object]
Now, the log file gives me a user as "undefined", and the call to the function gives me a pending status in the Chrome Network tab in the Inspector tool, until it turns into 502, and then the request is auto generated by the browser again. All other requests get a correct 200 response.
However, the data seems to be saved.. the record against this email address saves the token generated correctly. But the request from the browser fails and the user is "undefined" while in the original log file, I see the correct user Id... everytime it fails, the function automatically runs again (because the browser is generating another request everytime it gets a 502) and since it is actually supposed to send an email, it's running again and again keeps on generating infinate emails...
Thank you in advance..
Understood this finally:
The user will remain undefined until and unlesss I obtain it using the Parse.User.current() method. The data does save into the database because it is a forced update to the record, however until the user is aunthenticated using the current() method, it will remain undefined.
I see this is an old post but I spotted clear error in the code:
query = new Parse.Query("User")
Should be:
query = new Parse.Query(Parse.User)
Or at least:
query = new Parse.Query("_User")
As User is a predefined class in Parse.

Node.js error handling

I am building an app using node.js and knex for the ORM. I want my insert command to send either a success or error response, but it is not working for some reason:
knex('reports').insert({
reportid: reportId,
created_at: currentDate
}).then().catch(function(error) {
if(error) {
console.log("error!!!: " + error)
res.send(400, error);
} else {
console.log('no error');
res.send(200);
}
});
The code as is does NOT console.log out the error nor lack of error.
Note - the res.send(200) should go back to my client side to alert the client the request was successful.
Can someone help? Thanks in advance!!
Promises will either trigger your then function or the catch function. Not both. Handling the success case happens in the then function, handling the error case happens in the catch function.
To demonstrate with your code:
knex('reports').insert({
reportid: reportId,
created_at: currentDate
}).then(function(data) {
console.log('no error');
res.send(200);
}).catch(function(error) {
console.log("error!!!: " + error)
res.send(400, error);
});
You should handle the positive flow within the .then part:
then()
{
console.log('no error');
res.send(200);
}
Also it's not consider a good practice to mix DB code with HTTP related logic as they probably should reside in different layers/components, see best practice number 4 here:
http://goldbergyoni.com/checklist-best-practices-of-node-js-error-handling/

PhoneGap ajax call fails everytime

I am developing a mobile application using PhoneGap, and I have to access some services from another project.
I am using jquery-2.0.0.js and jquery-mobile-1.3.2.js.
$.ajax({
url: 'http://localhost:62465/api/account?email=johndoe#yahoo.com',
dataType: 'json',
success: function (data) {
alert(data.Name);
},
error: function (xhr, type) {
alert("Failed to load data");
alert(xhr + " " + type);
}
});
This ajax call fails everytime. In the config.xml I have the following line: <access origin="*" />
Where I might be going wrong!
The problem is that your phonegap application is requesting a local file from something that isn't a webserver. The local file is delivered with NO HTTP HEADERS - that means no "200 OK" header and no "404 Not Found" errors. So, the status code is assumed to be 0.
Straight javascript XHR will need to ignore status and perform your action on readystate == 4 (finished and ready). Like this:
var myrequest = new XMLHttpRequest();
myrequest.open('GET','localfile.html');
myrequest.onreadystatechange = function(){
if(myrequest.readyState == 4) {
var result = myrequest.responseText;
}
}
myrequest.send();
In MooTools, it's a relatively straightforward task of implementing an altered status test in the Request class - altering the return code test to also accept 0 for true. Like this:
Request.implement({
isSuccess: function(){
var status = this.status;
return ((status >= 200 && status < 300) || status === 0);
}
});
jQuery.... I have some things I'd like to say about jQuery - but I'll hold my tongue because this seems like a classy place.
To prepare jQuery for status == 0, you need to use the always event instead of the success event, you can test the status code there.
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "email=a#b.com"
}).always(function(data, textStatus, jqXHR){
switch(textStatus) {
case 200:
case 0:
alert('Success.');
break;
case 404:
alert('oops');
break;
}
});
Ajax in Cordova/Phonegap - Yay!
url of your query is localhost, thant means- the same device (android emulator or physical). I'm sure that this is your problem. You should use IP (or domain) of your api json server, maybe 192.168.1.1 (depending on your network configuration)
Are you using a physical device or an emulator ? iOS ? Android ?
I might be wrong, but if you're running your app on a mobile device you can't access to your localhost.
I solved the problem with the "GET" call, but now I am trying to make a "PUT" call and it's the same problem, always fails.
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "email=a#b.com",
success: function(data) {
alert('Success.');
}
});
If the url: 'http://localhost:62465/api/account?email=johndoe#yahoo.com' is not reachable from your mobile, there's a very useful trick to use.
With www.ngrok.com, you can assign an internet domain to your locally unreachable port.
Just signup, get an access token, and then you can use:
ngrok -authtoken myauthtoken -subdomain=mysubdomainname 62465
And then you can access your computer with the url http://mysubdomainname.ngrok.com/api/account?email=johndoe#yahoo.com
(For people with similiar problems)
Use ajax error to know what is wrong:
error: function(jqXHR, exception){
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}

Getting global handler to all AJAX calls in dojo

I need to invoke some common methods before an AJAX call is made and after the AJAX call (before the actual handler method is called) is success. I'm using dojo.aspect to achieve this.
This is my code sample
function makeAjaxCall(){
dojo.xhrGet({
url:"sample_url",
content:{
test:"value"
},
load:function(response){
//Do some logic here
},
error:function(response){
//handle error
}
});
}
Below is the dojo.aspect which I'm using to get a hook to the XHR calls.
define(["dojo/aspect"], function(aspect){
aspect.after(dojo, "xhr", function(deferred){
console.log("AJAX AFTER");
deferred.then(function(response){
//CALLED AFTER 'load' METHOD IS CALLED.
console.log("Testing");
});
});
aspect.before(dojo, "xhr", function(method, args){
console.log("AJAX BEFORE");
});
});
Now the problem is deferred.then inside aspect.after is called after the "load" function is called. Is it possible to have a method which is called before the actual load method is invoked?
The short answer is yes.
First, there are two ways to make ajax calls in Dojo.
dojo/xhr - this is what you have above and this is deprecated
in favor of
dojo/request/xhr
The first implementation will call into the second implementation. So I would recommend using aop on dojo/request/xhr.
aspect.around(require.modules['dojo/request/xhr'], 'result', function(originalXhr){
return function(url, options, returnDeferred){
var dfd = new Deferred();
// Logic before making the xhr call
originalXhr(url, options, returnDeferred)
.then(function(response) {
// Logic handling the response but before resolving the deferred.
dfd.resolve(vm);
// Logic after resolving the deferred.
}, function(err){
// error handling?
dfd.reject(msgs);
}, function(update) {
dfd.progress(update);
});
return dfd;
};
});
You can find the complete implementation at
https://github.com/cswing/evinceframework/blob/master/evf-web-js/src/dojo/evf/serviceRegistry.js (~ line 111)
USAGE:
require('dojo/xhr/request', function(xhr){
xhr({...}).then(
function(response) {
//handle response
},
function(error) {
//handle error
}
);
});
The dojo/xhr code will translate itself to the usage above, so the code you posted should work.
If you switch to the new API - dojo/request
Then you could use dojo/request/xhr and dojo/request/notify
In Dojo 1.10 there is new API to globally catch state of requests.
notify("error", function(error){
console.error(error);
//SyntaxError: Unexpected token < in JSON at position 0(…)
});
But in my case I get errors in html eg. so in error I get "error SyntaxError: Unexpected token < in JSON at position 0(…)"
In previous version there was an access to response object:
topic.subscribe("/dojo/io/error", function(/*dojo.Deferred*/ dfd, /*Object*/ response){
if (response.status === 401) {
window.location.reload();
}
});
So I figured out that json handler can be customized:
require(["dojo/request/handlers"], function(handlers){
handlers.register("json", function(response){
if (response.status === 401) {
window.location.reload();
return;
}
return JSON.parse(response.text || null);
});
});
This way you are able to detect response.errors before JSON.parse throws exception.

Resources