XMLHttpRequest Error Checking- Better way to write this? - javascript

I wrote a webpage that runs from the desktop to grab information off of a public website. I am trying to make it to where 1) if there is no internet connection there is a alert 2) if there is a an internet connection but somehow the info was not retrieved correctly, the user would be alerted.
The try and catch works for the test if there is no internet connection.
I am using the xml.status codes for the second test...if the website is active but the info that is pulled is messed up....that test condition isn't working the way I wanted it. I tried giving the xml.open a bogus website and was expecting a non 200-300 status code. But it did not work...instead the catch statement was activated. Why is this? And is there a better way to write this?
Also, on a side note I had return ""; because I the calling variables that use this could not be have null or undefined: variable = getInfo(); n.setAttribute("placeholder", variable);
function getInfo() {
var xml = null;
xml = new XMLHttpRequest();
try {
xml.open("get", "http://example.asp", false);
xml.send(null);
if ((xml.status >= 200 && xml.status <= 300) || xml.status == 304) {
var hi = xml.responseText;
hi = hi.replace(/(\r\n|\n|\r)/gm, "");
var what1 = /winning_number_sm.*?ul/
var what2 = /\d+/g
hi = what1.exec(hi);
var temp;
for (i = 0; i < 6; i++) {
if (null !== (temp = what2.exec(hi))) {
numbers[i] = temp;
}
}
return numbers;
} else {
alert("Error Connecting to Website! You will have to eneter informatin by hand");
return "";
}
} catch (e) {
alert("No Internet Connection! You will have to enter information by hand");
return "";
}
}

I don't know if you can use jQuery framework but to get error from an ajax connection (test if a website is up) you can do easely that :
//your ajax object
var request = $.ajax({
url: "http://www.exemple.com/script.php",
type: "POST",
data: {/*your datas*/},
dataType: "html"
});
request.done(function(msg) {
//make your stuff automatically
});
request.fail(function(jqXHR, textStatus) {
alert( "Error Connecting to Website! You will have to enter informatin by hand");
});

