jQuery: On click ajax, get the clicked object in done/fail? - javascript

Simple ajax query, but being triggered for every item of a class using the .click() event. When it gets to the .done() I cannot figure out how to look up the element which was clicked so I can properly remove the m_action class.
Below is the code. I'm sure I'm missing something simple, but I've been searching with Chrome and Firefox web tools without luck, and can't find a duplicate question here on Stack.
In short: using the code below, how do I properly remove the m_action class of the clicked element on a successful jQuery ajax return?
<script type="text/javascript">
jQuery("div#normal .m_action").click(function() {
jQuery.ajax({
url: "./action.php",
type: "POST",
data: { action: this.id }
}).done(function(result) {
jQuery(this).removeClass("m_action");
jQuery(this).html(result);
}).fail(function(result) {
alert("There was an error.")
});
})
</script>

You can just store a reference to it so that it is available anywhere in that scope:
jQuery("div#normal .m_action").click(function() {
var elem = this; // <-- right here
jQuery.ajax({
url: "./action.php",
type: "POST",
data: { action: this.id }
}).done(function(result) {
jQuery(elem).removeClass("m_action"); // <-- elem is still available
jQuery(elem).html(result); // <--
}).fail(function(result) {
alert("There was an error.")
});
});
Just a note for the future, your problem doesn't have to do with jQuery. This is just a simple use of variables within a scope. The this pointer changes within the done function, so you just needed to cache the reference.

This code should work:
$(document).ready(function()
{
jQuery(".m_action").click(function() {
var self = $(this);
jQuery.ajax({
url: "./action.php",
type: "POST",
data: { action: this.id }
}).done(function(result) {
self.removeClass("m_action");
self.html(result);
}).fail(function(result) {
alert("There was an error.")
});
})
});
</script>

Related

jQuery interact with appended data

Can anyone point out what I'm doing wrong here? I'm trying to interact with data (appended using ajax)
The alerts fire if the element is already in DOM, but not when It's appended.
Am I using the ".on" wrong?
$(function() {
$('.card').on('click','.add-exercise', function() {
alert('clicked');
});
// Detect 'enter' key up
$('#search').on('keyup', function(e){
if(e.keyCode == 13)
{
console.log('hit enter key');
$(this).trigger("enterKey");
}
});
$('#search').on("enterKey",function(e){
$.ajax({
url: '{{ url("exercises/load") }}',
method: "POST",
data: {
_token: "{{csrf_token()}}",
search: $('#search').val(),
},
dataType: "text",
success: function(data) {
console.log(data);
$('.exercise-result').remove();
$('.card-deck').append(data);
}
});
});
});
I guess you have other .card elements in data.
You have to assign the event click again for them. The event is currently only assigned to your first .card elements. This is why it doesn't fire on your new .card elements.
I believe you need to add the event again each time the append is done. Try this and let me know if it works:
function addEvent() {
$('.card').on('click','.add-exercise', function() {
alert('clicked');
});
}
$(function() {
addEvent();
// Detect 'enter' key up
$('#search').on('keyup', function(e){
if(e.keyCode == 13)
{
console.log('hit enter key');
$(this).trigger("enterKey");
}
});
$('#search').on("enterKey",function(e){
$.ajax({
url: '{{ url("exercises/load") }}',
method: "POST",
data: {
_token: "{{csrf_token()}}",
search: $('#search').val(),
},
dataType: "text",
success: function(data) {
console.log(data);
$('.exercise-result').remove();
$('.card-deck').append(data);
addEvent();
}
});
});
});
I think the .card element is also loading dynamically, in order to make event delegation works properly you need to bind it to an element which is present at the time of page load.
So either you can attach it to the document object.
$(document).on('click','.card .add-exercise', function(){
// rest of your code
});
or better approach would be, attach to an element which is present at the time of page load(I guess .card-deck is present at the time of page load since you are appending data to that or attach to body tag).
$('.card-deck').on('click','.card .add-exercise', function(){
// rest of your code
});

How to check if my container fully load is completed?

I have an issue, do not know if it possible or not, how to check if my container is already loaded or not, because sometimes it is being loaded faster, sometimes slower and if it does not succeed in time getting an error in javaScript where gridview some functions are not recognizable(because the gridview is not loaded fast enough). Hope it is clear. Thanks for Your time.
Code:
function LoadPartial(partialUrl, container) {
$.ajax({
type: 'POST',
url: partialUrl,
success: function (returnData) {
$(container).html(returnData);
}
});
//.done(function () {
// return;
//});
}
you can use something like this.
$(".container").load(function (){
alert("Loaded :)");
});
Let me know in-case this doesn't work.
You can try using .data()
if ($('#mycontainer').data('loaded')) {
// your code
}
If you mean to find event when data received use "complete" function:
$.ajax({
type: 'POST',
url: partialUrl,
success: function (returnData) {
$(container).html(returnData);
},
complete: function() {
console.log('container filled with data');
}
});

