jQuery GET Function Returns Previous Result - javascript

I'm running into a strange problem on my webpage using the jQuery $.get function. The code below is executed on page load:
$.get(urls.validateSession, function(data){
console.log(data);
});
I would expect this to make a GET request to urls.validateSession each time the page is loaded, then log the response data to the console.
It does this on the initial page load with no problems. But on subsequent page loads, jQuery does not make a new request to urls.validateSession. It instead just prints the exact same response data from the previous request (identical response timestamp and everything!)
Interestingly, when reloading the page with Shift + F5, jQuery does make a new request to urls.validateSession and I can see a new response timestamp.
Can anyone explain this behavior?

I think this previous question might help get you the desired result.
The JQuery get() method's cache is, by default set to true.
cache (default: true, false for dataType 'script' and 'jsonp')
And it sounds like your results are getting cached, that's why it doesn't bother to run the function each page load.
You can check out more ajaxSettings here
The snippet from #KevinB in the linked question:
$.get({
url: url,
cache: false
}).then(function(rdata){
console.log(rdata);
});

If you do not want caching on any of your AJAX requests, you could also set this field in your initial AJAX setup before running any AJAX functions.
$.ajaxSetup({
cache: false
});

Related

Success function in ajax when using setInterval doesn't work

Well I would like to check answer from server every 5 seconds. But my success function inside $.ajax just does not work. Although ajax sends requests and gets response. Time limit is not exceeded since function is run every 5 seconds and response is received within 1 second.
If i put something inside checkMyCreatedGame function after $.ajax it does work but success function does not.
var checkMyGame;
checkMyGame =setInterval(checkMyCreatedGame,5000);
var checkMyCreatedGame = function(){
$.ajax({
url :'../cgi-bin/lobby.py',
type :"GET",
cache :false,
data {
"checkMyGameId":createdGameId,
"player":playerName
},
dataType:"json",
success:function(jsonData){
console.log(jsonData)
}
});
};
Here is my firebug console logs when I run this code (do not pay attention to what is above those gets):
Here is same screenshot but not resized by stackoverflow: https://i.stack.imgur.com/e9HBa.png
As you can see console.log inside success function is not executed.
In your AJAX call, you tell jQuery to expect JSON data:
dataType:"json",
Then your server returns non-JSON data:
waiting
jQuery then tries to parse it as JSON, and unsurprisingly, fails. If you tell jQuery to expect text instead, it will work fine:
dataType:"text",
The message of this is: if you are finding that an AJAX call is failing silently, put an error handler in. If you had, you would have received a message telling you that you had a parsererror.

Run (JS) function if server responded something specific

On one of my pages I have "tracking.php" that makes a request to another server, and if tracking is sucessful in Firebug Net panel I see the response trackingFinished();
Is there an easy way (built-in function) to accomplish something like this:
If ("tracking.php" responded "trackingFinished();") { *redirect*... }
Javascript? PHP? Anything?
The thing is, this "tracking.php" also creates browser and flash cookies (and then responds with trackingfinished(); when they're created). I had a JS that did something like this:
If ("MyCookie" is created) { *redirect*... }
It worked, but if you had MyCookie in your browser from before, it just redirected before "track.php" had the time to create new cookies, so old cookies didn't get overwritten (which I'm trying to accomplish) before the redirection...
The solution I have in mind is to redirect after trackingFinished(); was responded...
I think the better form in javascript to make request from one page to another, without leaving the first is with the ajax method, and this one jQuery make it so easy, you only have to use the ajax function, and pass a little parameters:
$.post(url, {parameter1: parameter1value, param2: param2value})
And you can concatenate some actions:
$.post().done(function(){}).fail(function(){})
And isntead of the ajax, you can use the $.post that is more easy, and use the done and fail method to evaluate the succes of the information recived
As mentioned above, AJAX is the best way to communicate between pages like this. Here's an example of an AJAX request to your track.php page. It uses the success function to see if track.php returned 'trackingFinished();'. If it did then it redirects the page 'redirect.php':
$.ajax({
url: "track.php",
dataType: "text",
success: function(data){
if(data === 'trackingFinished();'){
document.location = 'redirect.php';
}
}
});
The example uses JQuery.

jquery ajax async false is not working

