how to tell the program the value of an element is refreshed - javascript

How can refresh an html element when its value is changing. I mean assume that i have this tag:
<div id="response" style="display:none;"><div>
and i have this script:
<script type="text/javascript">
$('#delete_link').click(function(e) {
e.preventDefault();
$('#result').html('').load('{% url messages_delete message.id %})
alert($('#result').html());
$('#'+$('#result').html()+'_list').trigger('click');
});
</script>
when user clicks on delete_link, the server sends a value to response div, so response div which was empty before, now has a value, and i will use it's value to know which tab i should trigger. when i use alert, it understands that the value of this tag is changed, and the trigger works. but without alert, it seems it doesn't understand the value is changed and trigger doesn't work. Is there a way to tell the program that the value is changed? i don't want to use alert. thanks very much for your help

.Load() is asynchronous, you need to set your content html in the load callback function.
$('#delete_link').click(function(e) {
e.preventDefault();
$('#result').html('').load('{% url messages_delete message.id %}',function(){
$('#'+$('#result').html()+'_list').trigger('click');
});
});

AJAX is asynchronous, you can use the load callback function which is executed after request is complete.
$('#delete_link').click(function(e) {
e.preventDefault();
$('#result').load('url', function(){
$('#'+ $(this).html() +'_list').click()
})
});
Note that load before adding new markup, removes the current markup of the element, so using html('') is redundant.

Related

Callback function not executing click after .load()

I've come to a road block and I'm hoping someone can explain where my error is. I'll do my best to explain my script, sorry if I overly break it down.
I have a div on page1.html that is being replaced by a div on page2.html via jquery's .load(). My script which is found in the <head> is as following:
<script>
$(document).ready(function(){
$(".info").click(function(event){
var gallery = event.target.id;
$("#replace").load( "folio/" + gallery + ".html #grab", function () {
jQuery("#gallery").unitegallery({
theme_enable_preloader: true,
tiles_col_width: 250,
tiles_space_between_cols: 10,
tiles_min_columns: 1,
tile_enable_image_effect:true,
tile_image_effect_type: "blur",
tile_image_effect_reverse: true,
lightbox_show_numbers: false,
lightbox_top_panel_opacity: true,
lightbox_overlay_opacity:1
});
$("#return").on("click", function(){
$("replace").load(" Portfolio1.html #replace1") });
});
});
});
</script>
The script executes when a <a id="folio1" class="info"> is clicked. A variable gallery will store the id value of the <a id="folio1" class="info"> that was clicked. I then select the <div id="replace"> which will have its content updated via Jquery's .load(). Variable gallery that is storing the id will be used inside the .load to determine the appropriate page url the new content will be loaded from. So far this works perfectly.
On success of .load() I create a call back function which executes .unitegallery(). Unitegallery() successfully executes and beautifully creates the image gallery. After unitegallery() I have another function which is waiting using .on("click" for a click event on <a id="return">. This function will perform another .load that will return <div id="replace"> back to its previous state. This is when things stop working.
Note:The selector used for the function <a id="return">, was inserted into the webpage via the first .load().
Issue: This .on("click" is not executing.
Ideas on why that portion of the script is not executing? Is the <a id="return"> loaded into the document by the first .load() not able to be selected?
Ask me questions for clarification! :)
please see my comment below if it works.
$("#return").on("click", function(){
$("replace").load(" Portfolio1.html #replace1") // you need the # because i think the event registration will not recognize 'replace'
//enter code here`
});
Also if this does not work, can you please paste your html so we can see the structure of your document.
I also just want to point out, there is nothing wrong when the event registration will be moved outside of the load scope.

Using jQuery Load Function before DOM Ready

I have a page that renders HTML blocks from another page on the same domain using IDs. My current code:
<div id=”testdiv”></div>
<script>
jQuery(document).ready(function(){
jQuery('#testdiv').load('/references/embed1.html #testdiv2');
});
</script>
While this loads the content correctly, there is a visible lag between the page loading and the jQuery content loading; depending on the DIV contents it sometimes a full second to display then it just pops into place. This is obviously due to the page not attempting to retrieve the HTML content until DOM Ready so I removed the ready function but the Load function doesn’t run. If I use an iFrame instead it appears to load as the browser executes the code but I lose the ability to only include specific DIV IDs and it’s difficult to make it responsive. Looked at $.ajax but apparently Load uses .ajax so it doesn’t look like there will be a difference.
Simply put – how do I load specific DIV ids from another page without waiting for DOM Ready whether jQuery, JavaScript, iFrames or other method? Second question
Thanks
document readywill be triggered until the whole page were loaded, just remove it and .load() will be invoked after #testdiv had finish render on DOM.
here's the example
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<div id="testdiv"></div>
<div id="error"></div>
<script>
$( "#testdiv" ).load( "/references/embed1.html #testdiv2", function( response, status, xhr ) {
alert("Triggered");
if ( status == "error" ) {
var msg = "Err trying to load ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>
https://jsfiddle.net/Angel_xMu/rer3yuny/1/
Ajax is not instant, and nothing you do will change that. Therefore, there will always be some form of delay. You can reduce the delay by removing the need for $(document).ready(), however I suspect it still won't be enough to have it do what you were hoping for.
$.get('page.html', function (result) {
// note, you may need to use `.filter` rather than `.find` depending on the structure of `result`
$('#target').html($($.parseHTML(result)).find('#target2'));
});
or leave your code as is minus $(document).ready and move it to after the target div just like in your example.
The only way to completely remove the delay would be to remove the need for using $.ajax by inserting the html directly into the page server-side.

Load Html Content if not exist JQuery AJAX

I have a page with 3 buttons. >Logos >Banners >Footer
When any of these 3 buttons clicked it does jquery post to a page which returns HTML content in response and I set innerhtml of a div from that returned content . I want to do this so that If I clicked Logo and than went to Banner and come back on Logo it should not request for content again as its already loaded when clicked 1st time.
Thanks .
Sounds like to be the perfect candidate for .one()
$(".someItem").one("click", function(){
//do your post and load the html
});
Using one will allow for the event handler to trigger once per element.
In the logic of the click handler, look for the content having been loaded. One way would be to see if you can find a particular element that comes in with the content.
Another would be to set a data- attribute on the elements with the click handler and look for the value of that attribute.
For example:
$(".myElements").click(function() {
if ($(this).attr("data-loaded") == false {
// TODO: Do ajax load
// Flag the elements so we don't load again
$(".myElements").attr("data-loaded", true);
}
});
The benefit of storing the state in the data- attribute is that you don't have to use global variables and the data is stored within the DOM, rather than only in javascript. You can also use this to control script behavior with the HTML output by the server if you have a dynamic page.
try this:
HTML:
logos<br />
banner<br />
footer<br />
<div id="container"></div>
JS:
$(".menu").bind("click", function(event) {
event.stopPropagation();
var
data = $(this).attr("data");
type = $(this).attr("type");
if ($("#container").find(".logos").length > 0 && data == "logos") {
$("#container").find(".logos").show();
return false;
}
var htmlappend = $("<div></div>")
.addClass(type)
.addClass(data);
$("#container").find(".remover-class").remove();
$("#container").find(".hidde-class").hide();
$("#container").append(htmlappend);
$("#container").find("." + data).load("file_" + data + "_.html");
return false;
});
I would unbind the click event when clicked to prevent further load requests
$('#button').click(function(e) {
e.preventDefault();
$('#button').unbind('click');
$('#result').load('ajax/test.html ' + 'someid', function() {
//load callback
});
});
or use one.click which is a better answer than this :)
You could dump the returned html into a variable and then check if the variable is null before doing another ajax call
var logos = null;
var banners = null;
var footer = null;
$(".logos").click(function(){
if (logos == null) // do ajax and save to logos variable
else $("div").html(logos)
});
Mark nailed it .one() will save extra line of codes and many checks hassle. I used it in a similar case. An optimized way to call that if they are wrapped in a parent container which I highly suggest will be:
$('#id_of_parent_container').find('button').one("click", function () {
//get the id of the button that was clicked and do the ajax load accordingly
});

Same JQuery click function for numerous links

I have a page that has multiple links with various attributes (these attributes will be pulled in from a database):
index.php
<html>
<head>
<script type='text/javascript' src='header.js'></script>
</head>
<body>
My_Link_1
My_Link_2
<div id='my_container'> </div>
</body>
</html>
My header.js file has:
$(document).ready(function(){
$('.link_click').click(function(){
$("#my_container").load("classes/class.project.php", {proj: $(this).attr('id')} );
return false;
});
});
class.project.php is pretty simple:
<?php
echo "<div id='project_container'>project = ".$_POST['proj']." : end project</div>";
?>
This loads and passes the ID variable (which actually comes from a database) to class.project.php. It works fine for the first link click (either link will work). Once one link is clicked no other links with this div class will work. It feels like javascript loads the class.porject.php and it will not refresh it into that #my_container div.
I tried running this as suggested by peterpeiguo on the JQuery Fourm, with the alert box for testing wrapped inside .each:
Copy code
$(document).ready(function() {
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
});
});
This seems to work fine for the alert box. But when applying it to .load() it does not reload the page with the new passed variable. As a matter of fact, it doesn't even reload the current page. The link performs no function at that point.
The example site can be viewed here: http://nobletech.net/gl/
I looked at the link you posted, and the problem is that when you're doing load you're replacing the elements on the page with new ones, thus the event handlers don't work anymore.
What you really want to do is target the load. Something like:
$("#project_container").load("classes/class.project.php #project_container", {proj: $(this).attr('projid')} );
This only loads stuff into the proper container, leaving the links and other stuff intact.
Ideally, the php script should only return the stuff you need, not the whole page's markup.
BTW- Caching shouldn't be an issue in this case, since .load uses POST if parameters are passed. You only have to worry about ajax caching with GETs
Sounds like the request is getting cached to me.
Try this:
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
Sorry but this might be completely wrong but after examining your XHR response I saw that you are sending back html that replaces your existing elements.
So a quick fix would be to also send the following in your XHR response (your php script should output this also):
<script>
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
</script>

Calling Javascript in a page after it's been loaded by jQuery GET

Imagine a normal page calling javscript in head. The trouble is some of the content isnt loaded untill i click on a link. Subsequently when this link loads the content it wont work. This is because i guess the javascript has already been run and therefor doesnt attach itself to those elements called later on. There is only standard html being called.
So for example this is the code which calls my external html.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).slideDown('slow');
});
});
If the html i was calling for example and H1 tag was already in the page the cufon would work. However because i am loading the content via the above method H1 tags will not be changed with my chosen font.This is only an example. The same will apply for any javascript.
I was wonering whether there is a way around this without calling the the javascript as well the html when its received from the above function
If you want to attach events to elements on the page that are dynamically created take a look at the "live" keyword.
$('H1').live("click", function() { alert('it works!'); });
Hope this is what you were looking for.
Does Cufon.refresh() do what you want?
As you said Cufon was just an example, I'd also suggest a more general:
$.get(url, options, function(html, status) {
var dom = $(html);
// call your function to manipulate the new elements and attach
// event handlers etc:
enhance(dom);
// insert DOM into page and animate:
dom.hide();
$target_element.append(dom); // <-- append/prepend/replace whatever.
dom.show(); // <-- replace with custom animation
});
You can attach event handlers to the data that you get via the get() inside of the callback function. For example
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).find('a').click(function(e) {
// specify an event handler for <a> elements in returned data
}).end().slideDown('slow');
});
});
live() may also be an option for you, depending on what events you want to bind to (since live() uses event delegation, not all events are supported).
Andy try this. It will call the Cufon code after each AJAX request is complete and before the html is actually added to the page.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data);
Cufon.replace('h1');
$(this).slideDown('slow');
});
});
JavaScript is not executed because of a security reason OR beccause jQuery is just setting this element's innerHTML to some text (which is not interpreted as a JavScript) if it's contained. So the security is the beside effect.
How to solve it?
try to find all SCRIPT tags in Your response and execute them as fallows:
var scripts = myelement.getElementsByTagName("SCRIPT");
var i = 0;
for (i = 0; i < scripts.length; i++)
eval(scripts[i].innerHTML);

Categories

Resources