Alert doesn't execute after anchor click in AJAX response - javascript

I have the next code:
$('.ver').click(function(e) {
e.preventDefault();
var id = $(this).next().val();
$.post('cotizar_detalles.php', {'id': id})
.done(function(response) {
$('#detalles').dialog('open').dialog('option', 'title', 'Detalles')
.html(response, function() {
$('.corregir').click(function(e) {
e.preventDefault();
alert('aqui toy');
});
});
});
});
Where ".ver" and ".corregir" are both class inside an anchor tag.
'.corregir' exists on the html after the ajax.response.
The problem is the last alert, inside the '.corregir' click event doesn't execute, and I need it to execute another action.
What's the problem?
And thanks for the answers.

$.click() is a direct binding in jQuery which only works on elements in the DOM on page load. Try using a delegated binding instead, such as $.on():
$(body).on('click', '.corregir', function(e) {
e.preventDefault();
alert('aqui toy');
});
Check out the .on() jQuery Documentation.

Related

Change behavior of button using AJAX

I'm trying to figure out how to change behaviour of a button using AJAX.
When the button is clicked, it means that user confirmed order recently created. AJAX calls /confirm-order/<id> and if the order has been confirmed, I want to change the button to redirect to /my-orders/ after next click on it. The problem is that it calls again the same JQuery function. I've tried already to remove class="confirm-button" attribute to avoid JQuery again but it does not work. What should I do?
It would be enough, if the button has been removed and replaced by text "Confirmed", but this.html() changes only inner html which is a text of the button.
$(document).ready(function () {
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
var id = this.value;
var url = '/confirm-order/'+id;
$.ajax({
type: 'get',
url: url,
success: function (data) {
$this.empty();
$this.attr('href','/my-orders/');
$this.parent().attr("action", "/my-orders/");
$this.html('Confirmed');
}
})
});
});
The event handler will be still attached to the button, so this will run again:
b.preventDefault();
which will prevent the default, which is opening the href. You need to remove the event handler on success. You use the jQuery #off() method:
$(".confirm-button").off('click');
or more shortly:
$this.off('click');
You can add to your success function something like: $this.data('isConfirmed', true);
And then in your click handler start by checking for it. If it's true, redirect the user to the next page.
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
if ($this.data('isConfirmed')) {
... redirect code ...
}
else {
... your regular code ...
}
}
You need to use .on() rather than .click() to catch events after the document is ready, because the "new" button appears later.
See http://api.jquery.com/on/
$(document).ready(function() {
$('.js-confirm').click(function(){
alert('Confirmed!');
$(this).off('click').removeClass('js-confirm').addClass('js-redirect').html('Redirect');
});
$(document).on('click', '.js-redirect', function(){
alert('Redirecting');
});
});
<button class="js-confirm">Confirm</button>

Trigger AJAX inside an AJAX loaded page [duplicate]