I have a python script that's doing around 8 or 9 specific steps. These steps are being logged in a file. For web GUI to display status change, or error messages, I am using the script belowjquery PeriodicalUpdater plugin.
I need the program to run simultaneously so that as the value in the file changes,it gets polled and displayed.
Please find my jquery code below.
Note the url "/primary_call/" takes around 2 and half minutes to execute. Problem is async :false is not working. The browser waits for 2.5 minutes, and then gets into the next level.
I tried in Firefox and Chrome and it gives the same result.
When I call the URL of another browser tab, it works perfectly, but I am unable to run both script components simultaneously, when I try calling from the same page.
What should I do so that the browser initiates "/primary_call/", which runs a Python script in the background, at the same time moving ahead to the portion called PeriodicUpdate.
$(document).ready(function()
$.ajax({
type: 'GET', // Or any other HTTP Verb (Method)
url: '/primary_call/',
async: false,
success: function(r){
return false;
},
error: function(e){
}
});
$.PeriodicalUpdater({
url : '/static/12.txt',
method: 'post',
maxTimeout: 6000,
},
function(data){
var myHtml = data + ' <br />';
$('#results').append(myHtml);
});
})
Setting async:false means you are making the process synchronous, so the browser will hang on it until it is finished -- it can't move on to your other method. Removing that option will make the call asynchronous (which it is by default, as it should be) at which point the browser will initialize each ajax call in a separate thread.
In short, remove async:false.

Any function with mixed functionality of .ajax() and .load()?

.ajax() can send a post request and get data in return where as .load() can get any element in the rendered page. How to create a form when submitted(asynchromously) instead of getting back some data should get the page element of the rendered page that would be generated had there been normal submission instead of ajax submission?
I dont want to write views(Django) for xhr, normal requests separately. So, When I submit a form by ajax I dont want to hijack default action but only want to get some element of the rendered post submission page instead of actually being redirected to that post submission page which would have happened hadn't it been an xhr request.
Update:
load will do a POST rather than a GET if you supply the data to send as an object rather than a string. From the docs:
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
So:
$("#target").load("/path/to/resource selector_for_relevant_elements", {});
..should convert the load from GET to POST. Of course, you'd replace {} with the arguments you want to send.
Original answer:
You can do the POST directly with ajax and then process the returned HTML yourself. For instance, to turn this load:
$("#target").load("/path/to/resource selector_for_relevant_elements");
..into a POST:
$.ajax({
url: "/path/to/resource",
method: "POST",
dataType: "html",
success: function(html) {
// Build the elemnts of the result in a disconnected document
var page = $("<div>").append(html); // See note below
// Find the relevant elements and put them in target
$("#target").html(page.find("selector_for_relevant_elements"));
}
});
I've done the wrapper div because that's what jQuery's load function does. You may want to look at the source for load (that line number will rot, of course, but the filename is unlikely to change) to see if there are other tricks you need to replicate.

Adding a random number after the URL

I've got a site which uses jQuery and Ajax to change the site content without reloading the page. The site contains content which I often change. But somehow the page gets saved in the cache so it doesnt show the changes.
I tried several things to make the browser not to save the site into the cache like METAs and PHP. But it doesnt work.
I think it has to do with the fact, that the page always has the same URL so I thought about adding a random number to it like:
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
(It's not my code, found it with some googlin) But this only adds the link ID I clicked on to the URL. I don't know where to put "Math.random()" to add a random number.
Hope you can help!
Just use cache : false. jQuery will automatically add a timestamp to the end of the URL for you, making sure that ajax requests are never cached.
Quoting the the API reference for .ajax()
cache
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.
Examples
Globally disable caching for all future ajax requests. See .ajaxSetup()
$.ajaxSetup({
cache: false
});
Disable caching per request. See .ajax()
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
If you are using jQuery's AJAX functions, try setting $.ajaxSetup( { cache: false } ) at the top of your page, and let jQuery take care of it for you.
Like most mentionned, you should use the jQuery cache parameter, but for your information, it is often done not using Math.random but with new Date().valueOf(), which is a time value pretty much guaranteed to be unique.
window.location.hash = $(this).attr('href')
.substr(0,$(this).attr('href').length-5)
+ Math.random();
Best option is to use timestamp with the request:
window.location.hash = $(this).attr('href')
.substr(0,$(this).attr('href').length-5)
+ timestamp;

Categories

Resources