An other approch can be to call a local php script whose test distant url with curl function (ex : http://www.php.net/manual/en/function.curl-error.php)

Related

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.

Can't get data out of indexedDB

Here's the function I'm trying to call:
function restoreCurrent() {
var tzact = db.transaction(['Picture'],"readonly").objectStore("Picture").get(2);
tzact.onerror = function(event) {
alert ("Failed to retrieve the data.");
}
tzact.onsuccess = function(event) {
document.getElementById("demo").innerHTML += "Transaction success.<br />";
}
}
window.onload = function() {
restoreCurrent();
}
As you can see, it should output something on either a success or an error. In fact it doesn't output anything. I had further code after this in the .onsuccess function, but nothing gets executed. And the line where it stops working is the database call, I've tested that much.
For the record, both this line of code when I created the database
var tzact = db.transaction(['Picture'], "readwrite").objectStore("Picture").add({id : 2, pictureData : working});
and this line when I try and update that particular record
var tzact = db.transaction(['Picture'], "readwrite").objectStore("Picture").put({id : 2, pictureData : working});
seemed to execute OK -- or at least, the functions they were embedded in went on to output success messages. Without being able to extract any data it's hard to be sure.
EDIT: Figured it out myself. The answer is that I had to put this into each function:
var request = window.indexedDB.open("[database name]",5);
request.onerror = function() {
alert ("Failed to open the database.");
}
request.onsuccess = function() {
var db = request.result;
var tzact = db.transaction(['Picture'],"readonly").objectStore("Picture").get(2); // or "readwrite" and .put(2), as the case might be
tzact.onerror=function() {
alert ("Data transaction failed.");
}
tzact.onsuccess=function() {
document.getElementById("demo").innerHTML += "Data transaction successful.<br />";
if (tzact.result) {
var working = tzact.result.pictureData;
// the rest of the function goes here
} else {
alert ("No data received.");
}
}
}

How to Send Ajax Request After A Specific Time

How to Send Ajax Request in specific time and only that particular event
I m User Time Interval But it’s not Working.
i want get data in request 1 for use in request 2 but it get null data in request 2
setInterval()
it's not Working for me.
I want To send Request 2 After the some time of Request 1
Request 1:-
$(document).on("change", ".supplyItem", function (event) {
var id = $(this).attr("data-id");
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospital = $("#hospital").val();
var physician = $("#physician").val();
var category = $("#category").val();
var manufacturer = $("#manufacturer").val();
var project = $("#project").val();
if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
data: {
supplyItem: supplyItem,
hospital: hospital,
project: project,
},
success: function (data) {
console.log(id);
if (data.status) {
var html_data = '';
var item = data.value;
console.log(item);
$('.hospitalPart[data-id=' + id + ']').val(item.hospitalNumber);
$('.mfgPartNumber[data-id=' + id + ']').val(item.mfgPartNumber);
// $('.mfgPartNumber[data-id='+id+']').text('something');
} else {
$('.hospitalPart[data-id=' + id + ']').val('');
$('.mfgPartNumber[data-id=' + id + ']').val('');
}
$('.quantity[data-id=' + id + ']').val('');
$('.purchaseType[data-id=' + id + ']').val('');
$('#serial-text' + id).val('');
$('#serial-drop' + id).val('');
$('#serial-drop' + id).empty();
}
});
}
});
Request 2:-
$(document).on('change', '.supplyItem', function (event) {
var timer, delay = 2000;
var id = $(this).attr("data-id");
var client = $("#hospital").val();
timer = setInterval(function(){
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospitalPart = $(".hospitalPart[data-id=" + id + "]").val();
var mfgPartNumber = $(".mfgPartNumber[data-id=" + id + "]").val();
alert(supplyItem);
alert(hospitalPart);
alert(mfgPartNumber);
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
data: {
supplyItem: supplyItem,
hospitalPart: hospitalPart,
mfgPartNumber: mfgPartNumber,
client: client,
},
success: function (data) {
if (data.status) {
var html_data = '';
var check = data.value;
if (check == 'True') {
html_data += "<option value=''>Purchase Type</option><option value='Bulk'>Bulk</option><option value='Consignment'>Consignment</option>";
$('.purchaseType[data-id=' + id + ']').html(html_data);
} else {
html_data += "<option value=''>Purchase Type</option><option value='Consignment'>Consignment</option>";
$('.purchaseType[data-id=' + id + ']').html(html_data);
}
}
}
});
}, delay);
clearInterval(timer);
});
You can move Request 2 into a function and this JS code will call the Request2 function after given interval of time (milliseconds), I have set it to 5 seconds for now.
setInterval(function () { Request2(); }, 5000);
function Request2(){
console.log("Request 2 called");
//add request 2 code here
}
jQuery's $.ajax method returns a promise, which is passed the result of the server-side call. You can chain these calls together so that you can build the result of multiple ajax calls. When you use it this way you do away with success callbacks as they are no longer necessary.
Applied to your code it might looks something like this:
$(document).on("change", ".supplyItem", function (event) {
var id = $(this).attr("data-id");
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospital = $("#hospital").val();
var physician = $("#physician").val();
var category = $("#category").val();
var manufacturer = $("#manufacturer").val();
var project = $("#project").val();
if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
data: {
supplyItem: supplyItem,
hospital: hospital,
project: project,
})
.then(function(data1){
// process result of call1 and make call2
var item = data1.value;
return $.ajax({
url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
data: {
supplyItem: supplyItem,
hospitalPart: value.hospitalPart, // note using result from 1 directly
mfgPartNumber: value.mfgPartNumber,
client: hospital
}
});
})
.then(function(data2){
// process result of call2
});
};
});
The point here is that you don't need to stash the result of call1 into some elements and re-read them before making call2, and trying to wait enough time before making call2. You just chain it all together with then.
Ok first though: Instead of using setInterval and then clearing the interval after it has run a single time, why not just use
setTimeout(function, delay);
Then personally I prefer to use XMLHttpRequest instead of Jquery AJAX, Jquery uses XMLHttpRequest at its base anyway,I just prefer it so I dont have to use Jquery, but if your already using Jquery in your site then it should be no more heavy. Here is a quick example of XMLHttpRequest so u can use it if you prefer.
var xhr = new XMLHttpRequest();
xhr.open("POST", 'URL::to("admin/repcasetracker/getdevicedata")', true);
xhr.setRequestHeader("Content-Type", "application/json charset=utf8");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// content is loaded...
if (xhr.responseText) {
//Some code to run after the server responds and it was successfull
}
}
};
xhr.send(JSON.stringify({test:'test'})); //This is the data you are handing to the server
Notice the use of xhr.responseText, JQuery uses the same variable and this is usually the response from the server. One sure way to know is use your browser's debugging engine (F12 on Chrome and Firefox, have no idea on other browsers) to inspect the variables, it is very easy to ascertain the correct variable to use.
And then one last thought: I see you are not declaring the content-type and not JSON.stringify'ing() your data when you send it to the server.
Best way to debug a situation like this is 'proccess of elimation' so find out if the server is receiving the data then if the server is proccessing the data correctly and then check if the server is sending the data correctly.
If you are using Nginx use the /var/log/nginx/error.log to see if it throws any errors ( tip: tail -f /var/log/nginx/error.log | Apache uses /var/log/http/error.log on most distros ) and if you are using .NET just debug it in Visual Studio.
And read up on the Jquery success event there is 2 more arguments that gets passed - String textStatus and jqXHR jqXHR
http://api.jquery.com/jquery.ajax/
So to summarize:
Make sure to declare the dataType: 'json'
Use the correct variable, should be responseText
when passing the server data and using 'json' make sure to JSON.stringify() it
And I don't quite see why you want to use setTimeout in the first place.
If you are simply waiting for the server to respond then using any type of delay will be a terrible idea, instead use the events that gets fired after the server responds.
So in Jquery that is success: function() {} and error: function() {}
and in XMLHttpRequest its the xhr.onreadystatechange = function () { }