I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click event is bound on DOM elements that are not loaded with my AJAX function.
What do I have to change, such that the event will be bound?
My HTML:
<a class="LoadFromAjax" href="someurl">Load Ajax</a>
<div class="appendedContainer"></div>
My JavaScript:
$(".LoadFromAjax").on("click", function(event) {
event.preventDefault();
var url = $(this).attr("href"),
appendedContainer = $(".appendedContainer");
$.ajax({
url: url,
type : 'get',
complete : function( qXHR, textStatus ) {
if (textStatus === 'success') {
var data = qXHR.responseText
appendedContainer.hide();
appendedContainer.append(data);
appendedContainer.fadeIn();
}
}
});
});
$(".mylink").on("click", function(event) { alert("new link clicked!");});
The content to be loaded:
<div>some content</div>
<a class="mylink" href="otherurl">Link</a>
Use event delegation for dynamically created elements:
$(document).on("click", '.mylink', function(event) {
alert("new link clicked!");
});
This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/
If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!
Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:
$('.parent-element').on('click', '.mylink', function(){
alert ("new link clicked!");
})
Some more reading on the subject:
https://learn.jquery.com/events/event-delegation/
http://jqfundamentals.com/chapter/events
if your question is "how to bind events on ajax loaded content" you can do like this :
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});
so you don't need to place your configuration to every you ajax code
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
Example -
$( document ).on( events, selector, data, handler );
For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready"
For e.g :
$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'post',
url: url,
data: $(this).serialize(),
success: function (data) {
// DO WHAT YOU WANT WITH THE RESPONSE
}
});
});
});
If your ajax response are containing html form inputs for instance, than this would be great:
$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) {
if (this.value == 'Yes') {
// do something here
} else if (this.value == 'No') {
// do something else here.
} else {
console.log('The new input field from an ajax response has this value: '+ this.value);
}
});
use jQuery.live() instead . Documentation here
e.g
$("mylink").live("click", function(event) { alert("new link clicked!");});
For ASP.NET try this:
<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>
This appears to work on page load and on update panel load
Please find the full discussion here.
Important step for Event binding on Ajax loading content...
01. First of all unbind or off the event on selector
$(".SELECTOR").off();
02. Add event listener on document level
$(document).on("EVENT", '.SELECTOR', function(event) {
console.log("Selector event occurred");
});
Here is my preferred method:
// bind button click to function after button is AJAX loaded
$('#my_button_id').bind('click', function() {
my_function(this);
});
function my_function () {
// do stuff here on click
}
I place this code right after the AJAX call is complete.
I would add one point that was NOT obvious to me as a JS newb - typically your events would be wired within document, e.g.:
$(function() {
$("#entcont_table tr td").click(function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
}
With event delegation however you'd want:
$(function() {
// other events
}
$("#entcont_table").on("click","tr td", function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
If your event delegation is done within the document ready, you'll an error of the like:
cant assign guid on th not an boject

How to edit an event trigged by an anchor from inside of a $.get() function?

I'm trying to make a script that, when you click on an anchor, a $.get function will get the anchor's href and then the href will be removed, but I cannot edit anything about the anchor from inside de get element. Example:
// make anchor disappear for example (doesn't work)
$('.belovedanchor').click(function(e) {
$.get($(this).attr('href')).done(function() {
$(this).hide();
});
});
// make an anchor disappear using a function (doesn't work too)
$('.belovedanchor').click(function(e) {
function do() { $(this).hide(); };
$.get($(this).attr('href')).done(function() {
do();
});
});
I don't understand why $(this) change to work with the $.get function istead of the .click event.
How would you guys do it?
You have a couple problems. Edit: Only one problem -- I now see from your comment below that belovedanchor is not the actual selector in your code.
First, your jQuery selector for the click event handler is most likely incorrect. Change $('belovedanchor') to $('.belovedanchor') or $('#belovedanchor') depending if the anchor is identifiable by either class or element ID respectively.
Second, this in the do callback function does not refer to the anchor. In JavaScript, scope is set at the function level, so anytime you declare a new function, this will refer to that new scope.
Do this instead:
$('belovedanchor').click(function(e) {
var anchor = $(this);
function do() { anchor.hide(); };
$.get($(this).attr('href')).done(function() {
do();
});
});
Simplified:
$('belovedanchor').click(function(e) {
var anchor = $(this);
$.get(anchor.attr('href')).done(function() {
anchor.hide();
});
});
This may work properly
$('.belovedanchor').click(function() {
var selectedancor = $(this);
var myurl = $(this).attr('href');
$.get(myurl, function() {
selectedanchor.hide();
});
});

How to bind Events on Ajax loaded Content?

I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click event is bound on DOM elements that are not loaded with my AJAX function.
What do I have to change, such that the event will be bound?
My HTML:
<a class="LoadFromAjax" href="someurl">Load Ajax</a>
<div class="appendedContainer"></div>
My JavaScript:
$(".LoadFromAjax").on("click", function(event) {
event.preventDefault();
var url = $(this).attr("href"),
appendedContainer = $(".appendedContainer");
$.ajax({
url: url,
type : 'get',
complete : function( qXHR, textStatus ) {
if (textStatus === 'success') {
var data = qXHR.responseText
appendedContainer.hide();
appendedContainer.append(data);
appendedContainer.fadeIn();
}
}
});
});
$(".mylink").on("click", function(event) { alert("new link clicked!");});
The content to be loaded:
<div>some content</div>
<a class="mylink" href="otherurl">Link</a>
Use event delegation for dynamically created elements:
$(document).on("click", '.mylink', function(event) {
alert("new link clicked!");
});
This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/
If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!
Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:
$('.parent-element').on('click', '.mylink', function(){
alert ("new link clicked!");
})
Some more reading on the subject:
https://learn.jquery.com/events/event-delegation/
http://jqfundamentals.com/chapter/events
if your question is "how to bind events on ajax loaded content" you can do like this :
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});
so you don't need to place your configuration to every you ajax code
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
Example -
$( document ).on( events, selector, data, handler );
For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready"
For e.g :
$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'post',
url: url,
data: $(this).serialize(),
success: function (data) {
// DO WHAT YOU WANT WITH THE RESPONSE
}
});
});
});
If your ajax response are containing html form inputs for instance, than this would be great:
$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) {
if (this.value == 'Yes') {
// do something here
} else if (this.value == 'No') {
// do something else here.
} else {
console.log('The new input field from an ajax response has this value: '+ this.value);
}
});
use jQuery.live() instead . Documentation here
e.g
$("mylink").live("click", function(event) { alert("new link clicked!");});
For ASP.NET try this:
<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>
This appears to work on page load and on update panel load
Please find the full discussion here.
Important step for Event binding on Ajax loading content...
01. First of all unbind or off the event on selector
$(".SELECTOR").off();
02. Add event listener on document level
$(document).on("EVENT", '.SELECTOR', function(event) {
console.log("Selector event occurred");
});
Here is my preferred method:
// bind button click to function after button is AJAX loaded
$('#my_button_id').bind('click', function() {
my_function(this);
});
function my_function () {
// do stuff here on click
}
I place this code right after the AJAX call is complete.
I would add one point that was NOT obvious to me as a JS newb - typically your events would be wired within document, e.g.:
$(function() {
$("#entcont_table tr td").click(function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
}
With event delegation however you'd want:
$(function() {
// other events
}
$("#entcont_table").on("click","tr td", function (event) {
var pk = $(this).closest("tr").children("td").first().text();
update_contracts_details(pk);
});
If your event delegation is done within the document ready, you'll an error of the like:
cant assign guid on th not an boject

Mouseover event in jQuery

I have the following mouseover function:
$('.msg_id').live("mouseover", function() {
$(this).css('cursor', 'pointer');
tid = $(this).attr('id');
idx = $(this).attr('name');
resp="";
$.ajax({
async: false,
url: "log_msg.asp",
data: $("#msgForm").serialize() + "&aktion=popup&msg_id="+tid+"&msg_id"+idx,
success: function(data){
$("#"+tid).html(data);
}
});
//$.post("log_msg.asp", $("#msgForm").serialize() + "&aktion=popup&msg_id="+tid+"&msg_id"+idx,
//function(data) {
//}).success(function(){
//$("#"+tid).html(data);
//resp=data;
//$('#bub'+tid).css('display', 'block');
//popd.css('display', 'block');
//});
});
It puts some html code inside .msg_id ( $("#"+tid).html(data); ).
The function mouseover is called in a loop. The ajax request is sent all the time while mouseovering it, not only once.
How can I fix it?
I have also tried mouseenter, but it fires in a loop too.
You might want to use the mouseenter() event instead, as mouseover will fire upon every move inside the element.
$('.msg_id').live("mouseenter", function() {
//Do work here
});
or if live isn't required, simply:
$('.msg_id').mouseenter(function() {
//Do work here
});
MouseOver():
Will fire upon entering an element can fire inside of any child elements.
MouseEnter():
Will fire upon entering an element, and only that element.
You want to use mouseenter

Categories