Web page becomes unresponsive after ajax call - javascript

I have a webpage in which I am getting some data from the server.I have used servlet to get the data from server.I need to fetch the data in every 5 seconds time inerval.I have used ajax call in my script, but after several calls the webpage becomes unresponsive.I have found one thing that here I have replaced the entire html page again , how can I seperate a particular div from the output html content (here page_html). I want to replace the div only
setInterval("update_content();", 5000);
function update_content(){
$.ajax({
url: "url", // post it back to itself - use relative path or consistent www. or non-www. to avoid cross domain security issues
type: "POST",
async: true,
cache: false, // be sure not to cache results
})
.done(function( page_html ) {
var newDoc = document.open("text/html", "replace");
newDoc.write(page_html);
newDoc.close();
});
}

how can I seperate a particular div from the output html content (here page_html). I want to replace the div only
You can simply change the contents of a div using jQuery html() method.
<div id="yourDivId">
</div>
JS:
function update_content(){
$.ajax({
url: "url", // post it back to itself - use relative path or consistent www. or non-www. to avoid cross domain security issues
type: "POST",
async: true,
cache: false, // be sure not to cache results
})
.done(function(page_html) {
$("#yourDivId").html(page_html);
});
}
This method will load the HTML using AJAX, and then replace HTML contents of #yourDivId with loaded data. This is what AJAX usually used for.

Related

Why does browser network show all javascript reloaded after jQuery .ajax call

I am using jQuery (v1.11.3) on my site and have noticed that after I use $.ajax to load part of content into the page, both Chrome and Firefox list a whole host of javascripts / css files which it seems to reload into the page
My call is cut down as:
ajaxUrl = '/sample/ajaxSavedItems';
xhr = $.ajax({
url: ajaxUrl,
data: jsonObj,
type: 'post',
cache: false,
dataType: "html",
success: function(data){
$('#loadMore').remove();
$('#loadMore-section').replaceWith(data);
}
})
The routine works and the html returned is just the extract from the backend code with no header - just the bare html required to be inserted.
So the question is, why does the network seem to show that all of the existing javascript and css files (around 42 files in total all included in the main page header) are reloaded by the browser (as this obviously slows down the delay of the inserted section).

JSON call giving value that is not actually in the .json file

