Jquery getJson page never finishes loading - javascript

The following code calls the JSON and displays the results but then it seems like the page never completes loading. The browser still says connecting and view source never displays
Any ideas?
<script>
function getroadcondFiles () {
jQuery.support.cors = true
// electdiv=electdiv+"</center><br>";
$.getJSON('http://example.com?callback=?',function(dataa){
// console.log("before each");
//console.log(dataa.result.totalCount);
$.each(dataa.roadid, function(i,item){
document.write(item.desc+"<br>");
document.write(item.overstat[0]+"<br>");
document.write(item.weatherstat[0]+"<br>");
document.write(item.pavementstat[0]+"<br>");
});
;}).error(function(jqXHR, textStatus, errorThrown) { alert(errorThrown); });
;}
</script>
</head>
<body>
<script>
$=jQuery;
getroadcondFiles();
</script>

Check for an $.ajaxError or use your browser's debugger to get more insight in to the failure. Without knowing if the json call is failing (and no error besides "this doesn't work") there's no way to tell what's failing.
I recommend using $.ajax and the error property to determine if there is a problem occurring with the query. one you find out if it's the query or the script you'll be better informed on how to correct the issue.
it may not even be ajax failing though, it could be another script still processing. Once again, use your browser's debugging tools to get more insight in to what's actually the original problem.

Related

How to control error display by JavaScript in Chrome, eg 404 error?

I have tried use "try-catch" handle, but it doesn't work. Chrome would still display 404 URL error (I don't want to display it in console);
Sample code you can see below:
try {
$.post("/APIURL", function(data) {
$(".hint").fadeIn(300);
});
} catch (e) {
console.log(e);
}
Sorry, this is not possible. I think there was a workaround with try catch clauses in older IE versions, but thats not very useful. Anyway, 404 error should not be something to hide, and you should not make it part of your normal workflow - an error is an error. If you need to check the existence of the resource and you don't want to report it to the console, you could make a separate API endpoint that would check if the resource exists and simply return a boolean or something more complex.
While you can not disable the chrome console errors, there are multiple ways to catch errors which might get you closer to your goal.
First example, this just enables you to handle POST Failure without try/catch and gives you textStatus so you get some better feedback other than error or success.
//catching failure in post
$.post("/APIURL", function(data, textStatus) {
console.log("post success");
}).fail(function(data,textStatus){
console.log(textStatus);
});
the second will catch any ajax errors on the page in general, this might help to notify users of errors for any ajax requests, not just the one you implemented.
//catching ajax failure across the page
$( document ).ajaxError(function( event, request, settings ) {
$( "#msg" ).append( "<li>Error requesting page " + settings.url + "</li>");
});
here's a Jsfiddle to play around with https://jsfiddle.net/c6q6dfxt/

Simple Ajax jQuery get method not completing

This is my first use of Ajax. Here is the script I am trying to run:
$(document).ready(function() {
alert("on document ready");
$(document).click(function(e){
alert("inside click handler");
$.get("runner.php", function(data) {
alert("get method has completed");
});
});
});
The alerts: "on document ready" and "inside click handler" all display correctly but I cannot get the alert inside the $.get method to display. Also, the runner.php file is in the same directory as the JavaScript file. I eventually want to get information from the runner.php file but I cannot even make this $.get method complete.
I'm sure I'm missing something simple here, but this example was taken almost directly from the jQuery manual.
Try placing an absolute url to runner.php, so /js/runner.php or /runner.php whichever directory it's in.
Also if you have firebug installed, you can use it to view what the problem is. If it's telling you 404 Not Found then you will need to place the absolute url as I just mentioned.
Try to follow this pattern:
$.get("runner.php", function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
Where are these files? Are they on a web server or on your local computer? I had the same problem before and the reason being I was trying to access a file that was located on my local computer so I would always get an error
AJAX request using jQuery does not work
I fixed it by setting up a local web server and the same code worked beautifully :)
If you are using jquery 1.8 or later, then you need to use the fail() function to report errors with your call to your PHP, like this:
.get("runner.php", function() {
alert("success");
})
.fail(function() {
alert("An error happened, check PHP script for problems.");
})
Note: jQuery 1.8 deprecated the error callback and replaced it with the .fail() function.
The most likely cause of nothing happening on the callback is a 404 or 500 error. As with a few other answers, make sure to add a fail listener to your $.get request and you can console.log(data); to determine what's going wrong on the server side.

jQuery ajax request to Flickr sporadically fails