Ajax request succeeds in Chrome but fails in Firefox

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.

AJAX function not getting called - Database not getting called?

I'm trying to get my project running on the localhost. I'm having a problem with the built-in ajax function upon success. Here is the javascript function:
function getDecisions(page, searchstring) {
page = typeof page !== 'undefined' ? page : 1;
searchstring = typeof searchstring !== 'undefined' ? searchstring : '';
$('.loading-container').show();
if (searchstring != '') {
params = searchstring;
}
else {
params = getFilterObj();
params['page'] = page;
//Only get checked types
$('#types input[type="checkbox"]').each(function() {
if ( $(this).is(":checked") ) {
params[$(this).attr("name")] = 'True';
}
});
}
if ( $('input[name="approved-only"]:checked').val() == 'yes' ) {
params['approved-only'] = 'yes';
}
$.ajax({
url:'/dh',
data: params,
success: function(data) {
info = data.info;
newhtml = '';
if (info.length == 0) {
newhtml += '<tr><td colspan="18" style="text-align: center;">No results returned</td></tr>\n';
}
...
}
I know that the javascript function is working as I'm stepping through until the very last line of the function, but I'm not even sure if the ajax function is being called. I'm getting the following Internal Server Error (500):
Can anyone say what could be causing a 500 error on the localhost for this type of an ajax call? Or how I might see whether the ajax function is being called?
The ajax call is definitely being made. The reason I know this is because you are seeing the 500 server error. The 500 server error is a response from the server that means the request had some kind of error at the server. It looks like you are debugging in chrome. If that is the case, you can go to the Network tab in the developer tools and then as you step through your code, you will see an entry appear for that request. When the request completes, you will see the status update with error 500, which should match up with what you were seeing in the console. You can then click on that entry in the network tab, and hopefully be able to see the actual response from the server.
If you have control over the server, you might also be able to debug the webservice at that side and see what is going on.

Categories

Resources