I'm hoping someone here can help me. I don't use JQuery or javascript very much--I'm more of a php guy. I've got some code that seems to work except for actually appending the content to the UL with JQuery. If I watch the log in firebug, I see it bringing back the correct data, but the data is never actually put into the page. I have tried .html, .load, and .append with no luck. It will always load the initial HTML from the php script in the .load, but it's hit or miss as to whether the .append or .html works even though the data is always the same. Here's what I've got:
$(document).ready(function(){
var page = 1;
$('#favoritesul').load("/custom/getfavorites.php"); //initial load
//load more on click
$('#favoritesul').on( "click", "a.paginated", function (e) {
e.preventDefault();
++page; //increment page counter
//temporarily hide the load icon
$('#favoritesul > a.paginated').remove();
//send AJAX
$.ajax({
type: 'POST',
dataType: 'html',
url: '/custom/getfavorites.php',
data: { page: page}
})
.done(function(data) {
$('#favoritesul').append(data);
$('#favoritesul').append('<i class="icon-undo"></i>LOAD MORE</ul>');
})
.fail(function(){
alert('post failed');
});
});
});
As I said, if I console.log and look at the AJAX response, I'm seeing the HTML I expect, it just will not append, or even replace, the contents of the HTML. For clarity, the contents of the HTML I'm trying to append look like this:
<li class='data-item'><div class='test'><div class='padding'><div class='image-container'><a href='pagelink.php'><img class='image' src='imagesource.jpg' /></a></div><div class='header'><h2 class='heading'><a href='pagelink.php'>Video</a></h2></div></div></div></li>
And the pertinent part of the existing page looks like this prior to the first .load event:
<div class='clear'></div><ul id='favoritesul' class='someclasses'></ul>
Thanks for all of the help in advance!
You do have invalid HTML in your done() handler. Firstly #favoritesul is an UL, you can't append an anchor to it, only a LI, and secondly, you can't append partial elements, like you're trying to do by including just the closing </ul> tag.
Try appending valid HTML
.done(function(data) {
var li = $('<li />');
li.append(data);
li.append('<i class="icon-undo"></i>LOAD MORE');
$('#favoritesul').append(li);
})
Related
I am making a GET ajax call and it is returning html as data.
I only want to return what is within div#product-detail-response and replace that html with what is within the div.product-detail-info.
That works just fine, but when I am logged into the CMS as an admin, it spits out debugging code at the end of every page. I know I could disable that feature, but I'd like to keep it on and just remove the debugging div from the response.
*the div#debugging-info exists within div#product-detail-response
// this displays the html correctly, but it includes the debugging-info that I want removed
var $response=$(data);
$(".product-detail-info").html($response.filter('#product-detail-response').html());
// I tried adding a remove in different spots of this line without success
$(".product-detail-info").html($response.filter('#product-detail-response').html()).remove("#debugging-info");
*I also put a display: none; for .product-detail-info #debugging-info {} and this:
$("#debugging-info").hide();
after the above code.
Response:
<div class="product-detail-info">
html and all the stuff I want to show up
<div id="debugging-info">
this shows debugging info, and I want to remove this div completely
</div>
</div>
My desired response:
<div class="product-detail-info">
html and all the stuff I want to show up
</div>
AJAX call
$.ajax({
url: '/product_detail_ajax/'+entry_id,
type: 'GET',
data : {},
dataType: 'html',
context: this,
success: function (data) {
var $response=$(data);
$(".product-detail-info").html($response.filter('#product-detail-response').html());
$(".breadcrumb-product-title").text($response.filter('#breadcrumb-product-title').text());
},
error: function (data) {
// console.log('error');
}
});
you actually ve something like this:
the data returned from your call
var data = "<div class='product-detail-info'>html and all the stuff I want to show up<div id='debugging-info'>this shows debugging info, and I want to remove this div completely</div></div>";
and now create a dom obj to manipulate your data
var parsed = $('<div/>').html(data);
parsed.find("#debugging-info").remove();
$("#result").append(parsed.html());
FIDDLE
After you have injected the response htmlin the dom, you could hide the debugging info element, as follows:
$response = $( data );
$( ".product-detail-info" ).html( $response.html() ).find( "#debugging-info" ).hide();
Here is a JS Fiddle
i am working on a single page application using jQuery. whole html pages are sent as response to browser as ajax response.
$.post(url, function (data) {
$("#resp").html(data);
$("#resp").find("script").each(function (i) {
//alert($(this).text());
eval($(this).text());
});
});
how to remove script tags from data and than assign html to the div ?
the issue i am facing is the scripts that are written in the response page. they were not getting added to the DOM at first, so i used eval(), now the scripts are getting added twice in some situations.
The easiest way would be to use the .load() function with a fragment selector, since that will strip out <script> tags prior to updating content and result in them not being executed. If you're working with entire HTML pages though there may not be a suitable selector for you to use. However, I'd suggest trying this first:
$('#resp').load(url + ' body');
That would give you just the content between the <body> and </body> tags in the HTML page requested via AJAX.
If that doesn't work, I guess you could try manually stripping out <script> tags from the response prior to adding to the DOM:
$.post(url, function(data) {
var tempDiv = $('<div>').html(data).find('script').remove();
$('#resp').html(tempDiv.html());
});
That creates a new <div> element that isn't part of the document, sets its HTML to the returned HTML from the AJAX request, searches for <script> elements inside that, and then removes them. However, even though the element isn't part of the current document yet, the scripts may still end up being executed (I've never had a reason to do this so I haven't tested it).
with the help of Anthony's answer this is what i did to get it working :
$.post(url, function (data) {
var tempDiv = $('<div>').html(data);
var raw = $('<div>').html(data);
$(tempDiv).find("script").remove();
$("#resp").html(tempDiv.html());
$(scripts).find("script").each(function (i) {
//alert($(this).text());
eval($(this).text());
});
});
i could not understand why
var tempDiv = $('<div>').html(data).find('script').remove();
did'nt work though.
I have some code that calls in a new html file, to be added into a div. I'm wondering why the content in the div is replaced rather than just added in. Once I understand the "why" Id like to know how I would add in external markup into a div while preserving what was already in that div to begin with.
$.ajax({
url: 't3.html',
success: function(data) {
$('.ajax').html(data);
}
});
Instead of:
$('.ajax').html(data);
use:
$('.ajax').append(data);
try .append
$.ajax({
url: 't3.html',
success: function(data) {
$('.ajax').append(data);
}
});
Because you are replacing the whole HTML of .ajax div with data. If you want to preserve the existing HTML of that control use the following
$('.ajax').html($('.ajax').html() + data);d
I load content of a page by jQuery AJAX as
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php?start="+$('#lastid').text(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
In the current document, I have <div id="lastid"></div> and in the external php file <div id="start"></div>
The value for id="start" is updated from database, and it will be transferred to id="lastid". However, this code only works for FIRST click. For default <div id="lastid">1</div>, when clicking the button (id="more") it will read load.php?start=1 and updates the current document to <div id="lastid">11</div> (it's visible). But the second click will not load load.php?start=11
It seems that $('lastid') well reads the default value of <div id="lastid"></div>, but NOT when it has been updated by $("#lastid").empty().load('html #start')
How can I modify this code to work for subsequent clicks?
Wow, what a mess! Let's clean up a bit :)
You need to get rid of the id, as an id has to be unique and if you load another div with id lastId into your site, jQuery will not know which id to get. If you have many divs, each containing the id, you can just read the last id by using ('div:last').text();
So your ajax would look like this:
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php",
data: "start="+$('div:last').text()
success: function(html){
$("#results").append(html);
}
});
});
});
I also don't know what you do with the last line in the success, as load should be used to load data from the server with ajax, what is what you do by using $.ajax(). Also load() takes at least an url as parameter, see here.
try .live() function instead of .click()
Mate,
What I see from you code is that you are attaching an event once the page is loaded. And this creates a static call with static values that don't get updated as you continue.
My suggestions is to use a function that will feed an Id dynamically to your ajax call as follows:
$(document).ready(function(){
$(document).on("click", '#next', function(event){
$.ajax({
url: buildurl(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
function buildurl()
{
return "load.php?start="+ $('#lastid').text();
}
This will force your event to always call this function and the function to get a fresh value from lastid.
Regards
you have to change your success function because you have multiple #lastid when clicking twice.
try something like:
success: function(html){
$("#lastid").removeAttr("id"); // remove's the id from #lastid
$("#results").append(html); // appends the new one
$("#lastid").empty().load('html #start');
}
I am trying to call some script in a newly ajax loaded tab but it looks like the script blocks inside the tab are not being processed at all so when I go to call a function in the tab the function cannot be found. Is there a way to properly load the tab content such that the scripts are interpreted?
I have tried playing with the ajax options but that doesn't seem to help.
$("#tabs").tabs({
ajaxOptions: {
error: function (xhr, status, index, anchor) {
$(anchor.hash).html("This tab not yet built, sorry bub.");
},
dataType: 'html'
},
spinner: 'Loading tabs...',
});
In the tabs I have something like
<script type="text/javascript">
function SetupTab(){
alert('loaded');
}
</script>
but
$("#tabs").bind("tabsshow", function(event, ui){ SetupTab();});
cannot find SetupTab. Even if I allow the tab to load and then attempt to call SetupTab from firebug it can't be found.
if you try and bind any events/actions to a html element that does not exist yet i.e.
$(document).ready(function(){
//apply elemnt bindings here
});
when you do load the elements using ajax the elements will not take on the bindings you supplied on document ready because they did not exist at that point.
Add a call back to your ajax call to then bind any events/functions to ur new html elements, then this should work.
I think thats what you was reffering to.
EDIT: try this.
$("#tabs").bind("tabsshow", function(event, ui){ alert('loaded');});
EDIT AGAIN: you could try this.
make sure the page you are loading just contains the script itself and not the script tags and then use:
//lets say the data returned from your ajax call:
data = function SetupTab(){alert('loaded');}
eval(data);
then you could call that function no problem.
EDIT 3RD TIME: if you cant remove the script tags from the page your load you could regex the html. with this pattern.
pattern = /<script\b[^>]*>(.*?)</script>/i
urscript = data.match(pattern);
eval(urscript[1]);
this should work.
What you can do is also to detach your ajax call from the element (do just $.getScript for example).
Your loading tabs function should do something like this:
<div class="tabs" onclick="$.getScript('myScript.php?index='+$(this).index(#tabs"))">...
Then the server-side script should return something like this:
echo '
$("#tabs").eq('.$_GET['index'].')html("'.$myHTML.'");
/* Then the rest of your JS script (what you had in your HTML output) */
';