How to properly try and Catch in jQuery - javascript

I have the following function, that get a response from a web service. The response should be displayed on one section of the website.
That's working fine, but the thing is, in case of error, I've trying to get the error message and display it in the same way as the succesful response does, but I can't get that.
$(document).ready(function(){
$('.button').click(function(){
try {
var $resp = $.get("service url here", function(resp){
$('.response').append(resp.response.greeting + ", " + resp.response.Welcome);
});
}
catch (err){
$('.response').append(err.name + ", "+ err.message);
}
});
});

Try using .always()
$(document).ready(function(){
$(".button").click(function() {
$.get("service url here")
.always(function(resp, textStatus, jqxhr) {
$(".response")
.append(textStatus === "success"
? resp.response.greeting + ", " + resp.response.Welcome
: textStatus + ", "+ jqxhr
);
});
});

Related

404 in JQuery Ajax POST call while sending XML to server

I am recently working with adobe InDesign extension's and in that I want to upload an xml file to my server using jquery ajax POST call, so for that, I have to read the XML file from the file system store it into a variable and then pass that variable as body into the post request here is my code
function uploadDocument( onSuccess, onError, onComplete) {
var token = localStorage.getItem("token");
writeLogs("uploadDocument function \n " + token );
var result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
var xmlStr = "";
if(result.err == 0){
writeLogs("file read complete " + ' ' + result.data)
xmlStr = result.data;
alert("type of xmlStr new" + ' ' + typeof(xmlStr));
$.ajax({
url : "https://xyz.abc.com/capi-demo/article?customerNumber=888",
method: "POST",
data: xmlStr,
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Content-Type", "application/xml");
},
complete: function(xhr) {
alert("on complete with code" + ' ' + xhr.status + ' ' + xhr.statusText );
//onComplete();
},
success : function(response) {
alert("file upload success with response : " + ' ' +response);
},
error : function(jqXHR, textStatus, errorThrown) {
alert('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
}
});
}
}
and here exact is the XML file I want to send :
<document xmlns="http://pubpress.com/document">
<properties>
<magazineNumber>95100</magazineNumber>
</properties>
<article>
<pam:message xmlns:pam="http://xax.org/namespaces/pam/2.0/" xmlns:ppc="http://axa.com/content" xml:base="/article/content/39992.xml">
<pam:article>
<head xmlns="http://www.w3.org/1999/xhtml">
<dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">888-create.xml</dc:identifier>
<pam:status/>
</head>
<body xmlns="http://www.w3.org/1999/xhtml"><p>Sample body text</p></body>
</pam:article>
</pam:message>
</article>
</document>
so whenever I execute this POST call it returns 404 error Not Found but when I send the wrong(undesired to server) XML file then it shows 400 bad request.
the wrong xml (undesired to server) is as follows :
<?xml version="1.0" encoding="UTF-8"?>
<variable type="NameValuePair[]">
<item type="NameValuePair">
<name type="String"><![CDATA[No Data Found]]></name>
<value type="String"><![CDATA[95990070]]></value>
</item>
</variable>
i am not able to find why this POST call is returning 404 from ajax call where the same call with same parameters runs well in PostMan.
thank you in advance..
Any help on this will be highly appreciated.
Aside from making sure the url accepts xml posted, you should add the ajax option for contentType: "text/xml", to your configuration.
Here I get stuff out of the global scope with myApp (not part of question but to me it is better in practice to do so). I refactored to the promise form of .ajax() again because I like it better and I could then replace the functions there with some name spaced error handler for all my ajax for example.(is that what those passed things are, callbacks?)
I also saw a couple of bugs like typeof() in there. This assumes ES6.
// create a namespace object
var myApp = myApp || {
url: "https://xyz.abc.com/capi-demo/article?customerNumber=888"
};
// borrow some code from https://stackoverflow.com/a/23861977/125981
myApp.isXHR = function(maybe) {
if (!maybe) {
return false;
}
if (!('readyState' in maybe)) {
return false;
}
if (!('responseText' in maybe)) {
return false;
}
if (!('status' in maybe)) {
return false;
}
if (!('statusText' in maybe)) {
return false;
}
return true;
};
myApp.writeLogs = function(logmessage) {
// just to act as placeholder for the answer
};
myApp.processMessage = function(message, silent = true) {
if (silent) {
alert(message);
} else { // or
console.log(message);
// or something else like send to server via ajax to log or some such
}
};
myApp.getDocumentContent = function() {
let result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
//var xmlStr = "";
let getResult = {
xmlStr: "",
hasContent: false,
error: result.err
};
if (result.err == 0) {
myApp.writeLogs("file read complete " + ' ' + result.data)
myApp.processMessage("type of xmlStr new" + ' ' + (typeof result.data));
getResult.xmlStr = result.data;
getResult.hasContent = true;
}
return getResult;
};
myApp.sendContent = function(contentObj) {
let token = localStorage.getItem("token");
myApp.writeLogs("uploadDocument function \n " + token);
myApp.writeLogs("file read complete " + contentObj.xmlStr);
myApp.processMessage("type of xmlStr new " + (typeof contentObj.xmlStr));
$.ajax({
url: myApp.url,
method: "POST",
data: contentObj.xmlStr,
contentType: "text/xml",
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Content-Type", "application/xml");
}
})
.always(function(dataOrJqXHR, textStatus, jqXHROrErrorThrown) {
// determine which parameter is which when the .always() is called
let my_jqXHR = null;
let data = null;
let errorThrown = null;
if (myApp.isXHR(dataOrJqXHR)) {
my_jqXHR = dataOrJqXHR;
errorThrown = jqXHROrErrorThrown;
}
if (myApp.isXHR(jqXHROrErrorThrown)) {
my_jqXHR = jqXHROrErrorThrown;
data = dataOrJqXHR;
}
let status = my_jqXHR.status;
// do something with status
myApp.processMessage("on complete with code" + ' ' + status + ' ' + errorThrown);
})
.done(function(data, textStatus, jqXHR) {
myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
})
.then(function(data, textStatus, jqXHR) {
myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
}, function(jqXHR, textStatus, errorThrown) {
myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
});
};
myApp.uploadDocument = function(onSuccess, onError, onComplete) {
let contentObj = myApp.getDocumentContent();
if (contentObj.hasContent && contentObj.err == 0) {
myApp.sendContent(contentObj);
} else {
myApp.processMessage("No Content" + contentObj.err);
}
};
// call it, not sure what these passed thing are, and seem unused
myApp.uploadDocument(onSuccess, onError, onComplete);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ajax error function not working 2

Basically what I'm trying to do is have a search bar. The user should input the state and city. Once I get the state and city, update the html with the result. The problem is once i enter an invalid state or city, it gives me an error in the console. What i want is an alert telling the user that they have made a mistake in entering the city or state. I tried using a try and catch/ ajax error function but it doesn't seem to work. Need some help thanks !
$(document).ready(function() {
setTimeout(function(){
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search= $('#search');
var searchsubmit= $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
try {
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}catch(err){
alert(err.message);
}
});
});
I think that adding the error callback should work, here is a jsbin:
https://jsbin.com/ciwosoqeye/edit?html,js,output
var searchresult = '';
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/" +
searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
},
error: function(jqxhr, errorString, ex) {
alert(ex);
}
});
as defined in the doc
Without knowing what error message you are getting or what parsed_json looks like with a bad request, this is only a guess but parsed_json probably doesn't have a location property and/or a city property when bad data is passed in. I'm guessing that is causing the error. If this is the case, you can check for the existence of parsed_json.location and parsed_json.location.city before trying to access them and display the error if they don't exist.
$(document).ready(function() {
setTimeout(function() {
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search = $('#search');
var searchsubmit = $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
if (parsed_json.location && parsed_json.location.city) {
var location = parsed_json.location.city;
var temp_f = parsed_json.current_observation.temp_f;
alert("Current temperature in " + location + " is: " + temp_f);
} else {
alert(err.message);
}
}
});
});
});
Setting a break-point at the beginning of the success callback and inspecting parsed_data would help in debugging this sort of thing.