Occasionally, an ajax request to Flickr's api will fail. I'm not sure if I'm doing something wrong here - or if I'm just not handling things correctly - but the code works over 90% of the time. When it doesn't work, I get the following error message from Firefox's console:
TypeError: jQuery19109306644694293944_1362865216185 is not a function
(I am letting jquery generate the callback, which is why the callback is named like that.)
This is the code that sometimes fails:
function getAppropriateSize(photo){
console.log("In getAppropriateSize");
/** stuff. query is defined here **/
$.ajax({
url: 'http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&format=json&api_key='+flickrKey+'&photo_id='+query.id,
dataType:'jsonp',
jsonp:'jsoncallback',
timeout:3000,
success: function(sizes){
console.log("In success - getAppropriateSize");
/**determine the correct size**/
flickrURL = sizes.sizes.size[currVal].source;
},
error: function(xmlhttprequest,textstatus,msg){
console.log("In error - getAppropriateSize");
/* handle error*/
}
});
}
I've checked what's returned when this happens and JSLint says it's valid javascript. flickrURL also gets set to a valid URL. I'm pretty mystified about what's causing this error - any help would be appreciated.
Edit: I was messing around and this time getAppropriateSize just received two separate messages from flickr for one call. The first one was
({stat:"fail", code:1, message:"Photo not found"})
The second one was the a full response from the server that also produced the TypeError mentioned above. However, the second response found the photo and gave me the sizes.

404 error with Ajax request

I need to grab some data from a JSP page that does a select on a database and then put inside a div. I need to do this with ajax.
Here is my code:
$(function() {
teste();
});
function teste() {
var v1 = document.getElementById("selCodigo").value;
alert(v1);
$.ajax({
type : "GET",
data : "turma="+v1,
url : "busca-notas.jsp",
success : function(resposta){
alert("DEU CERTO");
},
error : function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
document.getElementById("notas").innerHTML = "ERRO";
}
});
}
I tested the variable v1 and the value that it receives necessary, and in my JSP page, I do this:
String turmaSelecionada = request.getParameter("turma");
the problem is that the ajax content that does not feed into the div need, beyond what the xhr.status presents thrownError and a 404 error not found
Can anyone help me?
Either, busca-notas.jsp does not exist, or it is on a different server or path as the HTML calling the Ajax request.
Example: If your HTML and JavaScript is here:
http://www.example.com/somepath/page.html
and your PHP code is here:
http://www.example.com/otherpath/busca-notas.jsp
then you'll Need to use url: "../otherpath/busca-notas.jps". There is an easy way to check: Open your HTML in the browser, remove the last bit of the path, and replace it with "busca-notas.jpg", and see what you're getting.
A 404 also means, your JSP code never gets executed.
This is saying the resource you are trying to do a GET to is not there. The path you are doing a GET to is probably incorrect. Can you tell the structure of your files (javascript/service files etc...). I would suggest using the browser developer tools or fiddler to debug what is going on.
Use F12 (windows) with browsers to get to the developer tools. Also the fiddler tool is great! http://www.fiddler2.com/fiddler2/
On a side note if you use console.log for debugging you will never go back to alerts :)

Fire a .js file with jquery click event

I am attempting to load a .js file hosted online after a jquery click event. First, am I doing this right? Will all the javascript be applied only after a link is clicked?
$(document).ready(function() {
var clickHandler ="file.js";
$('a').click(function() {
$.getScript(clickHandler, function(data, textStatus, jqxhr) {
console.log(data);
console.log(textStatus);
console.log(jqxhr.status);
});
});
Edit: I just checked the console and it is loading the file but giving me a 403 Forbidden message. Why is this happening? Do I need to have some text in my header to refer to?
EDIT 1:
Misread the jQuery code -- this part of the answer doesn't apply:
There are ways to add Javascript file to an existing document, but it isn't as simple as you are trying to do.
This discussion can explain that: How to dynamically insert a <script> tag via jQuery after page load?
The other solution is to put the contents of the Javascript into its own function, include that on the page normally and then run that function in your click handler.
Edit: Expanded answer
Lets say that you have some fairly simple code in your file.js like this:
var el = document.getElementById("fooz");
if (el) {
el.className += " example";
}
This code will, since it is not wrapped up in a function, will run (or try to run) as soon as it is loaded. It will only run once every time it is loaded.
However, if you wrap it up in a function, like this:
function colorFooz() {
var el = document.getElementById("fooz");
if (el) {
el.className += " example";
}
}
Then the code will not run until the function is called. It will load and be ready to be called later.
Error 403
The first thing to do is figure out why are getting the error 403.
At this stage, that has nothing to do with Javascript, jQuery or AJAX. Simply the problem by trying to load that Javascript file directly in your browser, by typing something like this utnil your URL:
http://example.com/file.js
Changing the URL to your website and path of course. At this point, you should still be getting the 403 error, but you can now check your server logs to see what error is written there.
I found a page that gives a guide to tracking down 403 errors here: http://www.checkupdown.com/status/E403.html
((PS: If I had to randomly guess at the reason why you are getting the 403 error, I'd say that you don't have the path file file.js correct. Depending on your structure and various includes, it may be calculating the relative path incorrectly.))
The function you pass to click() is a callback and is only executed when the element is clicked. So yes, you've got that part right.

Categories

Resources