I am a little new when it comes to JSON and Javascript , so please excuse me if if this is a stupid question, but I have run into a problem that is starting to drive me insane.
On a webpage I am including two scripts; jQuery and a file called "scripts2.js". In the same directory as scripts2.js, I have a JSON file; "settings.json". From within my "scripts2.js" file I am running he following code inside of a function.
var settingsPath = settings.json;
jQuery.getJSON(settingsPath, function (data){
jQuery.each(data, function(index){
console.log("!"+data[index].name);
/*unrelated other stuff */
});
});
Previously the settings.json file looked like this
[
{"name":"Standard Black"},
{"name":"Gold"},
{"name":"Silver"}
]
So naturally when I looked in the Chrome Dev Console the log would print out
!Standard Black
!Gold
!Silver
However, when testing what would happen upon editing my settings.json file I changed "name":"Gold" to "name":"Test".
[
{"name":"Standard Black"},
{"name":"Test"},
{"name":"Silver"}
]
After the json updates I tried refreshing the page but my console log is still printing out
!Standard Black
!Gold
!Silver
...
I am at a loss. I have no idea why the data being retrieved with jQuery.getJSON() is sending the data of my old settings.json even after the changes has been saved. I have perused my .php file (which is generating the HTML) , as well as my included javascript and there is no other mention of another json file or any sort of clone of my json file in any related directory.
I really have no idea what is going on and I am starting to go insane. Does anyone have an idea of what the issue might be?
I dont know if it matters but I am running a XAMPP stack on my localhost. All files (index.php, scripts2.js, and settings.json) are in a directory located inside XAMPP's htdocs folder.
EDIT: Thank you all for the speedy and thorough answers, many of you answered the question I was a bout to ask next. I really appreciate it!
This is because the browser is caching the file from your first request. Simply clear the cache and run it again and the new data will be retrieved.
UPDATE:
To prevent the browser from caching this file, change your AJAX settings like so:
jQuery.ajaxSetup({ cache: false });
Before you make the getJSON call
Try clearing web cache and restart local servers if you have not already
When using jQuery.ajax() instead of the shorthand method, you can disable caching like this:
jQuery.ajax(settingsPath, {cache: false})
jQuery will append a timestamp parameter to your request URL which changes with every request and therefore keeps the browser from caching the response.
To force the browser to get a new version each time you can use cache: false in jQuery.ajax()
$.ajax({
dataType: "json",
url: settingsPath,
cache: false,
success: function (data){
$.each(data, function(index){
console.log("!"+data[index].name);
});
}
});
Pass additional parameter to your requested url which value will change with every request.So,your browser will consider it as new request every time and will not cache the data.
var random = Math.round(new Date().getTime())
var settingsPath = 'settings.json&time=' + random;
jQuery.getJSON(settingsPath, function(data) {
});
});
You can use any algoritham that generate random new value everytime for random for every request.
OR
you can have same things with jQuery#Ajax method
jQuery.getJSON is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So, set the optional parameter cache to false (this value by default is always true):
$.ajax({
dataType: "json",
url: url,
data: data,
cache: false, // If set to false, it will force requested pages not to be cached by the browser
success: success
});
Therefore, your getJson becomes:
var settingsPath = settings.json;
jQuery.ajax({
dataType: "json",
url: settingsPath,
data: data,
cache: false,
success: function(data) {
jQuery.each(data, function (index) {
console.log("!" + data[index].name);
/*unrelated other stuff */
});
}
});

Cross Domain AJAX request return HTML (not jsonp)

I'm using this plugin: https://github.com/padolsey/jquery.fn/tree/master/cross-domain-ajax/
And this is my code:
$.ajax({
dataType: 'html',
type: 'GET',
url: 'http://www.google.com',
crossDomain: true
}).done(function(data) {
$("#box").html('').append(data);
});
From my understanding, even though I have dataType: 'html' I'm fairly sure this is still getting me a response in JSONP.
I want to be able to grab the entire html of the page, everything I need to display the page in full. Comparable to an iframe. The reason I need to do this through ajax is because eventually I am going to need to pass parameters to the URL I am using. What is the best way to return a page's content in full HTML, so that I may display the page? Do I need to do anything to return the pages scripts/stylesheets as well?
Basically, the URL that I am calling needs to be returned so that I can append the return to a div id, and that div id should then look exactly like the page I was calling, as if I were to load that page independently in a browser window.
Thanks!
You can try Ajax-cross-origin a jQuery plugin.
http://www.ajax-cross-origin.com/
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});
Plugin referenced uses Yahoo YQL service as a proxy to get remote page. YQL will return json and you should be able to access your data in data.responseText. This is per limted docs for plugin
To be sure you can log the data to console and see it's structure.
Could do same thing without plugin by using YQL console to create URL needed to meet your scraping needs using their XPATH syntax

Jquery ajax function returns wrong page, though the url in a browser window shows correct page

I'm building a chrome extension in javascript.
I'm trying to get the page contents from an Outlook mailserver through an ajax request, but I have trouble getting the correct page returned.
I suspect it is the danish letter æ, that creates the problem, but don't know how to resolve it.
$.ajax({
url: baseURL + 'Indbakke/',
data: "Cmd=contents&View=Ulæste%20meddelelser", //Avoid encodeURI
dataType: 'html',
processData: false, //Avoid encodeURI
cache: false,
success: function(data) {
fetchedInbox = $.parseHTML(data);
//If there are changes to the inbox, refresh the inbox page
if(findString(fetchedInbox, 'ingen emner'))
{
window.parent.frames[1].location = baseURL + 'Indbakke/?Cmd=contents';
}
},
complete : function(){
console.log("URL" + this.url)
}
});
The data variable of the succes function contains the wrong page, but if I copy 'this.url' from the complete function into a browser, it displays the right page. I have tried using default ajax settings and encodeURI on the full link (without using the 'data' option), but then neither 'data' or 'this.url' will work (i.e. I change the second parameter to 'View=Ul%C6ste%20meddelelser').
I do not have access to the (probably) asp page that the server sends, just javascript, so I can't do anything serverside.
Note: When chromes console show this.url, it breaks the link before æ, so I have to manually copy the url
It's probably the æ that creates this error. Replace æ by %C3%A6 and the headers will be send to the correct location.
data: "Cmd=contents&View=Ul%C3%A6ste%20meddelelser"
To find the encoded character, I used this converter: http://meyerweb.com/eric/tools/dencoder/