Ajax unable to parse JSON data

I know there are many questions out there on the same topic and I've read all of them but they don't help my case.
I am trying to parse some JSON data returned from my serverside PHP script. I've used JSONLint to verify that the PHP output is a valid JSON string.
I have the following ajax code:
$(document).ready(function(){
$('#update-stats-submit').on("click", function(){
if (requestRunning) { // don't do anything if an AJAX request is pending
return;
}
$.ajax({
type: "GET",
url: "calculate.php",
data: "q="+$("#table-info").val(),
dataType: "json",
success: function(data){
$("#update-result").animate({ opacity: 100 });
$("#update-result").html(data.output_msg);
$("#update-result").delay(3000).animate({ opacity: 0 });
setTimeout(function() {
$("#update-result").empty();
}, 4000);
alert(data.avg + "\n" + data.var + "\n" + data.count + "\n" + data.est + "\n" + data.min + "\n" + data.max);
},
error: function(xhr, ajaxOptions, thrownError){
$("#update-result").html(xhr.responseText + "\n" + xhr.status + "\n" + thrownError);
}
})
return false;
});
});
I've not gotten this piece of code to execute successfully. Each time the following error is returned.
200 SyntaxError: Unexpected end of input
Sample JSON output returned from calculate.php:
{
"output_msg":"Success!",
"avg":5.79916666667,
"var":4.63505345486,
"n":40,
"est":"1",
"min":"3",
"max":"4"
}
Any tips would be greatly appreciated.
Basically there's nothing wrong with the above ajax script. It appears the bug lied with the serverside PHP code that allowed the script to exit() under certain GET request conditions.

