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;
});
})
Related
I'm not sure if this will actually be possible, since load() is an asynchronous method, but I need some way to basically Load several little bits of pages, one at a time, get some data included in them via JavaScript, and then send that over via Ajax so I can put it on a database I made.
Basically I get this from my page, where all the links I'll be having to iterate through are located:
var digiList = $('.2u');
var link;
for(var i=0;i<digiList.length;i++){
link = "http://www.digimon-heroes.com" + $(digiList).eq(i).find('map').children().attr('href');
So far so good.
Now, I'm going to have to load each link (only a specific div of the full page, not the whole thing) into a div I have somewhere around my page, so that I can get some data via JQuery:
var contentURI= link + ' div.row:nth-child(2)';
$('#single').load('grabber.php?url='+ contentURI,function(){
///////////// And I do a bunch of JQuery stuff here, and save stuff into an object
///////////// Aaaand then I call up an ajax request.
$.ajax({
url: 'insertDigi.php',
type: 'POST',
data: {digimon: JSON.stringify(digimon)},
dataType: 'json',
success: function(msg){
console.log(msg);
}
////////This calls up a script that handles everything and makes an insert into my database.
}); //END ajax
}); //END load callback Function
} //END 'for' Statement.
alert('Inserted!');
Naturally, as would be expected, the loading takes too long, and the rest of the for statement just keeps going through, not really caring about letting the load finish up it's business, since the load is asynchronous. The alert('Inserted!'); is called before I even get the chance to load the very first page. This, in turn, means that I only get to load the stuff into my div before I can even treat it's information and send it over to my script.
So my question is: Is there some creative way to do this in such a manner that I could iterate through multiple links, load them, do my business with them, and be done with it? And if not, is there a synchronous alternative to load, that could produce roughly the same effect? I know that it would probably block up my page completely, but I'd be fine with it, since the page does not require any input from me.
Hopefully I explained everything with the necessary detail, and hopefully you guys can help me out with this. Thanks!
You probably want a recursive function, that waits for one iteration, before going to the next iteration etc.
(function recursive(i) {
var digiList = $('.2u');
var link = digiList.eq(i).find('map').children().attr('href') + ' div.row:nth-child(2)';
$.ajax({
url: 'grabber.php',
data: {
url: link
}
}).done(function(data) {
// do stuff with "data"
$.ajax({
url: 'insertDigi.php',
type: 'POST',
data: {
digimon: digimon
},
dataType: 'json'
}).done(function(msg) {
console.log(msg);
if (i < digiList.length) {
recursive(++i); // do the next one ... when this is one is done
}
});
});
})(0);
Just in case you want them to run together you can use closure to preserve each number in the loop
for (var i = 0; i < digiList.length; i++) {
(function(num) { < // num here as the argument is actually i
var link = "http://www.digimon-heroes.com" + $(digiList).eq(num).find('map').children().attr('href');
var contentURI= link + ' div.row:nth-child(2)';
$('#single').load('grabber.php?url=' + contentURI, function() {
///////////// And I do a bunch of JQuery stuff here, and save stuff into an object
///////////// Aaaand then I call up an ajax request.
$.ajax({
url: 'insertDigi.php',
type: 'POST',
data: {
digimon: JSON.stringify(digimon)
},
dataType: 'json',
success: function(msg) {
console.log(msg);
}
////////This calls up a script that handles everything and makes an insert into my database.
}); //END ajax
}); //END load callback Function
})(i);// <-- pass in the number from the loop
}
You can always use synchronous ajax, but there's no good reason for it.
If you know the number of documents you need to download (you can count them or just hardcode if it's constant), you could run some callback function on success and if everything is done, then proceed with logic that need all documents.
To make it even better you could just trigger an event (on document or any other object) when everything is downloaded (e.x. "downloads_done") and listen on this even to make what you need to make.
But all above is for case you need to do something when all is done. However I'm not sure if I understood your question correctly (just read this again).
If you want to download something -> do something with data -> download another thing -> do something again...
Then you can also use javascript waterfall (library or build your own) to make it simple and easy to use. On waterfall you define what should happen when async function is done, one by one.
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.
Sorry if this is a silly question but I'm completely new to AJAX and I'm wondering why my code is not working like I want..
I have the following:
an Ajax Call looking like that:
$.ajax({
type: "POST",
url: "/newnote.php",
data: {
content: content
},
success: function() {
}
});
and on the beginning of the page newnote.php (which is exactly the one, where the ajax-call is on, I have the following PHP:
if(!empty($_POST)){
header("Location:index.php");
}
But the php on the beginning of the page is not executed, of course, because the site seems not to be reloaded, but, when looking in developer tools under "network", i see that there is a post request on newnote.php with the values I want. But the question is: How can I access them? So for example, if I post the following data: content: "test", that I can write in PHP sth. like <?=$_POST['content'];?>... So how can I access the $_POST-Data from AJAX? Do I need to refresh the page or how does this work?
Thanks for your help
after exchanging I now got the question:
to access to your code you must use the callback of your ajax call
success: function(result){
$("#div1").html(result); // here you put the content that echoes your php inside your div1 on the actual page without reload
}
On the php side where the content is posted you must echo something that will be caught by this ajax call
I am Opening dynamically a page using Ajax, to prevent browser refresh. It opens and it runs scripts on the destination page. but before executing the script, I want them to retrieve the parameters like request.querystring but in Javascript.
This is my code that opens the page.
function cargarPagina(para1) {
$.ajax({
url: "/tarea.aspx",
context: document.body,
data: { "p1": para1 },
type: 'POST',
success: function (responseText) {
$("#maincontent").html(responseText);
$("#maincontent").find("script").each(function (i) {
if ($(this).text() != "") {
$("#maincontent").find("#hola").val(para1);
//alert(para1); //eval($(this).text());
}
});
},
async: true
});
}
After that, the tarea.aspx opens and executes scripts blah blah.
But before executing scripts, I want to get the "para1" value that was sent within the ajax POST call.
Any help would be much appreciated.
You are doing a POST not to the page, but to a server. The server then looks at your POST and says "oh, it looks like this is the page that you are requesting", and serves up some html content. The javascript on that served up page does not have any knowledge of the original POST, or how it (the page) came to be created.
If you want to get the POST parameters into the destination page, you must handle the POST request on the server, and then write the parameters in to the output page, via ASP.net or PHP or whatever scripting language you are using.
Alternatively, you could use GET instead of POST, and then the parameters would be available in the URL
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