Jquery ajax call throws empty JS exception? - javascript

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?

Related

Handling file download from ajax get request in JavaScript

I am using a python CGI server to handle a cgi-bin request that I am making from an ajax call.
I'm trying to download the information I'm receiving on the Python side from my browser, using a button that triggers the ajax call.
I have tried some different things I saw on StackOverflow, but nothing has helped.
function issueDownloadCmd(port) {
var statusURL = window.location.protocol + "//" + window.location.host + "/cgi-bin/sod_log.py" + "?" + "down" + port.toString();
$.ajaxSetup({ 'cache': true });
$.ajax({
type: 'GET',
url: statusURL,
error: function (xhr, desc, exception) {
$('#traceStatus').html("Fail: response=" + xhr.status + "\nbecause: " + desc + "\nexception: " + exception);
},
success: function (data) {
console.log("data was downloaded");
}
});
return false;
}

jQuery 1.8 ajax call returns null although post response has value

I'm having problems with the return value of a jQuery ajax call. I can debug the whole thing server side and I know everything is working correctly and the return value is properly being calculated. I can look under the NET tab in FireBug and see that the response is:
{"d":false}
But when I test the value in the Success function of the ajax call, msg is NULL. Why?
Here's the ajax call:
function GetStateCertifiable(areaID) {
$.ajax({
url: "../WebServices/AoP.asmx/GetStateCertifiable",
data: '{"AreaID":"' + areaID + '"}',
dataType: 'json',
success: function (msg) {
alert(msg); // for debugging
if (msg)
$("#isCertified").slideDown("fast");
else
$("#isCertified").slideUp("fast");
},
error: function (msg) {
alert("An error occured. \nStatus: " + result.status
+ "\nStatus Text: " + result.statusText
+ "\nError Result: " + result);
},
complete: function () {
}
});
};
Other, similarly structured client-side calls work fine. This is a same-domain request.
try changing the name of the variable to something other than msg. I think that might be a message box or something similar. Try
function GetStateCertifiable(areaID) {
$.ajax({
url: "../WebServices/AoP.asmx/GetStateCertifiable",
data: '{"AreaID":"' + areaID + '"}',
dataType: 'json',
success: function (result) {
alert(result); // for debugging
if (result)
$("#isCertified").slideDown("fast");
else
$("#isCertified").slideUp("fast");
},
error: function (result) {
alert("An error occured. \nStatus: " + result.status
+ "\nStatus Text: " + result.statusText
+ "\nError Result: " + result);
},
complete: function () {
}
});
};
It turns out the problem was that my web service (../WebServices/AoP.asmx/GetStateCertifiable) returned a bool and from the post response, I know that was properly sent back to the client. Ajax, however, didn't like that. Once I changed the web service to return the strings "true" or "false", everything worked.
Does jQuery ajax only work for strings or is there something I should have done to prepare the msg object to receive a bool?

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 order of events - unable to figure out proper solution

I'm trying to create an if/else statement within my jQuery code that changes the ajax URL and success function that gets fired off:
if($($this.context).find('img').hasClass('scheduler-img')) {
url = window.location.origin + "/recipes/" + planned_recipe_id +'/update_recipe'
} else {
url = window.location.origin + "/recipes/" + recipe_id +'/make_recipe'
success = successfulRecipeAdd(closest_date, image_url, recipe_id);
}
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
data: {
planned_for: planned_for,
meal_type: meal_type
},
success: (function() {
success
}),
error: (function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
})
});
I'm using this for a jQuery draggable and sortable table, so when I'm dragging and dropping the first item, it doesn't work because it tries creating the 'success' variable with an empty dataset. However, it does work for every subsequent drag/drop after.
function successfulRecipeAdd(closest_date, image_url, recipe_id) {
$.get( window.location.origin + "/recipes/get_recipes", function(data) {
console.log(data);
var planned_recipe_id = $(data).last()[0][0].id;
$(closest_date).append("<img src='"+image_url+"'class='scheduler-img col-md-12' id='"+ recipe_id +"' data-planned-id='"+planned_recipe_id+"'>");
});
}
I'm having a lot of trouble figuring out a way to write this that would allow me to create variables within the if/else statement, then fire off the ajax call using variables, rather than having two ajax calls within the if/else statement.

UPDATED form validation error in javascript

from the coding below, if some data are wrong, it will alert false. it works fine if the confirmed pw is not same as the password. however, if the loginID checking seems gotta some problems. it alert true789 false false123 false456 respectively. why the consequence is not false123 false456 false789 false? because of the delay from json? how to solve it?
var result = "true";
$('#test').click(function(){
validation();
alert(result);
});
function validation(){
result = "true";
var loginID = $("#loginID").val();
var role = $("#role").text();
// check Login Name
if (loginID == "" || loginID == null){
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>'
);
$("#errorID").show();
result="false";
} else {
$.ajax({
type: "GET",
dataType: "jsonp",
jsonpCallback: "jsoncallback",
data: {
ID: loginID,
role: role
},
url: "http://mydomain.com/checkID.php?jsoncallback=?",
success: function(data){
if (data[0].data.user_name!=""){
result="false";
alert(result+"123");
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name " + data[0].data.user_name +
" is used." + '</h6>'
);
$("#errorID").show();
alert(result+"456");
}
},
error: function(jqXHR, textStatus, errorThrown){
alert("Request failed: " + textStatus + errorThrown);
result="false";
}
}); //end of ajax
}
alert(result+"789");
return result;
} // end of #validation
the ajax call is done asynchronous. it enters the ajax() function then carries on and when the result will eventually come the alerts or whatever you have in the event handlers will trigger.
You can add a async : false to your ajax call that will change how things run. The 789 alert will only run after the ajax call is done and responded.
Also, if your ajax call is made to your domain then you don't need the jsonpCallback and if the headers of the response are application/json then you should remove dataType as well and leave it to jQuery to handle it correctly

Categories

Resources