How to call a jquery method from PHP page loaded through ajax - javascript

I have a page where I am loading a series of buttons into a div using jquery/ajax. This is a script for loading every time the user user scrolls the page. Each of the buttons are clickable and run a jquery function after being clicked. The problem is when I switched to loading the buttons from a different page the now don't call any method. If I switch the buttons to calling a pure javascript function it works just fine but I need the button to call a jquery function as the rest of the script, which is quite long, has been done in jquery.
Here is what I am talking about:
Page A:
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = '<?php echo $total_groups; ?>';
$('#results').load("testshareload.php", {'group_no':track_load}, function(result) {
track_load++;
}); //load first group
$(window).scroll(function() { //detect page scroll
});
$('#testerino').on('click', function () {
console.log("CALLED");
});
PAGE B: (testshareload.php)
<?php
echo "<input type='button' value='Button' id='testerino'>";
?>
It also will not work for me to do this due to the existing code:
function testerino() {
$(document).ready(function() {
});
}
What else can I do to solve this problem?

You're creating a click handler for an element that doesn't exist, and this will fail in jQuery. What you need to do is create a DELEGATED handler for the item:
$(document).on('click','#testerino', function () {
console.log("CALLED");
});
The document accepts the handler being registered, and later when it gets a click event from an element matching the selector #testerino it will fire off the handler.