Jquery ajax call throws empty JS exception?

This function works on one page but not another. I've added all sorts of logging to try to find the error, but cannot. The output of this code on the broken page is:
[13:59:56.427] "here"
[13:59:56.428] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A"
[13:59:56.428] "fileName=undefined"
[13:59:56.428] "lineNumber=undefined"
[13:59:56.428] "columnNumber=undefined"
[13:59:56.428] "here6"
That tells me it's getting into the exception handler, completely skipping my ajax() call, but it's not telling me the exception.
function test(server, port, username, password, spanId) {
spanId = "#" + spanId;
$(spanId).html("<img src='/images/ajax-small.gif'/>");
console.log("here");
try {
$.ajax({
dataType: "json",
type: "GET",
url: "/admin/test.html?server=" + server + "&port=" + port + "&username=" + username + "&password=" + password,
success: function(json){
console.log("here2");
if (json.httpStatus == "200") {
// Change the image to show success
$(spanId).html("<img src='/images/accept.png' title='success'/>");
}
else {
console.log("here7");
// Change the image to show failure
$(spanId).html("<span style='color:#b22222;'>" + json.httpStatus +"</span> <img style='vertical-align: middle;' src='/images/cancel.png' title='placeholder'/>");
}
console.log("here8");
$(spanId).tooltip({ content: json.msg});
},
// Display the URL
beforeSend: function(b,c,d) {console.log("beforesend: " + c.url);},
error: function(b,c,d) {console.log("here5");}
});
}
catch(e) {
console.log(e);
for (var i in e)
console.log(i + "=" + i[e]);
}
console.log("here6");
}
What could I do further to debug this?
UPDATE: Output of code on a working page
Here's the output of the exact same code but on the page where it is working:
[15:01:20.158] "here"
[15:01:20.159] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A"
[15:01:20.159] "here6"
[15:01:21.661] GET https://localhost/images/accept.png [HTTP/1.1 200 OK 2ms]
[15:01:21.599] "here2"
[15:01:21.600] "here8"
So it obviously gets through the ajax call with flying colors. No errors, nothing. How can I find the problem on the page where it doesn't work?

How to access result array returned in ajax?

Arg!! I had this working flawlessly and now I am back to banging head against the keyboard.
I want access defined columns inside the array, but I am getting undefined but if I display the results using an alert as detailed in snipped of code below I see the following:
[{"firstname":" Mr","0":" Mr","lastname":" Two","1":" Two","user_public_info_id":"3","2":"3","st_usage_id":null,"3":null},{"firstname":" Mr","0":" Mr","lastname":" Three","1":" Three","user_public_info_id":"5","2":"5","st_usage_id":null,"3":null}]
***
g
***
e
***
undefined
Here is the Ajax code:
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: "handler=getStActivitySharingList&stu_id="+stu_id,
datatype: "json",
success: function(result){
var count = 0;
if (result !== null)
{
//display results
alert(result + " <br />*** <br />" + result[0] +" <br />*** <br />" + result[1] + " <br />*** <br />" + result[0]["firstname"]);
//clears choice list
clearOptions();
//result = $.parseJSON(result); //if this is used cannot display result again
alert (result);
$.each(result, function (i, elem) {
alert("elem"+elem.st_usage_id ); //displays as undefined and won't break
if (elem.st_usage_id === null)
{
count++;
alert(elem.firstname + " "+ elem.lastname + " " + elem.user_public_info_id);
appendOption(elem);
}
});
}
alert(count);
if (count === 0){
noResultsAvailableOption();
}else{
resultsAvailableOption();
}
ShowDialog(false);
e.preventDefault();
},
error: function(){
alert("ajax failure: could not retrieve a list of contacts");
}
});
i not know how you return it from PHP, but in jquery try:
sucess: function (result)
{
console.log(JSON.parse(result)); // parse string to json
}
See json.org
To better answer this question is to implement better debugging procedures.
Here is the code that I used for debugging this issue. The breaking down of the xmlHttpRequest clearly displayed to me that issue was with the data and that I was encountering an illegal character exception when trying to encode the data to json.
A great way to solve any issue is to first implement the correct debugging procedures, and everything else will work itself out.
error: function(xmlHttpRequest, status, error){
alert("ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xmlHttpRequestStr= "";
for(x in xmlHttpRequest)
xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x];
alert(xmlHttpRequest);
}

Categories

Resources