Ajax request succeeds in Chrome but fails in Firefox - javascript

I have a javascript function that makes an ajax call to a PHP page for some database transactions and data processing. Here is the function:
function processQuizResults()
{
console.log("Processing results...");
var selections = [];
for (var i = 1; i <= 8; i++)
{
var thestr = "#sel" + i;
$(thestr).is(':checked') ? selections.push(1) : selections.push(0);
}
var URLcode = '<?php echo $URLcode; ?>';
var ajaxURL = "/processNewData.php?qid=" + URLcode + "&res=";
for (var i = 0; i < 8; i++)
{
ajaxURL += selections[i];
}
$.ajax({
url: ajaxURL,
type: 'post'
})
.done(function () {
console.log("ajax success.");
})
.fail(function () {
console.log("ajax failure.");
});
}
In Chrome, the browser makes the Ajax call, I see the breakpoints in my processNewData.php get hit (if I have some set) in visual studio, and the data comes out clean and showing up in my database properly on the other side. However, in firefox, running this exact same function has the $.ajax go into its .fail method, and the processNewData.php code never gets executed.
I have no idea how to debug an issue such as this and I have no idea what could be causing the problem. Can anyone kindly tell me where I'm going wrong?

According to this answer you're probably running into CORS issues.
From what domains are you serving the server-side app and the front-end? Try to make sure they're on the same domain and see if you get the same error.

Related

Error looping through array after upload to server

I'm using jquery.csv.min.js to create an array based on a csv. This part works fine. However, when I try and parse that 2d array into sessionStorage items, I'm getting the dreaded "Uncaught TypeError: Cannot read property '0' of undefined". Here's what I have so far:
var stationData;
var station = "";
// Gather data from CSVs
$.ajax({
type: "GET",
url: "document.csv",
dataType: "text",
success: function(response){
stationData = $.csv.toArrays(response);
console.log(stationData); // This works and confirms the array in the console
console.log("Station Variables Success!");
}
});
// Parse array into sessionStorage items
$(document).ready(function() {
setTimeout(() => {
station = getUrlParameter('stn');
var v;
var varLen = stationData[0].length;
for(v = 0; v < varLen; v++) {
sessionStorage.setItem(stationData[0][v], stationData[station][v]); // Line producing error
console.log("Setting sessionStorage:" + stationData[0][v] + " to \"" + stationData[station][v] + "\"");
}}, 2000);
});
When I run this on my local XAMPP Apache server, I was getting the same TypeError until I included the setTimeout() to space it out a bit figuring it was trying to set the storage items before the array could finish loading and it worked. Just a 10ms timeout is enough to run it on my local server, which is why it's there. However, when I try and upload this to our live server, the TypeError comes back. I've tried increasing the timeout in increments upto 10000ms but it's still happening. I've googled around with no luck, so I'm hoping someone here might be able to share some insight!
It's throwing TypeError because you are trying to read the value of an asynchronous operation before its returned by the server.
Increasing the timeout is not the option.
You just need to slightly refactor your code like this -
$(document).ready(function() {
function fetchCSVFromServer(successCb, errorCb) {
return $.ajax({
type: "GET",
url: "document.csv",
dataType: "text"
})
.done(successCb)
.fail(errorCb);
}
var successCb = function(response){
// Parse array into sessionStorage items
var stationData = $.csv.toArrays(response);
console.log(stationData); // This works and confirms the array in the console
console.log("Station Variables Success!");
setTimeout(() => {
var station = getUrlParameter('stn');
var varLen = stationData[0].length;
for(let v = 0; v < varLen; v++) {
sessionStorage.setItem(stationData[0][v], stationData[station][v]); // Line producing error
console.log("Setting sessionStorage:" + stationData[0][v] + " to \"" + stationData[station][v] + "\"");
}
}, 2000);
};
var errorCb = function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR);
};
fetchCSVFromServer(successCb, errorCb);
});
This code has 2 parts to it, first making the XHR using the $.ajax in the fetchCSVFromServer function and the second synchronizing the code flow which follows the asynchronous XHR call which is written in the successCb callback.
The trick is to synchronize the callback to run only after the server has sent its response in the .done callback.
This is a well known and a solved problem, for more details refer this question.

Works perfect locally but on server: Failed to load resource: 500 (Internal Server Error)