How to load new content to DIV without refreshing [duplicate]

This question already has answers here:
how to reload DIV content without refreshing whole page
(8 answers)
Closed 9 years ago.
I want to load new content from the server to the DIV without refreshing the whole page.
I tried the following
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData +"&relationship="+ forData +"#",
success: function (response) {
$("#testDIV").html(response);
}
});
But the problem is the whole page is loading in <DIV id="testDIV">. I want to replace the old DIV with New DIV content returned from the server not with the whole page.
You can keep your same process sense you are interested in using AJAX directly and want to manage your done function (instead of success because .done() will replace it). Here is how...
.done(function(data) {
...
}
Inside of that done function, you can filter the page content to what you want. Simply request what you want to filter with jquery like this...
var $response = $(data);
var response_title = $response.filter(".title").html(); //I'm assuming you are trying to pull just the title (perhaps an < h1 > tag, in this little example, from the entire external page!
THEN!...
$("#testDIV").html(response_title);
With the done function, based on jQuery's API, you can use this format...
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
So your final code may look something like this...
$.ajax({
type: "GET",
url: "ht.tp://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+ occasionData +"&relationship="+ forData +"#"})
.done(function(response) {
var $response = $(response);
var response_title = $response.filter(".title").html();
$("#testDIV").html(response_title);
});
I like the answer by blackhawk. It uses the existing code with slight modification.
I would just condense it to a one line change like this:
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData+"&relationship="+ forData +"#",
success: function (response) {
$("testDIV").html($(data).filter(".title").html());
}
});
The code you are displaying is actually correct.
The problem comes from what your server is providing.
What you are doing here is GETing a whole page via an AJAX call, and replacing the content of One div with that whole page.
Your server should not render the whole page for that call, but only the content of the div you wish to replace. If you are using framework like rails or symfony, they often provide an easy way to detect if the query is a normal GET request, or an AJAX call.
Basically you have 4 strategies at your disposal :
Make the requests to a specific endpoint that is used only for the ajax call and that returns the content of the div you wish to replace. And not the whole page.
Make the request to the same page, and detect if the request is a normal HTTP request or an AJAX call. Based on that, return the whole page or just the content of the div. You'll probably have to look for the helpers in your framework / toolbox documentation.
Make the AJAX request but ask for a JSON object. Transform your JSON in HTML on the client side to replace the content of the div. This is the "my app is just an API" approach. This is my personal favorite as this JSON endpoint can be used for other purposes (eg: a mobile app) since it carries only content, and not presentation. This also tends to be the fastest way in terms of performance since a significant part of the computation is done on the client side. On the con side, this requires you to write more JS.
Always render the whole page, and filter only what you need on the client side. This is balchawk approach. Benefit is that you don't have to modify your server, but you will waste processing time and bandwidth by returning a whole page, when only a subset is necessary.
$(function(){
$('.classloader.').on('click', function(e){
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData +"&relationship="+ forData +"#",
beforeSend: function() {
$("#testDIV").hide();
$('div#loading').show();
},
success: function(html){
$("#testDIV").html($(html).filter("#mainContent").html()).show();
$('div#loading').hide();
}
});
return false;
});
})

Categories

Resources