I am building a framework and I want to write some generic functions for buttons when they are clicked before and after an ajax call is made.
My problem is how do I reference to the actual element itself.
$(this) in this case references to the xhr I guess.
$.ajaxSetup({
beforeSend : function(){
$(this).css('cursor', 'wait');
$(this).text('wait...');
},
error : function(){
$(this).css('cursor', 'normal');
}
});
I found another question about this with an answer:
jquery ajax - global settings. Is it possible to know what event/element trigger the ajax call?
Moreover the jQuery docs says:
Note: Global callback functions should be set with their respective
global Ajax event handler methods—.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than
within the options object for $.ajaxSetup().
My old answer:
You sould bind an onclick listener on the buttons you want to take
ajax action on. In this case you can access the button with this:
$(this).addClass('a');
// ajax calls...
example: http://jsfiddle.net/ichr/s6EUg/2/
Related
This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 8 years ago.
I have Javascript code that is supposed to do stuff on a click, but it isn't doing anything. It's essentially a button on a pane that slides in. When I click the button, I expect something to happen. This button, though, is populated when an AJAX call completes because the AJAX call is fetching some HTML that contains the button.
Here's my code to set up the button:
$("#btn-delete-setup").on("click", function() {
console.log("clicked");
_deleteFunction();
//return false;
});
Because the Javascript is loaded before that pane and button are rendered from the AJAX call, does this mean the button will not respond to my .on("click") code? Is my button not responding because when Javascript loads, it hasn't found the button to bind to?
So, the answer of your question is : No, this code won't work if the element is appended after the script is loaded (e.g. on document ready).
But you can achieve this easily with jQuery :) :
$(document).on("click","#btn-delete-setup", function() {
console.log("clicked");
_deleteFunction();
//return false;
});
Full solutions offered to you on this post (duplicate): Using jQuery 'click' function that was loaded with Ajax content?
This button, though, is populated when an AJAX call completes
So this is the perfect case for event delegation, which means binding events on the element which was not available when page was loaded, so you need to delegate the event to the closest static parent:
$("closestStaticparent").on("click", "#btn-delete-setup" function(e){
console.log("clicked");
_deleteFunction();
//return false;
});
$("closestStaticparent") is the page element like any div container/wrapper or i would say the element which is in the dom before ajax call.
Although $('body'), $(document) or $(document.body) are always available for delegating the event.
If you're affraid about the possibility that your button is not ready try with:
$(document).ready(function(){
$("#btn-delete-setup").on("click", function() {
console.log("clicked");
_deleteFunction();
//return false;
});
});
Hope this helps,
So i have a page in my site that has a with class name 'mainContent' that automatically updates with new data every like 1 minute using AJAX .ajax(). Content in this requires some JavaScript for some functionalities. The problem now is that JavaScript does not work on the new data loaded into the DOM without whole page refresh. I have searched and found using .on() to bind the data to the DOM should work, like so:
$(document).on('click', '.mainContent',function(){
expand();
});
where expand is a JS function.
However, it only works fully on the new data but not on the data that had been added in the previous AJAX call...
You're almost there, it's just your logic. This is how this jQuery function works:
You set a container. This is the element that will hold the AJAX-crated items that you want to bind. The more specific, the better. Otherwise, you'll wire an event for your whole page, which is bad
The event. What are you listening to?
Who will fire the handler. A selector to form the phrase: when these guys inside this big guy fire this event, run this code.
Let's suppose that your mainContent gets filled with hyperlinks (I'm not sure because your question lacks on details):
$('.mainContent').on('click', 'a', function () {
//do your magic
//$(this) is the clicked link
});
This way, our phrase is: when links inside .mainContent are clicked, run this.
UPDATE
Based on the comments, I think that your problem may be on the expand function.
Let's give a try:
$('.mainContent').on('click', 'a', function () {
$(this).simpleexpand();
});
Have you try to apply your binding on the callback of the ajax function that load your new datas ?
Something like that :
$.ajax({
url: url...//Classic ajax call
}).done(function ( data ) {
//Apply your 'on' here
});
I have an html form that loads its contents through ajax and includes buttons that, when clicked, should execute a JavaScript function that is defined in the html page's script tag. SO: Button is loaded through ajax (works), but when button is clicked, it doesn't trigger the desired action and doesn't trigger a JavaScript error in Firebug. How does one get the onclick signal of a bunch of buttons loaded through ajax to bind to an already existing JavaScript function?
EDIT: I should have noted also that I am not using JQuery. I am willing to do so if it is the only way, but otherwise, I would prefer to use only native JavaScript.
EDIT2: My problem was a bit more involved, but as was stated in the chosen answer, you should be able to set the onclick event handler in the php script before sending the data through ajax. If you have a data-heavy response and want to reduce bandwidth, you might consider doing everything client-side, but I find it easier in most situations just to set the onclick attribute in the php script.
Your dynamically generated button could have an inline event bound to it. When generating the button, simply make sure it has an onclick="alreadyExistingFunc();" and the page will happily execute it.
Alternatively, when your AJAX data is finished writing itself into the document, find the new button(s) and bind the event to them:
function ajaxSuccess()
{
document.getElementById('newButtonIdHere').onClick = function() {
alreadyExistingFunc();
}
}
That should do the trick. Also note that if you ever "need" a small part of jQuery to do something (like selectors or event handling), you can almost always do it without loading the whole library.
Append/insert the HTML (retrieved AJAX response) to DOM and bind click event to it:
function alreadyExistingFunc() {
alert('button is clicked!');
}
var ajax_data ="<button id='my-button'>My Button</button>";
$('body').append(ajax_data).find('#my-button').on('click', function(e){
alreadyExistingFunc();
// some more code...
});
OR:
$('body').append(ajax_data).find('#my-button').on('click', alreadyExistingFunc);
You could also use a callback:
function getAjaxContent(callback) {
$.ajax({url: "url"}).done(function() {
callback(data);
});
}
getAjaxContent(function (data) {
//ajax content has been loaded, add the click event here
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use variable outside the success function from an ajax/jquery call
I have this code and i don't understand why the accessing of the html elements is only working inside the ajax success function. the form is pulled in from ajax either way but i can only access it when i put all the selects for elements of it inside the ajax function.
The console.log('submit clicked'); gets not triggered this way, but inside the "ajax success" it does, i thaught everything pulled in with ajax is part of the DOM?
jQuery(document).ready(function($) {
console.log('ready');
$.ajax({
type: 'GET',
url: 'admin-ajax.php',
data: { action: 'get_arve_form' },
success: function(response){
// var table = $(response).find('table');
$(response).appendTo('body').hide();
console.log('response');
[ if i move the code below this ajax function in here its workign fine why not outside of it?]
}
});
// handles the click event of the submit button
$('#mygallery-submit').click(function(){
console.log('submit clicked');
[...]
});
Ajax is asynchronous so your elements don't exist until the ajax call finishes.
That being said, there are two ways to fix it:
1) Move your code into the success handler
2) Use event delegation to bind your event handler to all current and future elements.
An example of #2:
$(document).on('click', '#mygallery-submit', function(){
console.log('submit clicked');
});
Check out jQFundamentals to learn more about event delegation.
That's how ajax works.
When the external page is loaded, you have it available only on the success handler.
If you want it to be available elsewhere, you have to save it somehow, like you are doing.
But, the .click function gets executed before the ajax call returns successful. When you select $('#mygallery-submit'), it most likely is empty (you probably load this via ajax). So what you have to do if you want to declare the click function on document ready, rather than when the ajax page gets loaded, is to use the .on function:
$('body').on('click', '#mygallery-submit', function() {
console.log('submit clicked');
});
Because .click() is not a delegated handler. If the element you're trying to bind the event to doesn't exist at the time of execution, the event won't get bound. Try .on() instead.
$('body').on('click', '#mygallery-submit', function() {
// etc.
});
I am using the jQuery $(document).ready() event on page. All is fine, except that
if I am loading data using Ajax calls, the $(document).ready() event does not fire. I guess that it behave in such way because the page was already loaded and I am just adding more data from the Ajax response to the DOM.
How can I refire the ready event?
If you need to execute some additionnal Javascript, you might use a function that you call upon Ajax callback onComplete event :
function initJS(){
//your code here
}
$.ajax({
url: 'ajax/test.html',
success: function(data){
},
complete: function(){
initJS();
}
});
.load(), .bind(), or .live() will be your friends here....
just break the logic that is in the "$(document).ready( function() {});" block out into a separate function. Then the page will call it once when it is "ready", and you can directly call that function when you want to do a refresh.
I think the person asking is because most developer doing jQuery plugins i.e wordpress plugins use the "ready" function.
Everyone here is saying go modify the plugins !
I'm facing the same problem as I'm developing AJAX template for wp and most plugins don't work !