Passing into ajax success function [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I have developed following code, I need to pass exact 'this' value ( because lot of items with this class)in to ajax success function. How to do that.
$(document).on('click', '.address_remove_link', function(e) {
var id = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response, this) {
$(this).parent().closest('div').hide(200);
},
error: function(data) {
console.log("error");
}
});
});

The issue is because the scope of this changes within the success handler function. You can store the outer scope in the click handler function instead. Try this:
$(document).on('click', '.address_remove_link', function(e) {
var $link = $(this); // store reference here
var id = $link.attr("data-id");
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response) {
$link.parent().closest('div').hide(200); // to use here
},
error: function(data) {
console.log("error");
}
});
});

One simple way is to use a variable the function closes over:
$(document).on('click', '.address_remove_link', function(e) {
var $this = $(this); // ***
var id = $this.attr("data-id"); // ***
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response) {
$this.parent().closest('div').hide(200); // ***
},
error: function(data) {
console.log("error");
}
});
});
Alternately you could use Function#bind (MDN, spec):
$(document).on('click', '.address_remove_link', function(e) {
var id = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response) {
$(this).parent().closest('div').hide(200);
}.bind(this), // ***
error: function(data) {
console.log("error");
}
});
});

You are working on the scope of the click event handler function, so you can create a self variable and use it like this:
$(document).on('click', '.address_remove_link', function(e) {
var self = $(this),
id = self.attr('data-id');
$.ajax({
type: 'POST',
url: 'inc/controlllers/detele_shipping_addr.php',
data: {
internalId: id
},
success: function(response) {
// Do something with "response"
self.parent().closest('div').hide(200);
},
error: function(data) {
console.log('error');
}
});
});

Related

Select only the clicked button JQuery

