I've got a JavaScript function that I want to report an alert message to the users if it successfully updates the database, or if it has an error.
In the main X.JSP file I have:
function startRequest(pChange)
{
//alert("startRequest");
createXmlHttpRequest();
//alert("sending message");
//var u1=document.f1.user.value;
//alert("Running startRequest for: " + pChange.id);
//xmlHttp.open("GET","updateEntry.jsp&pID=pChange.id&pStatus=pChange.status&pAddress=pChange.address&pDate=pChange.date&pNotes=pChange.note&pAssigned=pChange.assigned" ,true)
xmlHttp.open("GET","updateEntry.jsp?pID=" + pChange.id + "&pAddress=" +pChange.address + "&pStatus=" + pChange.status +"&pNote=" + pChange.notes +"&pAssigned=" +pChange.assigned ,true)
//alert(xmlHttp.responseText);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
function handleStateChange()
{
//alert("handleStateChange");
var message = xmlHttp.responseText;
alert("Return Code:" + message);
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
}
}
else
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
}
I then run a method in updateEntry.jsp that does a number of things, but of interest is this section:
if(nId.equals("NMI")||nId.equals("MI")||nId.equals("NI")||nId.equals("SA")||nId.equals("S"))
{
org.hibernate.Query query2 = session2.createQuery("update Leads set Status = :nstatus where Id = :nid");
query2.setParameter("nid", nId);
query2.setParameter("nstatus", nstatus);
query2.executeUpdate();
out.println("Update successfully with: " + nstatus);
// Actual contact insertion will happen at this step
session2.flush();
session2.close();
}
else
{
out.println("Status must be: NMI, MI, NI, SA or S");
}
My understanding is that this should only create a single alert, if the function completes successfully. Instead it creates like 9 alerts all of which are blank. What am I doing wrong? I'm seeing both the "Return Code: " message and a blank " " message, (two different sections of code) but both output blank message variables.
If the readystate is not 4, it does not mean it is an error. Ajax has multiple states that inform the clientside about what is happening. Your code says that those connection states are all errors.
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
} <-- your else should most likely be up here
}
else <-- this is incorrect
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
Read the document at MDN - Ajax Getting Started
Related
I am using qzprint API for printing labels in my open cart extension. Everything was working fine but suddenly it stopped working on FF. In Internet explorer it works fine. If i add alerts in my functions of applet it works fine on firefox as well but not sure why not with out alerts. here is my code.
calling applet functions in my header.tpl
<script type="text/javascript">
deployQZ('<?php echo HTTP_CATALOG ?>');
useDefaultPrinter();
<script>
Applet file containing functions
function deployQZ(path) {
//alert("alert for printing label");
pathApplet = path + 'java/qz-print.jar';
pathJnlp = path + 'java/qz-print_jnlp.jnlp';
var attributes = {id: "qz", code:'qz.PrintApplet.class',
archive: pathApplet, width:1, height:1};
var parameters = {jnlp_href: pathJnlp,
cache_option:'plugin', disable_logging:'false',
initial_focus:'false'};
if (deployJava.versionCheck("1.7+") == true) {}
else if (deployJava.versionCheck("1.6+") == true) {
attributes['archive'] = 'java/jre6/qz-print.jar';
parameters['jnlp_href'] = 'java/jre6/qz-print_jnlp.jnlp';
}
deployJava.runApplet(attributes, parameters, '1.5');
}
/**
* Automatically gets called when applet has loaded.
*/
function qzReady() {
// Setup our global qz object
window["qz"] = document.getElementById('qz');
//var title = document.getElementById("title");
if (qz) {
try {
//title.innerHTML = title.innerHTML + " " + qz.getVersion();
//document.getElementById("content").style.background = "#F0F0F0";
} catch(err) { // LiveConnect error, display a detailed meesage
document.getElementById("content").style.background = "#F5A9A9";
alert("ERROR: \nThe applet did not load correctly. Communication to the " +
"applet has failed, likely caused by Java Security Settings. \n\n" +
"CAUSE: \nJava 7 update 25 and higher block LiveConnect calls " +
"once Oracle has marked that version as outdated, which " +
"is likely the cause. \n\nSOLUTION: \n 1. Update Java to the latest " +
"Java version \n (or)\n 2. Lower the security " +
"settings from the Java Control Panel.");
}
}
}
/**
* Returns is the applet is not loaded properly
*/
function isLoaded() {
if (!qz) {
alert('Error:\n\n\tPrint plugin is NOT loaded!');
return false;
} else {
try {
if (!qz.isActive()) {
alert('Error:\n\n\tPrint plugin is loaded but NOT active!');
return false;
}
} catch (err) {
alert('Error:\n\n\tPrint plugin is NOT loaded properly!');
return false;
}
}
return true;
}
function useDefaultPrinter() {
//alert("alert for printing label");
if (isLoaded()) {
// Searches for default printer
qz.findPrinter();
// Automatically gets called when "qz.findPrinter()" is finished.
window['qzDoneFinding'] = function() {
// Alert the printer name to user
var printer = qz.getPrinter();
//alert(printer !== null ? 'Default printer found: "' + printer + '"':
//'Default printer ' + 'not found');
document.getElementById("name_printer").innerHTML = 'Default printer found: "' + printer + '"';
// Remove reference to this function
window['qzDoneFinding'] = null;
defaultFound = true;
};
}
}
As u can see in my deployqz() and usedefaultprinter() functions i have alert on first line which is in comments if its commented it doesn't work in fire fox and if not commented than it works fine. With comments i get alert message from isLoaded() function "Print plugin is NOT loaded properly!".
Also in my console i get this
An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
Try this:
If the qzReady is called by the applet when ready, put useDefaultPrinter inside that function.
if isLoaded takes some time, call useDefaultPrinter in there too using setTimeout
Like this
<script type="text/javascript">
deployQZ('<?php echo HTTP_CATALOG ?>');
<script>
Applet file containing functions
var qz;
function deployQZ(path) {
pathApplet = path + 'java/qz-print.jar';
pathJnlp = path + 'java/qz-print_jnlp.jnlp';
var attributes = {id: "qz", code:'qz.PrintApplet.class',
archive: pathApplet, width:1, height:1};
var parameters = {jnlp_href: pathJnlp,
cache_option:'plugin', disable_logging:'false',
initial_focus:'false'};
if (deployJava.versionCheck("1.7+") == true) {}
else if (deployJava.versionCheck("1.6+") == true) {
attributes['archive'] = 'java/jre6/qz-print.jar';
parameters['jnlp_href'] = 'java/jre6/qz-print_jnlp.jnlp';
}
deployJava.runApplet(attributes, parameters, '1.5');
}
/**
* Automatically gets called when applet has loaded.
*/
function qzReady() {
// Setup our global qz object
qz = document.getElementById('qz');
if (qz) {
try {
useDefaultPrinter();
} catch(err) { // LiveConnect error, display a detailed meesage
document.getElementById("content").style.background = "#F5A9A9";
alert("ERROR: \nThe applet did not load correctly. Communication to the " +
"applet has failed, likely caused by Java Security Settings. \n\n" +
"CAUSE: \nJava 7 update 25 and higher block LiveConnect calls " +
"once Oracle has marked that version as outdated, which " +
"is likely the cause. \n\nSOLUTION: \n 1. Update Java to the latest " +
"Java version \n (or)\n 2. Lower the security " +
"settings from the Java Control Panel.");
}
}
else { setTimeout(useDefaultPrinter,300); }
}
/**
* Returns is the applet is not loaded properly
*/
function isLoaded() {
if (!qz) {
alert('Error:\n\n\tPrint plugin is NOT loaded!');
return false;
} else {
try {
if (!qz.isActive()) {
alert('Error:\n\n\tPrint plugin is loaded but NOT active!');
return false;
}
} catch (err) {
alert('Error:\n\n\tPrint plugin is NOT loaded properly!');
return false;
}
}
return true;
}
function useDefaultPrinter() {
//alert("alert for printing label");
if (isLoaded()) {
// Searches for default printer
qz.findPrinter();
// Automatically gets called when "qz.findPrinter()" is finished.
window['qzDoneFinding'] = function() {
// Alert the printer name to user
var printer = qz.getPrinter();
//alert(printer !== null ? 'Default printer found: "' + printer + '"':
//'Default printer ' + 'not found');
document.getElementById("name_printer").innerHTML = 'Default printer found: "' + printer + '"';
// Remove reference to this function
window['qzDoneFinding'] = null;
defaultFound = true;
};
}
else { setTimeout(useDefaultPrinter,300); }
}
I have made admin panel where setup notification alerts using ajax. It is working fine, but after few minutes than it starts to freeze the browser. Any idea what I am doing wrong, as it is my first Ajax project.
Following are codes which I am using, I used setInterval in a function which is called by body onload event.
<html>
<body onload="process()">
<-- Some notification divs to be replaced by javascript -->
</body>
<html>
JavaScript
<script>
var xmlHttp = createXmlHttpRequestObject();
function process() {
setInterval('process()', 10000);
if (xmlHttp) {
try {
xmlHttp.open("GET", "response.json", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
} catch (e) {
console.log("Can't connect to server:\n" + e.toString())
};
}
}
function handleRequestStateChange() {
if (xmlHttp.readyState == 4) {
{
if (xmlHttp.status == 200) {
try {
handleServerResponse();
} catch (e) {}
} else {
console.log("There was a problem retrieving the data:\n" + xmlHttp.statusText);
}
}
}
}
function handleServerResponse() {
responseJson = JSON.parse(xmlHttp.responseText);
for (var i = 0; i < responseJson.newbooking.length; i++) {
// html += "<li><a href='admin_user.php?id=" + + "'><div class='desc'>" + responseJson.users[i].first_name + ", " +responseJson.users[i].last_name + " joined</div></a></li>";
bookinghtml += "<li><a href='makeinvoice.php?bookingid=" + responseJson.newbooking[i].booking_id + "'><span class='subject'><span class='from'>" + responseJson.newbooking[i].company_name + " </span><span class='time'> " + responseJson.newbooking[i].user_name + " </span></span>";
bookinghtml += "<span class='message'> from " + responseJson.newbooking[i].start_date + ", " + responseJson.newbooking[i].batches + " " + responseJson.newbooking[i].campaign + "</span></a></li>";
}
myDiv = document.getElementById("bookinginfo");
myDiv.innerHTML = bookinghtml;
}
Every time you make a request, you tell it to make a request every 10 seconds.
So onload, you make a request and start a timer.
10 seconds later you make another request and start another timer.
10 seconds later you make two requests, each of which starts another timer.
10 seconds later you make four requests, each of which starts another timer.
and so on.
It starts freezing, because it eventually is making trying to make requests faster then the computer can handle.
Use setTimeout, not setInterval.
(Also, you should pass a function, not a string: setTimeout(process, 10000));
I am trying to make an Ajax request to the page specified in the drop down menu. I have successfully used most of my script code in binding a mouse click to table rows, but it does not work in this case when I try it here. I get ReferenceError: fnsuccess is not defined. I did not get this ReferenceError when I used most of this script to bind a mouse click.
<script type="text/javascript">
function isValid(frm){
$("#courseinfo").hide();
$("#frm").validate();
var four04 = $("#frm :selected").val();
console.log('Testing console');
if (four04 == "404")
{
console.log("404");
var txt = ($(this).text());
$.ajax({url:"404.json", data:{coursename:txt}, type:"GET", dataType:"json",
success:fnsuccess, error:fnerror});
function fnsuccess(serverReply) {
if (serverReply && serverReply.info) {
$("#infohere").text(serverReply.info);
$("#courseinfo").show();
} else
fnerror();
}
function fnerror() {
alert("Error occurred");
$("#courseinfo").hide();
}
}
else
{
console.log("else 404");
}
}
</script>
Course -->
Rating
404 error
403 error
Fix:
<script>
function isValid(frm){
$("#otherPageContent").hide();
$("#frm").validate();
var dropDownSelected = $("#frm :selected").val();
if (dropDownSelected == "404")
{
var txt = ($(this).text());
$.ajax({url:"404_error.json",
data:{coursename:txt},
type:"GET",
dataType:"json",
success:fnsuccess,
error: function(xhr, status, error){
$("#infohere").text(
"The requested page was: 404_error.json" +
". The error number returned was: " + xhr.status +
". The error message was: " + error);
$("#otherPageContent").show();
}
}); // end of ajax
} // end of if 404
function fnsuccess(serverReply) {
if (serverReply && serverReply.info) {
$("#infohere").text(serverReply.info);
$("#otherPageContent").show();
}
}
return false; // pause message on screen
}
</script>
define function fnsuccess(serverReply) and fnerror outside isValid function
I wrote a Flickr search engine that makes a call to either a public feed or a FlickrApi depending on a selected drop down box.
examples of the JSONP function calls that are returned:
a) jsonFlickrApi({"photos":{"page":1, "pages":201, "perpage":100, "total":"20042", "photo":[{"id":"5101738723"...
b) jsonFlickrFeed({ "title": "Recent Uploads tagged red","link": "http://www.flickr.com/photos/tags/red/","description": "", ....
the strange thing is that in my local install (xampp) both work fine and i get images back BUT when i host the exact same code on the above domain then the jsonFlickrApi doesn't work. What i notice (by looking at Firebug) is that for the jsonFlickrApi the response Header says Connection close
Also, Firebug doesn't show me a Response tab when i submit a request to the jsonFlickrApi
here is the code:
function makeCall(uri)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", "jsonget.php?url="+uri, true);
xmlhttp.send();
}
function jsonFlickrApi(response)
{
var data= response.photos.photo ;
var output = "";
output += "<img src=http://farm" + data[4].farm + ".static.flickr.com/" + data[1].server + "/" + data[4].id + "_" + data[4].secret + ".jpg>";
document.getElementById("cell-0").innerHTML = output ;
}
//Public Feed
function jsonFlickrFeed(response)
{
var data= response.items[0].media.m ;
alert(data);
var output = "";
output += "<img src=" + data+ ">";
document.getElementById("cell-0").innerHTML = output ;
}
function callback()
{
//console.log("Ready State: " + xmlhttp.readyState + "\nStatus" + xmlhttp.status);
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonResponse = xmlhttp.responseText;
jsonResponse = eval(jsonResponse);
}
}
examples of calls:
a)
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
b)
http://api.flickr.com/services/feeds/photos_public.gne?tags=red&format=json×tamp=1339190039407
Question: why does my connection close? why is it working on localhost and not on the actual domain?
Looking at the HTTP response headers of
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
I get a 302 with location
http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
So, what flicker wants to tell you is "use www.flicker.com instead of flicker.com!". With this URL I get content.
window.onerror = function(type, file, line){
if(type) {
console.log(type);
}
if(file) {
console.log(file);
}
if(line) {
console.log(line);
}
}
this code returns "Script error" when there is an error at some of the .js files. I need the type, file and line of the error. How can I get it?
When window throws error this script works perfect but it is not the same when there is error in the .js file.
I know that these things I can find on the console but imagine that I don't have one and i cannot install.
window.onerror = ErrorLog;
function ErrorLog (msg, url, line) {
console.log("error: " + msg + "\n" + "file: " + url + "\n" + "line: " + line);
return true; // avoid to display an error message in the browser
}
The post of Cryptic "Script Error." reported in Javascript in Chrome and Firefox should answer your "Script Error." problem. Namely it is probably caused by "Same origin policy".
Though I am still looking for why webkit will give me "undefined" file name and "0" line number for uncaught exception.
Here's what I use to capture errors. I have it request an image whose url points to a server side script.
function logJSErrors(errObj) {
if (!errObj || !errObj.lineNumber || errObj.lineNumber == 0) {
return; // can't use it any way.
}
if (window.location && window.location.toString().indexOf('rfhelper32.js') >= 0) {
return; // ignore the stupid Norton/Firefox conflict
}
var img = new Image();
img.src = "/jserror?m=" + encodeURIComponent(errObj.message) +
"&location=" + encodeURIComponent(window.location) +
"&ln=" + encodeURIComponent(errObj.lineNumber) +
"&url=" + encodeURIComponent(errObj.fileName) +
"&browser=" + encodeURIComponent(errObj.browserInfo);
}
window.onerror = function (msg, url, line) {
logJSErrors({ message : msg,
lineNumber : line,
fileName : url,
browserInfo : window.navigator.userAgent
});
// if a jquery ajax call was running, be sure to make the spinning icons go away
if (jQuery) {
try {
jQuery.event.trigger("ajaxStop");
} catch(e) {/* do nothing */
}
}
};