Your problem is that you're binding an event to an element that doesn't exist yet.
As per the docs:
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
You have two options:
Create the bind in your .load function instead.
Or as per the docs again:
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers.
Use $(document).on('click', '#testerino', function() { ...

Related

js stop click function subsequent execution after call back in ajax of itself

On the first click myClick() has been called again in itself of myLoad() then at the second click, this myClick() will execute two times
=> The following causes two subsequent execution of
click event of #myBtn by one click
How to avoid or stop this? Please anybody suggest me new logical method or which way to stop this.
$(function() {
myLoad()
})
function myClick() {
$("#myBtn").click(function() {
myLoad(); //load new every click
});
}
function myLoad() {
$("#myCnt").load('ajax.php', {
"data": "some"
}, function() {
myClick() //to live the click event works after ajax load
})
}
Problem with your implementation is that in each call to myClick() an new event handler is attached to button.
You can use .off() to remove existing event handler attached using .on().
function myClick(){
$("#myBtn").off('click').on('click', function(){
myLoad();//load new every click
});
}
A better approach would be to use .on() method with Event Delegation approach, when generating elements dynamically.
General Syntax
$(document).on('event','selector',callback_function)
In place of document you should use closest static container.
The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
A good read Direct and delegated events
Modify you code as
$(function() {
myLoad();
$(document).on("click", "#myBtn", function() {
myLoad(); //load new every click
});
})
function myLoad() {
$("#myCnt").load('ajax.php', { "data": "some"}, function() {
//No need to call my click
})
}
Issues is in the flow of your code
First time when you call myClick() it binds the click event with #myBtn,
On second time it binds that event again , so it will be called twice , remove that event binding from there,
Or else $("#myBtn").click will be bind each time you call the myClick function.
As solution please try this code :
$(function(){
myLoad()
})
$("body").on( "click" , "#myBtn" , function(){
myLoad();//load new every click
});
function myLoad(){
$("#myCnt").load('ajax.php', {"data":"some"}, function(){
$("#myBtn").trigger("click");
})
}

$( document ).ready() in partial view only runs first time it is added to the DOM via AJAX

After using AJAX to load a partial view in to a dialog on the page, this code, located in the partial itself NOT in the main page, runs and I get tabs as expected:
// Run this on page load
$(function () {
debugger;
$("#ProjectTabset").tabs();
});
This being the case, if the div containing the partial was removed from the DOM (using jQuery remove) then added again and the partial loaded in to it once more, it should run again, but it doesn't.
Why would it run the first time, but not any subsequent time? Could the problem be that the div in to which the partial is being inserted is not really removed somehow? (Though I am testing it is not present before creating, and it seems it is no longer part of the DOM.)
Please let me know if I can be more clear or provide any more detail :)
Since you have removed the element from DOM and added back dynamically you may need to use the delegated events via on() if you want events to be handled on dynamically added elements. Try the below and see if it helps.
$( document ).on( 'ready', function (e) {
$("#ProjectTabset").tabs();
})
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on(). To ensure the elements are present and can be selected, perform
event binding inside a document ready handler for elements that are in
the HTML markup on the page. If new HTML is being injected into the
page, select the elements and attach event handlers after the new HTML
is placed into the page. Or, use delegated events to attach an event
handler, as described next.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers.
May be the links here will help you resolve the problem.
You should use .delegate():
// Run this on page load or ajax load complete
$('body').delegate('#ProjectTabset', 'ready', function() {
$("#ProjectTabset").tabs();
});
UPDATE:
$(document).delegate('#ProjectTabset', 'click', function() {
$('#ProjectTabset').tabs();
}
$.ajax(function(){
...
success: function(){
$('#ProjectTabset').click();
}
})

Why does jQuery alls Alert() more times?

I currently have a quite big issue here, which I've been trying to figure out since yesterday, but I really don't know what could be the problem here.
So I basically made a jQuery Ajax call in my code, something like this:
var ajaxCall = function(id, token)
{
var datap = { "id": id, "token": token };
$.ajax({
type: "POST",
url: "ajax.php",
data: datap,
dataType: "json",
beforeSend:function()
{
// loading image
},
success: function(data)
{
setting(data);
},
error: function()
{
alert('error');
}
});
As for the success function you can see the setting function, which looks like this:
var setting = function(data)
{
$('#testDiv').html(data.country);
}
Basically, this ajax call is made, once someone clicks on an item like:
$('#popup').on("click", function(){
ajaxCall();
});
So when someone clicks in the popup button, they will have a popup window open with the loaded Ajax content.
This is actually working flawlessly. My only problem happens, if I want to make another event within the Popup window (like: on click).
var load = function()
{
$('#testDiv #button').on("click", function(){
alert(1);
}
}
So if I place it in the above Ajax call function, it looks like the following:
$('#popup').on("click", function(){
ajaxCall();
load();
});
Problem:
When I click on the opoup button, to load the popup window, it loads the Ajax content. When I try to click on #button within the popup window at the first time, after loading the page, it gives me the alert box with 1.
However! If I just close the opoup window and click on it again, to load the popup, than click on the #button again, now I got the alert(1) 2 times! If I do the above again, I got it 3 times, 4 times, and so on.
So basically I've found out, that if I use the on Click function (within the popup window, after ajax has loaded), the contents within the on Click function got called more times, if I load the popup window more times (without refreshing the page - after refresh, everything strats from the beginning).
So the first popup load and click is normal, but the others seems to get called more times. I have also checked that the Ajax call is called multiple times, but it's NOT. I have placed an increment number inside each part of the code and I only got it incremented multiple times when the #button was clicked.
I know that this is quite hard to understand, but I would really need someone's help here, as I'm completely lost. Any solutions would be really appreciated.
I suggest you to do this:
Bind your click event outside of that function and put it in doc ready:
$('#testDiv #button').on("click", function(){
alert(1);
});
and do this in the #popup click event:
$('#popup').on("click", function(){
ajaxCall();
$('#testDiv #button').trigger('click');
});
You are binding the click event whenever load is called, to fire it once, you should bind it once. Either unbind it every time you call load before binding it or use on for event delegation. If you have to bind event with ids then you should directly bind as id are supposed to be using do not use descendant selector.
var load = function()
{
$('#testDiv #button').off("click");
$('#testDiv #button').on("click", function(){
alert(1);
}
}
I would recommend you to use event delegation for dynamically added elements
$(document).on("click", '#testDiv #button',function(){
alert(1);
});
Delegated events
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers, jQuery docs.
Edit based on comments
As both elements are present in dom and not loaded dynamically you simply need click event. As ids are supposed to be unique do not use parent child selector
$('#testDiv').on("click", function(){
alert(1);
});

Javascript not working in jQuery UI tabs that are loaded with Ajax

Javascript seems to be disabled in all jQuery UI tabs that are loaded through ajax. I am testing this with jQuery tooltips and .click() alerts. Javascript works fine in tabs that aren't loaded through ajax (IDs present on the page).
Here is how I am calling the tabs:
$(function() {
$('#foo-tabs').tabs(
{
heightStyle: 'content',
// Callback run when selecting a tab
beforeLoad: function(event, ui) {
// If the panel is already populated do nothing
if (ui.panel.children().size() > 0)
return false;
//load specific ID within target page
ui.panel.load($('a', ui.tab).attr('href') + $('a', ui.tab).attr('data-target'));
// stop the default process (default ajax call should not be launched)
return false;
}
}
);
});
Here's the javascript I'm trying to activate:
$(function() {
$( '.activate-tooltip' ).tooltip();
});
And a test:
$(function() {
$("h1").click(function() {
alert("zomg javascript works!");
});
});
Any ideas on how to get javascript working in all ajax loaded tabs? Thank you for taking the time to go through this!
The problem is that at the time when your binding your events those elements are not present in the DOM. The way to deal with this is by delegating the events to a higher level DOM element (up to the Document if necessary) that does exist in the DOM.
For example to delegate using .on
$(document).on('click', 'h1', function() {
alert("zomg javascript works!");
});
For the tooltip plug in you can do something like the following
$(function() {
//initialize tooltip plugin
//dvCont is just an existing element in the DOM, you can use #foo-tabs
$('#dvCont').tooltip({
items: '.activate-tooltip',
content: function(){
var element = $( this );
if ( element.is( ".activate-tooltip" ) ) {
return 'Some text';
}
if ( element.is( "[title]" ) ) {
return element.attr( "title" );
}
}
});
$('#dvCont').append($('<div class="activate-tooltip" >Test</div>')); //dynamic content
});
Here's a link to a jsBin
You can see a more complete example on the Demo page for the plugin.
Edit:
In response to why you should use event delegation if you can just initialize the plugin right after you add it to the DOM, I think its worth pointing out that besides for handling dynamic content another reason to use event delegation is due to performance. That is with event delegation you are able to attach fewer event handlers which in turn means less memory used.
To illustrate here's a link to a jsPerf that compares using event delegation vs binding directly.
When you call a method such as .click(), it adds the event handler directly to all of the elements in the jQuery object (i.e. those that matched the selector at the time it was run). When you add new elements to the page they don't have the associated event handlers, because they didn't exist when that code was executed.
The solution is event delegation; the general principle is that you set the event handler on an element higher up the DOM tree - one that contains all of the elements you wish to match. Then, when an event of that type is triggered on an element inside it and bubbles up to the element with the handler, it checks to see if the triggering element meets the conditions; if it does, it executes the callback function.
However, this only works for event handlers, it won't work for plugins. I don't know of a way to delegate plugin initialisation, so you'll likely just have to execute the code again. Thankfully the .load() function takes a callback function which will run when the new tabs content has finished being loaded via AJAX.
ui.panel.load($('a', ui.tab).attr('href') + $('a', ui.tab).attr('data-target'), function() {
$('.activate-tooltip', ui.panel).tooltip();
});
You could use on function of jquery to trigger click event for dynamically created html(in your case its the ajax function which creates dynamic html(tabs)). `
$("h1").on("click", function(){ alert("zomg javascript works!"); });
`

jQuery load() dynamic content with clicks get fired as many times as loaded

I load content via jQuery load() but for each time I load a given page, the clicks on the pages gets fired multiple times. Why??
Se the fiddle here:
http://jsfiddle.net/ZUZ3L/ph3tH/2/
Simply put your click hander outsie of load:
$(document).ready(function() {
function loadContent() {
$(".ajaxContainer").load("http://fiddle.jshell.net/ #actions", function() {
alert("Done");
});
}
$(".load").click(loadContent);
loadContent();
});​
Updated Fiddle
Each time you load content, you execute this line:
$(".load").click(loadContent);
which adds a new event handler to the list of event handlers to execute whenever .load is clicked. You execute your function three times, now you have three identical handlers all triggering for each click.
It's because you're adding the click event multiple times.
Every time your code runs, the click function is re-defined. When a click is redefined it won't replace the previous one, but instead will be added to the stack to be executed each time the "click" event occurs. This is applied to all events in jQuery.
As you are loading via AJAX the vars and events in the document are still persisted. Meaning that you are just adding layer on top of layer of function calls to be executed each time you run your ajax call
because you are calling the function 2 times, try this:
$(document).ready(function() {
function loadContent() {
$(".ajaxContainer").load("http://fiddle.jshell.net/ #actions", function() {
alert("Done");
});
}
loadContent();
$(".load").click(loadContent);
});
http://jsfiddle.net/ph3tH/4/

Categories

Resources