I have this ajax function, which should change the style of the clicked button, but for some reason it does not work. I'm not getting any errors in the console and the ajax call is successful Any idea what's wrong here?
function AcceptOffer(id)
{
var json = {
id : id
};
$.ajax({
type: 'POST',
url: "#Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(this).text("Accepted");
$(this).css("background-color", "green");
$(this).css("color", "white");
$(this).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
</script>
Html:
Accept
Your issue is with using this incorrectly. The way you are using it, it is going to reference the object you pass into the ajax command
function AcceptOffer(id)
{
var json = {
id : id
};
var elemYouWantToChange =...;
$.ajax({
type: 'POST',
url: "#Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(elemYouWantToChange).text("Accepted");
$(elemYouWantToChange).css("background-color", "green");
$(elemYouWantToChange).css("color", "white");
$(elemYouWantToChange).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
-- Edit --
In javascript, you listen for a click like so:
elem.addEventListener('click', function(e) {
console.log(e.target); // You need to get e.target to AcceptOffer so it can style the correct element
AcceptOffer(...);
});
In your code this is not pointing to the anchor tag you just need to pass this reference to your function.
function AcceptOffer(ele, id)
{
var json = {
id : id
};
$.ajax({
type: 'POST',
url: "#Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(ele).text("Accepted");
$(ele).css("background-color", "green");
$(ele).css("color", "white");
$(ele).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
So the anchor tag will be:
Accept

I am not able to clear me textare value after the ajax is submited successful

$(document).on('click','#commentsubmitimage',function(e) {
console.log("beni");
e.preventDefault();
var content =$('#commenttext').val();
console.log(content);
var imageid = $('#imagecomid').val();
$.ajax({
type: 'POST',
url: "/user/postcoment/" + imageid,
data:{
contenta:content
},
success: function(data) {
// have try this
document.getElementById(commenttext).innerHTML = '';
// have try this
$('#commenttext').val('');
},
error: function(data) {
console.log(data);
}
});
});
I want to clear my textareaa with id ="commenttext" i have try all the methods and it doesnt happen nothing any suggest ?
if your success call back working correctly then write
success: function(data) {
alert("working");
$("#commenttext").val("");

Create function inside deprecated javascript function

Currently I have a javascript file structure which seems deprecated to me, inside this function there's an ajax call, and after the ajax call giving response I want to add ajax function, but if I have to define it 1 by 1 for every ajax response type, it will consume a lot of space so I need to make a function which will call this ajax function, but I don't know where to place this function that I will make. here's my code
return Component.extend({
defaults: {
template: 'Icube_Snap/payment/snap'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function() {
$.getScript(js, function() {
$.ajax({
type: 'post',
url: url.build('snap/payment/redirect'),
cache: false,
success: function(data) {
var token = data;
var methods = [];
var methodSnap = $('input[name=snap-method]:checked').val();
snap.pay(token, {
enabledPayments: methods,
onSuccess: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onPending: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onError: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onClose: function() {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
}
});
}
});
});
}
});
I just added a successcallback and an errorcallback to the POST function. But if you want you can ignore those functions and implement the success and error functionality inside the function itself without using callbacks.
return Component.extend({
defaults: {
template: 'Icube_Snap/payment/snap'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function() {
$.getScript(js, function() {
$.ajax({
type: 'post',
url: url.build('snap/payment/redirect'),
cache: false,
success: function(data) {
var token = data;
var methods = [];
var methodSnap = $('input[name=snap-method]:checked').val();
//Define a function to send the POST request here.
//////////////////////////////////////////////////
var sendPayment = function(param, successcallback, errorcallback) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: param.id,
message: param.message
}
success: function(data) {
successcallback(data);
},
error: function(error) {
errorcallback(error);
}
});
};
snap.pay(token, {
enabledPayments: methods,
onSuccess: function(result) {
//Call sendPayment method and you can
//pass whatever you want.
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onPending: function(result) {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onError: function(result) {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onClose: function() {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
}
});
}
});
});
}
});

Checking dynamically generated element in jQuery?

Please consider the following code:
function autoRecursiveLoad(checkingElementId) {
if (checkingElementId.length) {
return;
}
else {
var targetId = $("#targetContent");
var requestUrl = $('#ajaxUrl').val();
$.ajax({
url: requestUrl,
cache: false,
type: "POST",
async:false,
beforeSend: function(){
},
complete: function(){
autoRecursiveLoad(checkingElementId);
},
success: function(data) {
targetId.append(data);
},
error: function(e) {
}
});
}
}
in the code: checkingElementId is the id of the dynamically generated element. I used checkingElementId.length to see if it already exists yet, if not, send ajax request to load the content, create div with the id of checkingElementId and then appends to targetId, then perform recursive call.
The problem is the div with id of checkingElementId is generated successfully but the code to check if it exists (checkingElementId.length) never worked. Hence, the above function will loop forever. Am I doing something wrong?
I dont know if it is the best solution or not, but this works for me, I trigger the DOMNodeInserted event on the fly, so the function is updated as follows:
function autoRecursiveLoad(checkingElementId) {
$(document).on('DOMNodeInserted', checkingElementId, function () {
// do something when the new dynamically generated item (checkingElementId) added to the page
});
if (checkingElementId.length) {
return;
}
else {
var targetId = $("#targetContent");
var requestUrl = $('#ajaxUrl').val();
$.ajax({
url: requestUrl,
cache: false,
type: "POST",
async:false,
beforeSend: function(){
},
complete: function(){
autoRecursiveLoad(checkingElementId);
},
success: function(data) {
targetId.append(data);
},
error: function(e) {
}
});
}
}

Combining Jquery and Javascript function

This is a relatively novice question. I have the following jQuery function:
$(function ()
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
});
I'm looking to name and parameterize the function so that I can call it repeatedly (with the parameters queryType and divID which are already included in the code). I've tried unsuccessfully multiple times. Would anyone have any insight?
Just stick it in a function
function doAjax(queryType, divID) {
return $.ajax({
url: 'testapi.php',
data: {query : queryType},
dataType: 'json'
}).done(function(data) {
var id = data[0];
$('#'+divID).html(id);
});
}
and use it
$(function() {
element.on('click', function() {
var id = this.id
doAjax('get_content', id);
});
});
or
$(function() {
element.on('click', function() {
var id = this.id
doAjax('get_content', id).done(function(data) {
// do something more with the returned data
});
});
});
If you're just looking for a simple function to wrap the ajax call give this a try. Place this function above the document ready code.
function callAjax(queryType, divID) {
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data) {
var id = data[0];
$('#'+divID).html(id);
}
});
}
To call the function do this:
callAjax('YourQueryHere', 'YourDivIdHere');
function myFunction(queryType, divID)
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
}
and to call it simply use
myFunction("someQueryType", "myDiv");
function doThis(queryType, divID)
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
}

Categories

Resources