I have a MVC5 web application which i have been working for a while. When i work on local it works perfect. But when i publish it to our company server, in a section where i print a receipt im having "Failed to load resource" error. As I said it works perfect when im working on local. Im using devexpress xtrareport .print() method to print the receipt. Here are some codes that im using:
POST method, this is the view where i get the error:
function result() {
$(document).ready(function () {
value = document.getElementById('tutar').value;
var value3 = document.getElementById('bankalar').value;
var value2 = parseFloat(value);
try {
value1 = document.getElementById('1001').innerHTML;
} catch {
value1 = "Girilmedi";
}
if (document.getElementById("musteriAdi0").value == "") {
alert("Müşteri Adı Girilmeden İşlem Yapılamaz");
for (var u = p; u < i; u++) {
try {
var element = document.getElementById(u);
var row = element.parentNode.parentNode;
row.parentNode.removeChild(row);
} catch {
}
}
window.location.href = '#Url.Action("HizliAlimSatim", "Kuyumcu")';
}
else {
ekle();
var m = JSON.stringify({
'model': things, 'toplam': value2, 'personel': value1, 'KrediKarti': value3
});
things = [];
$(function () {
$.ajax({
type: "POST",
url: "/Kuyumcu/HizliAlimSatim",
contentType: "application/json; charset=utf-8",
dataType: "Json",
data: m,
success: function (data) {
if (data.includes("/Kuyumcu/Document") == false) {
g = g - i;
} else {
alert("İşlem Başarılı!");
//window.open(data, '_blank');
document.getElementById('tutar').value = 0;
toplam = 0;
degistir();
for (var u = p; u < i; u++) {
try {
var element = document.getElementById(u);
var row = element.parentNode.parentNode;
row.parentNode.removeChild(row);
} catch {
}
}
p = i;
window.location.reload(true);
}
}
});
});
}
});
}
this is the controller where i call print method:
Fis report = new Fis();
report.Parameters["FisNo"].Value = id;
report.Parameters["Musteri"].Value = model[0].MusteriAdSoyad;
report.Parameters["Islemci"].Value = personel;
report.CreateDocument(false);
//report.ShowPreview();
report.PrintingSystem.ShowMarginsWarning = false;
report.Print();
return Json(Url.Action("Document", "Kuyumcu");
I have been trying to solve the issue for 2 days, I thought its a server side problem but whatever i changed it didnt work.
The XtraReport.Print method from your controller is invoked at the server side - that's why it works when you run your application on localhost. When you deploy it to the production server, the Print method will be executed at the server's machine - not the client one.
Assuming that you use a DocumentViewer to display a report on your web page, use the viewer's client-side API (see the Print method) to print a report. For instance, refer to the sample code snippet from the How to display print dialog after the WebDocumentViewer is loaded on the web page thread.
If you want to print a report without displaying it, use the approach shown in the following example.

recaptcha responded, but Ajax not getting it

So I'm having some trouble with my code. It seems that when I get the reCAPTCHA response it loads when I alert the variable, but AJAX isn't wanting to get it.
var url="";
if (DEPOSIT) {
url = "/get_inv?" + opts;
} else {
var g = grecaptcha.getResponse();
url = "/get_bank_safe?g-recaptcha-response=" + g;
}
alert(url);
$.ajax({
"url": url,
success: function(data) {
try {
alert(data);
data = JSON.parse(data);
Yes I've gotten a valid response from the URL variable itself, but when announcing the AJAX variable 'data', nothing is persevered. Therefore JSON cannot parse 'data'.
It even states that "url" : url.
So I'm not sure how to go about this. If there is any solution please alert me of so.
Thanks! ~LTn | mrgreen33gamer

Performance multiple ajax call in Javascript

I am developing a module in Javascript, that in some strange cases, will launch multiple AJAX call to a web service in a range of Ips. For example:
var _requests = [],
_found = false;
for( var i = 1; (i < 255 && !_found); i++ ){
_requests.push( $.ajax({
url: "http://192.168.1." + i + "/service?action=example",
type: "GET",
success: _callback
}) );
}
var _callback = function( data, status, petitionInfo ) {
_found = true;
var _requestsToCancel = _requests.length;
while( _requestsToCancel-- ){
_requests[_requestsToCancel].abort();
}
};
In terms of performance, is it necessary (convenient), cancel every AJAX petition? Or it is irrelevant? When one ip responses, no other ip will do it. Putting a low timeout would be better for performance?
As you have already started the requests, each server will receive a request.
I'm assuming however that only one will respond and the others will time out. In which case I would recomend cancelling the other requests to save resources on the client.

Javascript Array loses data

I'm having trouble getting my information into an array in an ajax call, if I alert the information right after I insert it into the array it works fine, but if I do it at the end it alerts unidentified. I made sure that books is declared outside so it doesn't interfere.
var books = [];
$.ajax({
url: 'getFolderContents.php',
dataType: 'json',
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
},
error: function()
{
alert("error");
}
});
alert(books[0]);
Your
alert(books[0]);
will be executed while the Ajax call is running and therefore will not have any elements at this point of execution yet. Ajax is asynchronous - while you are doing a request to your PHP script your script continues execution.
Put all actions with books in your success function.
Another hint: As of jQuery version 1.8 you cannot longer use the parameter async: false to create a synchronous "A"jax call. You have to use the callback functions. Have a look at the docs for $.ajax
Your array hasn't lost any data; the data hasn't been put in there yet. The 'A' stands for "asynchronous", meaning your success callback hasn't run yet at the time you call the alert.
Put the alert inside your callback instead:
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
alert(books[0]);
},
Your alert is executing before the success function is called. Perhaps seeing the same code using a promise will make things clearer.
$.ajax( url: 'getFolderContents.php', dataType: "json" )
//the then function's first argument is the success handler
.then(function( data ) {
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
alert(books[0]
});
});
I always feel this syntax makes async stuff make more sense. Otherwise this code functions exactly like Blazemonger's correct answer.
Your AJAX call is asynchronous, that's why it is undefined.
The alert at the end happens before the ajax success callback, because ajax is asynchronous.

Categories

Resources