Simple Ajax jQuery get method not completing - javascript

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.

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/

How to test JQuery fail callback?

This is jquery function:
$.get("/url", function(){
//success
}).fail(function(){
//fail <---- how to make code go in there.
});
Problem is how to let program goes into .fail block, I use .Net MVC, However, set break point in Controller doesn't trigger a timeout exception then leads to fail callback.
Don't know how people test this.
Should I start looking at some tools ?
Put this in your Controller method:
return new HttpStatusCodeResult(HttpStatusCode.NotFound);
Use an invalid endpoint URL. You should get 404 - not found http status code error.

Load content using AJAX on window.onload

I am trying load some JSON data from a PHP backend, parse them and populate a div based on the JSON data I receive. I want to do this as soon as the window has been done loading.
Right now I have it setup like this:
$(function(){
$.getJSON("todo_action.php?getall=true", function(data){
console.log(data);
});
});
However, this approach is not working. But after the window has been done loading and I go to Chrome's developer console and run the code above, it works. Correct me if I am wrong, but I think this is not working because by default all AJAX requests are asynchronous and it has to do with the asynchronous property of AJAX, right?
I tried other variants of jQuery's built in AJAX functions like get, load, ajax but no avail. I have also tried making the request synchronous using $.ajaxSetup({async: false}); and it still does not work.
Are you sure you're not just missing a closing );?
$(function(){
$.getJSON("todo_action.php?getall=true", function(data){
console.log(data);
});
}); // <- here
It should work fine, I have an example JsFiddle here.
Make sure the page is fully loaded.
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
$.getJSON("todo_action.php?getall=true", function(data){
console.log(data);
});
});

Jquery getJson page never finishes loading

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.

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