For more clarity I made it simple (so let's presume that iframe.attr() will be called after previous load was fully completed):
var iframe = $("iframe");
var counter = 0;
var trackLoads = function(){
console.log("I was loaded:" + counter);
counter += 1;
};
iframe.load(trackLoads);
iframe.attr("src","http://stackoverflow.com/");
iframe.attr("src","http://localhost:9081/mobile/api/content/badPath"); //returns 204 No Content
iframe.attr("src","http://stackoverflow.com/");
Console log looks like this:
I was loaded:1
I was loaded:2
When the iframe loaded new content from stackoverflow.com, It trigger the callback "trackLoads", but iframe will never trigger callback for 204 No Content from some reason.
How to detect "204 No Content" after iframe has changed "src" attribute?
Change your previous code to this:
var trackLoads = function(response, status, xhr){
console.log("I was loaded:" + counter);
counter += 1;
if ( status == "error" && xhr.status == 204) {
console.log( "Sorry but there was an error: " + xhr.status + " " + xhr.statusText );
}
};
From: http://api.jquery.com/load/
Related
I am not getting a status of the website nor an error when executing the code when using the URL that is being generated. However, when I use 'http://google.com', the status shows and it takes a screenshot of the page. The URL that is being used is a correct one, when I open the URL in browser it is the Page I want. It seems like the page is unreachable but I am not getting an error nor a status update.
var size = 9;
var model = 'CQ2626';
function URL(size, model){
var baseSize = 580;
var shoeSize = size - 6.5;
shoeSize *= 20;
rawSize = shoeSize + baseSize;
var URL = 'http://www.adidas.com/us/' + model + '.html?forceSelSize=' + model + '_' + rawSize;
return URL
};
console.log(URL(size, model));
var page = require('webpage');
var webPage = page.create();
webPage.open(URL(size, model), function(status){
console.log("Status: " + status);
if(status === "success") {
webPage.render('example.png');
}
phantom.exit();
});
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 currently loading the same page 3 times with 3 different .load() calls. I am wanting to know if there is something I can do to optimize the code.
When I click a link currently it loads the page 3 times
$("#"+target).load(url + " #page", function(response, status, xhr){
if(status === "error")
{
$("#"+target).load('error.php?error=503 #page', function(response, status, xhr){
if(status === "error")
{
alert("Something has gone very wrong right now, please contact an admin quoting 'error.php'");
return;
}
}); // This should never fail but if it does kill the page
console.log('Content failed to load ' + xhr.status + ' ' + xhr.statusText);
//Force update the title to error
document.title = "Error";
$("#pageBreadcrumbs").load('error.php #breadcrumbs');
}
else
{
console.log('Content was loaded');
//Load the title dynamically
document.title = "Venus | " + name;
$("#pageBreadcrumbs").load(url + ' #breadcrumbs');
if(sidebar === true)
$("#pageSidebar").load(url + ' #sidebar');
}
Is there anyway I can shorten this to just 1 call to the url or error page and extract it from there?
You can use this code:
$.get(url, function(response) {
var $nodes = $(response);
... some conditions ...
var $container1 = $("#"+target).html('');
$nodes.find('#page').appendTo($container1);
... some conditions ...
var $container2 = $("#pageBreadcrumbs").html('');
$nodes.find('#breadcrumbs').appendTo($container2);
});
I'm not really sure that it works, but you can try it...
UPDATE
This code assumes that whole server response is wrapped in one container (div)
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
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.