AJAX request not working on remote host - javascript

I've got an AJAX request which pulls the data from the form and POSTs it to an API. The weird thing is it works perfectly fine on localhost but fails silently when I upload to remote server. And I mean silently: the response code is blank, there's nothing in the logs. I've checked on Firefox and Chrome. jQuery is loaded, function is firing properly. The code is below:
function send() {
console.log("preparing");
var beacon = {
beaconID: $("#beaconID").val(),
name:$("#beaconName").val(),
campaignID:$("#campaignID").val(),
clientID:$("#clientID").val()
}
console.log("payload:");
console.log(beacon);
$.ajax({
type: 'POST',
url: '../beaconAPI/index.php/createBeacon',
data: JSON.stringify(beacon),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
console.log("done:");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}

From the comments you posted
10:33:21.046 "{"readyState":0,"responseText":"","status":0,
"statusText":"error"}" addBeacon.html:34 10:33:21.046 "AJAX error: error : "
A status code of zero means one of two things:
You are running off file protocol
The page refreshed as Ajax call is made
Since you said this is on production, sounds like it is a case of #2.
So you need to cancel the action that is causing the page to refresh. Since you do not show how you call send, here is some basic ways of cancelling the action.
onclick="send(); return false"
onsubmit="send(); return false"
$("#foo").on("click", function(e) {
send();
e.preventDefault();
});

Related

TypeScript : Ajax call call always calling Error rather than success on success

In typescript I have a DataAccess Class so that all Ajax calls are routed through a single object to save repetition of code in a lot of places within my application.
In using this approach I have needed to use call backs to get the response back to the calling class so that the success and error can be handled accordingly.
This is the typescript
ajaxCall(retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
}
This is the compiled Javascript
AjaxDataAccessLayer.prototype.ajaxCall = function (retVal, retError) {
$.ajax({
type: this.callType,
data: this.dataObject,
dataType: this.dataType,
url: this.url,
contentType: this.contentType,
traditional: this.traditional,
async: this._async,
error: retError,
success: retVal
});
};
return AjaxDataAccessLayer;
This calls through to the ASP.Net MVC controllers perfectly fine, however the problem that I have is regardless of Success or Error the call back is always retError.
This is the calling Typescript
var _this = this;
var dataAccess = new DataAccess.AjaxDataAccessLayer(Fe.Upsm.Enums.AjaxCallType.Post,
Fe.Upsm.Enums.AjaxDataType.json,
"../../PrintQueue/DeletePrintQueueItems",
jsonObj);
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, xhr => {
// failure
alert("An Error Occurred. Failed to update Note");
});
When stepping through and looking at this the Status is OK and the response is 200.
So, Problem (as mentioned above) always calling xhr \ retError regardless of success.
Question: How do I get it to go into the right call back?
In your error handler, you were not passing all the parameters, so you are only checking whether the request finished successfully. However, there can be errors after that, like when the response is processed. You can handle errors betters like this:
dataAccess.ajaxCall(data => {
// success
new Fe.Upsm.Head().showGlobalNotification("Selected Items Deleted");
_this.refreshPrintQueueGrid();
(window as any).parent.refreshOperatorPrintQueueCount();
}, (xhr, errorText, errorThrown => {
// failure
console.log(xhr, errorTest, errorThrown);
alert("An Error Occurred. Failed to update Note");
});
Based on the discoveries using this method, the error is that your controllers are returning empty responses, so you're getting an exception when jQuery tries to parse them, because an empty string is not valid JSON.

Dynamic / Changing variable in AJAX get Request

I have a page on a project I'm developing that is attempting to make an ajax request with a specific value assigned by the button's (there are multiple) id tag. This works; the value is successfully passed and an ajax call is triggered on every click.
When I try to make the call again to the same page with a different button the variables are reassigned however the GET request that is sent remains unchanged.
How do I pass a NEW variable (in this case id) passed into the GET request?
function someAJAX(target) {
var trigger = [target.attr('id')];
console.log[trigger];
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: target.attr("class"),
tableCall: true,
sort: trigger,
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
$(document).ready(function () {
$(".sort").on( "click", function (e) {
//e.stopPropagation();
//e.preventDefault();
target = $(this);
//console.log(target.attr("class"));
console.log(target.attr("id"));
/* ADD CHILDREN TO ELEMENT*/
if (target.hasClass('asc')) {
target.removeClass('asc')
} else {
target.addClass('asc')
}
/* MANAGE CLASS ADD/REMOVE FOR TARGET AND SIBLINGS */
if (target.hasClass('btn-primary')) {
} else {
target.addClass('btn-primary')
}
someAJAX(target);
target.siblings().removeClass('btn-primary');
})
});
Try to call your ajax like this someAJAX.bind(target)();
Then in function become
function someAJAX() {
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: this.attr("class"),
tableCall: true,
sort: this.attr('id'),
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
trigger doesn't seem to be defined anywhere. That's the only data that would be changing between your requests as the other ones are statically coded.
You just need to make sure trigger is defined and changes between the two requests.
Thanks for the input on this problem. I got down to the bottom of my problem. My requests were being handled correctly but dumping the tables was creating syntax errors preventing the appending of new information to my page.
Thanks for the quick replies!
It wall works now.

Syntax Error Unexpected token only for Jelly bean phones

I have an HTML5 based android app. The app was working perfectly fine and was able to fetch data from the backend system. However, since today the app is reporting a weird error while fetching data SyntaxError Unexpected token and shows some gibberish character. This error is occurring only on phones having Jelly Bean (Android 4.2.1); it was working perfectly fine till last week and there has been no change in the code. In the below code the ajax call goes into the error section for Android 4.2.1.
function getData() {
jQuery.support.cors = true;
$.ajax({
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('X-SMP-APPCID', connectionID);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(appUser + ":" + appPass));
},
url: calURL, //calURL is the connection to backend
crossDomain: true,
dataType: "json",
processData: false,
xhrFields: {
withCredentials: true
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error fetching Data - " + errorThrown);
hideMainContent(false);
document.getElementById("data").innerHTML = "Error fetching data - " + errorThrown;
if(errorThrown.indexOf("Unauthorized") > -1){**// Invalid token reported here**
document.getElementById("setButton").innerHTML = "<p>Unauthorized error can occur if your password has expired or changed. Below option can be used to change application password to your new Password.</p><button onclick=\"changePassword()\" class=\"ui-btn style=\"margin:10% 25%;width:50%;\">Change Password</button>";
}
else{
document.getElementById("setButton").innerHTML = "<p>Temporary communication error. Please refresh after some time.</p>";
}
},
success: function(jsonData) {
},
});
return;
}
Any help in this regards is highly appreciated.
Thanks!

Trapping Function not defined error in Javascript and jQuery

Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});

Jquery asynchrone requests

I have implemented comet client in jquery as following:
$(document).ready(function () {
comet();
});
function comet(){
var cometJSON = {
'comet': 'id'
}
$.ajax({
type: "POST",
url: "http://localhost:8080/comet",
data: JSON.stringify(cometJSON),
async: true, /* Set async request*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){
console.log('suc');
eventReceived(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error: "+textStatus);
},
complete: function(jqXHR, textStatus){
console.log("Send new comet!");
comet();
}
});
};
Everything works fine, but I have always noisy spinner in my browser tab and my status pannel always shows: Waiting for localhost, how can I fix that?
The spinner indicates a connection in progress, which is exactly what is happening - after you receive an answer, in complete section you instantly trigger a new request, hence there is a connection in progress most of the time (pretty much always). To avoid it, you need to do a delay before a new request - setTimeout(comet, 1000) sounds like a good alternative to the last comet();
I implemented the same thing a while back and ran into the same problem:
https://github.com/tenorviol/cometjax
To solve the problem of the forever spinner, put a timeout on your initial ajax call, e.g.:
$(document).ready(function () {
setTimeout(function() {
comet();
}, 10);
});

Categories

Resources