The button does nothing on click in jquery

I am learning jquery and i am stuck with a problem. Here is the code
$(function(){
var gotProducts=new Array();
var productsWithDelete=new Array();
$('.addProducts').on('keyup',function(event) {
var searchVal=$(this).val().trim();
if(searchVal.length > 0) {
$.ajax({
url: 'http://localhost/url',
data: { products: $(this).val(), },
type: 'POST',
dataType: 'html',
success: function(msg) {
$('#printTheProducts').html(msg);
}
});
}
});
$('.productsButton').click(function() {
alert('yes');
});
});
The response I am getting from the ajax call is a button having class productsButton.
Now when i try to click that button I got through ajax then it does not alert yes. I mean it does nothing.
Question:-
What might be the problem?
Try event delegation using .on() for generated button, As they are generated dynamically
$('#printTheProducts').on('click','.productsButton',function(){
alert('yes');
});
Where #printTheProducts is the closest parent element, you can use document or document.body also as a selector!
Syntax:
$(closestparentelement).on('event','targetselector',function(){
});

Function.prototype.apply: Arguments list has wrong type

The error in the title of the post came from jQuery version 1.10.2, line 637
I've got a modal that pops up on a button click with some textboxes and when a button inside the modal is clicked, the information that's in the text boxes is added to a database via AJAX. In order to make the page a little more user-friendly I added a setTimeout function to pause the hiding of the modal so the user can see a verification message that the data was added to the database. Block 1 of my code adds the record to the database, but the setTimeout call doesn't work right:
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
//something about the setTimeout function
//that gives the error in the title
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
//*******this function doesn't run
window.setTimeout(function () {
$('#contact').modal('hide');
$('.modal-body input').each(function () {
$(this).val('');
}, 1000);
});
}
});
}
I fixed it using the code:
(the success function is what we need to pay attention to here)
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
}
});
}
I see that I in the first block I didn't close the each function, and I fixed that in the second block and that's why it works, but for future reference, what does this error really MEAN in this context?
It means that you left off the second argument to setTimeout and instead passed it as the second argument to .each().
edit — it looks like jQuery is picking up the argument (that 1000) and trying to pass it through to its internal each implementation. The .apply() function expects it to be an array.

How do I reference the calling dom element in a jquery ajax success function?

I'm trying to modify the class of an element if an ajax call based on that element is successful
<script type='text/javascript'>
$("#a.toggle").click(function(e){
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text){
if(data.error=='')
{
if($(this).hasClass('class1'))
{
$(this).removeClass('class1');
$(this).addClass('class2');
}
else if($(this).hasClass('class2'))
{
$(this).removeClass('class2');
$(this).addClass('class1');
}
}
else(alert(data.error));
}
});
return false;
});
</script>
<a class="toggle class1" title='toggle-this'>Item</a>
My understanding of the problem is that in the success function this references the ajax object parameters, NOT the calling dom element like it does within other places of the click function. So, how do I reference the calling dom element and check / add / remove classes?
You can just store it in a variable. Example:
$("#a.toggle").click(function(e)
{
var target = $(this);
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text)
{
if(data.error=='')
{
if(target.hasClass('class1'))
{
target
.removeClass('class1')
.addClass('class2');
}
else if(target.hasClass('class2'))
{
target
.removeClass('class2')
.addClass('class1');
}
}
else(alert(data.error));
}
});
return false;
});
jQuery passes the target of the event, along with some other information about it, to your handler function. See http://docs.jquery.com/Events_%28Guide%29 for more info about this.
In your code, it'd be referenced like $(e.target).
Better set ajax parameter : context: this. Example:
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
context: this,
success: function(data,text){
if(data.error=='')
{
if($(this).hasClass('class1'))
{
$(this).removeClass('class1');
$(this).addClass('class2');
}
else if($(this).hasClass('class2'))
{
$(this).removeClass('class2');
$(this).addClass('class1');
}
}
else(alert(data.error));
}
});
I know it's old but you can use the 'e' parameter from the click function.

Categories

Resources