jquery ajax load content from a button that is inside the container - javascript

I'm using jQuery and ajax to load pages without reloading the entire website and I ran into a problem.
This is the jquery script:
$(function(){
$("a[rel='tab']").click(function(e){
e.preventDefault();
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
if(pageurl!=window.location){
$.ajax({url:pageurl+'?rel=tab',success: function(data){
$('#main-wrap').html(data);
}});
}
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({url:location.pathname+'?rel=tab',success: function(data){
$('#main-wrap').html(data);
}});
});
and the html code is something like this:
<div class="nav">Page 1</div>
<div class="ajax-content">
<div class="title">Title</div>
</div>
Now if I click "Page 1" that is outside the div where the ajax content is loaded it's working but if I click "Title" that is inside the div, the whole page is reloaded(ajax not working).
It's possible to make that "Title" link(which is inside the div where the ajax content is loaded) to work?

The actual problem is that you are adding the event handler to all a[rel='tab'] on document ready, but you are loading the target <a> after the fact. That means that they will not have the event handler bound to their click. You should use something like live or more importantly on. The importance is event delegation, where you would use something like:
$("#container").on("click", "a[rel='tab']", function () {
// Your code
});
This way, any a[rel='tab'] that is removed or added inside of the #container element has this event handler attached to it.

Set your href attribute to # and add a return false;
Try this:
<div class="title">Title</div>

I would just ditch the inner link if you're already scripting it, and instead put the url in a data-url attribute. Then you don't have to worry about covering your tracks with any default behavior. Your div would look like this:
<div class="title" id='link_btn' data-url="title_page.html">Title</div>
Then rework your code like this:
("#link_btn").click(function(){
//get the link location that was clicked
pageurl = $(this).attr('data-url');
Data attributes are a great way to pass data between elements and your script. You just have to be careful when you create them as special characters and quotes can mess them up and make them unreadable.

Related

Ajax loaded part of a page - how do I make links in the loaded content work?

I load a part of my basketpage inside an accordion div in my header. This works great and shows my basket in a nice dropdown.
The last problem I need to solve with this is to get the buttons in the loaded content to work. Is it possible to write an callback that make these works? Im not sure even what to google for this one..
This is how the buttons is setup in the loaded content:
checkout
Script Im using to load the content:
$('.dcjqg-accordion ul.sub-menu').load('/m4n?seid=etailer-basket div#centerbox.itembox.centerbox');
use the callback function of .load().
$('.dcjqg-accordion ul.sub-menu').load('/m4n?seid=etailer-basket div#centerbox.itembox.centerbox', function() {
$("#_ec_oie2").on("click", function() {
if (UI.pb_boolean(this, 'click')) { }
return false;
});
});
checkout
You need to use a child selector for the event. You can attach an event to the .sub-menu element that will fire on the content loaded in through the ajax. Something like the following could work:
$(".dcjqg-accordion ul.sub-menu").on("click", ".action.actionbasket.checkout", function() {
if( UI.pb_boolean(this, 'click') ) {}
return false;
});
Notice the second parameter to the on method. It is a selector that will be used to look at the target of the click event. I used .action.actionbasket.checkout since that is what is on your a tag.
This code may not work exactly, but this should help get you in the right direction.
Here is the link to the jQuery documentation for the on method: https://api.jquery.com/on/

Using jQuery to append a div to a dynamically created div after AJAX success

I am using the WP-Polls plugin for WordPress which is an AJAX polling system and I'm trying to append an initially hidden div (.comment-block) to a new div (.voted) which will be dynamically inserted into the DOM by the WP-Polls plugin upon AJAX success. Once the user has voted and clicked on the vote button (.Buttons), the DOM updates to reflect the addition of the new (empty) div with a class of .voted. I put up a similar question earlier but thought I'd open a new more relevant thread.
Note: The .voted div was created through the templates that WP-Polls
offers in the dashboard. The plugin offers templates for "before
the user has voted" and "after the user has voted" and what I did was
insert a div into the latter like this: <div class="voted"></div>. The reason why I can't just add content inside that div directly is because the content in the div to be appended (.comment-block) is a contact form created by the plugin Contact Form 7 and it requires a PHP statement. Only HTML is allowed in the templates.
Among other various failed attempts, I have tried to use .on so that clicking on .Buttons would activate the function. However, nothing was changed in the DOM.
$(document).on('click', '.Buttons', function() {
$('.comment-block').appendTo('.voted');
});
Below is the HTML. This is before the user has voted:
<div id="poll">
(poll here) + .Buttons vote button <-- in here----------|
</div> |
<div class="comment-block" style="display:none"> <-- I want this div |
<?php echo do_shortcode('[contact-form-7]'); ?>
</div>
And this is how I want it to look after the user has voted:
<div id="poll">
<div class="voted"> <-- dynamically created div
<div class="comment-block" style="display:block">
<?php echo do_shortcode('[contact-form-7]'); ?>
</div>
</div>
</div>
If anyone can show me the way, I'd appreciate it. I've been racking my brain with this one for hours.
Edit: I am not up to speed with AJAX so I'm unable to provide exactly the code that is needed, but here is a list of the files for the plugin: https://github.com/lesterchan/wp-polls
$('button.Buttons').click(function ()
{
$('#poll').empty().append('<div class="voted"></div>');
$('.comment-block').show().appendTo('.voted');
$(this).unbind('click');
});
You can also change the '.show()' to actually set the style specifically to display:block if you need to.
If I understand your question correctly, this should work:
$('.Buttons').on('click', function () {
setTimeout(function () {
var commentBlock = $('.comment-block'),
cloneComment = commentBlock.clone();
commentBlock.remove();
$('#poll').append(cloneComment);
cloneComment.wrap('<div class="voted">').show();
}, 1000);
});
First, bind the 'click' to the '.Buttons' element. Then, create a clone of the '.comment-block' element so you can .remove() the original '.comment-block' and .append() or .prepend() the cloned element to the '#poll' element. Lastly, .wrap() the clone with a <div class="voted"> and call .show() to display the clone.
You need to trigger an event from the ajax call:
The button onclick function fires the ajax call.
The ajax success fires event(s) on the targeted elements to be changed and passes it's response as a parameter.
example:
html
<div id="foo">bar</div>
<button onclick="ajaxCall();" />
javascript
var ajaxCall = function() {
$.ajax({
success: function(response) {
$("#foo").trigger("ajsuccess", response);
}
});
};
$("#foo").on({
"ajsuccess" : function(e, response) {
$(this).append(response);
}
});

Make jquery ignore href

I am trying to append data into a div tag using jquery when there is a click event on a html tag,html and javascript code is below and live example for same is at JSFiddle
HTML
<a class="datafile" href="#">abc</a>
<div id="result2">
</div>
Javascript
$(".datafile").click(function() {
$('#result2').append('Clicked!');
}
When a user clicks on abc I dont want the browser to go to link in href rather it should insert Clicked! in div tag.
What I am doing wrong ? Please help.
Something like this:
$(".datafile").click(function(e) {
$('#result2').append('Loading Log File ...');
// For all modern browsers, prevent default behavior of the click
e.preventDefault();
// Just to be sure, older IE's needs this
return false;
});
You have to prevent the default action of the hyperlink.
$('.datafile').click(function(e) {
e.preventDefault();
//Your code
});
Change the href value from '#' to 'javascript:void(0);'?

Page finish loading, load in jQuery content via Jquery .load, execute jQuery elements

If I want to be able to load in content (containing elements depending on jQuery) after main page has finish loading, the content will be retrived from another page on my site (div). How do I then get those element depending on jQuery to execute (work)?
How do I make these different jQuery elements to work with some easy method after they being loaded into the main page? I dont know much about jQuery, it would be great if I could just ad/edit a function on the scripts to make them work after inload, but ofcurse its propably more difficult than that. In the passed days I have tried initialize the different object that loads in but notice that it was quite difficult with complicated scripts.
The page load in new content like this (selectbox):
<select id="selectbox">
<option>1</option>
</select>
jQuery code to the selectbox:
$(document).ready(function(){
$("#selectbox").change(function(){
var selectedOption = $('#selectbox :selected').val();
$containerDiv = $('#div_that_will_get_content');
$containerDiv.html("");
switch (selectedOption)
{
case "1":$containerDiv.load( "Page.html #div1 );break;
}
return true;
});
});
Selected option in selectbox (1) collects data from Page.html #div1, then send the data to div "#div_that_will_get_content". So the div get loaded in after the main page have finish loading.
Now if I want to put a jQuery element in this div and then load that div into the main page via the selectbox and to "#div_that_will_get_content", those elements dont work. Can anybody show a easy jQuery example with a smal explanation how the script was written from the begining and what you changed to make it work after it was loaded in?
Thanks.
Not entirely sure what you are needing but part of the answer lies in using the success callback of load()
/* define this cached elemn outside change handler so don't have to search DOM each time*/
$containerDiv = $('#div_that_will_get_content');
$("#selectbox").change(function() {
/* val() of select is same as searching for selected option val() but less code*/
var url = 'Page.html #div' + $(this).val();
$containerDiv.load(url, function() {
/* new ajax loaded html exists you can run code here*/
$containerDiv.find('#someOtherDiv').doSomething()
})
});
API Reference: http://api.jquery.com/load/
If your problem relates to binding events to elements that will be loaded any time in the future such as click handlers, you can delegate these in your page load script using on()
$(document).on('click', '.className', function(){
doSomething();
})

How to load two div from two different div (from html) by clicking the same link

I want to click on a#lanostracasa to take two different divs from an external .html and load it in another two div (the #fotoCasa from the external file havePicture)( http://frostcode.altervista.org and http://frostcode.altervista.org/db.html for the external HTML.)
I'm going crazy because I see the text in the container while I see it loading, and all the text disappears and no content was loaded.
<div id="contAll">
<div id="fotoCasaHtml"></div>
<div id="container">
<p>
<div id="imgHome"><img class="img"src="images/noimg.png"></div>
blablablablablablabla
</p>
</div>
</div>
The link I want to to click:
<div id="cssmenu">
<li><a id="lanostracasa"href='#'><span>La Nostra Casa</span></a>
</div>
and the JavaScript that doesn't work:
<script type="text/javascript" language="javascript">
$( function() {
$( 'a#lanostracasa' ).click(function() {
var postData = ''; // you can send any data to ajax file.
$('#container , #fotoCasaHtml').html('<p>loading</p>');
$.ajax( {
url : 'db.html',
type : 'post',
data : postData,
success : function( resp ) {
$('#container').html($('#lanostracasa-ita' , resp).html());
$('#fotoCasaHtml').html($('#fotoCasa' , resp).html());
}
});
return false;
});
});
</script>
I also use this call in jQuery for the same link but I don't think it affect the JavaScript:
$("#cssmenu a#lanostracasa").click(function(){
$('#container').load('db.html #lanostracasa-ita')
});
So you have two events bound to the same element that are, by themselves, contradictory. You cannot bind the same event (click) twice to the same element. In this case you have a precedence problem that needs to be addressed. One function is being fired and one is not, choose which one to use. Furthermore, if you think of this from a logical perspective...what's the point of binding the same event twice? If ONCLICK you want two things to happen, just put them both in one function.
Also, you must remember that when binding events to elements, the elements themselves must EXIST prior to binding. I can't see your HTML to verify that your second .click() event is wrapped in a function closure or $(document).ready() but that may also be a source of confusion.

Categories