Select only the clicked button JQuery - javascript

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

Related

Passing into ajax success function [duplicate]

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');
}
});
});

Calling Ajax request function in href

I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});

making ajax call fire only once

I have an ajax call that is being fired multiple times.
I have used e.stopImmediatePropagation() and return false to prevent it from firing more than once. Is there another sure shot way to prevent ajax call more than once.
$(document).on('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
e.stopImmediatePropagation();
return false;
});
You can use jQuery .one()
$(document).one('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
});
var n = null;
$(document).one('click', '#button1', function(e){
$.ajax({
url: 'https://gist.githubusercontent.com/anonymous/9a6997f09de9b68c59b2/raw/f7d7b756005ad6d2b88cf0211f78a2990d7d2dc7/content.json',
data: {},
method: 'HEAD',
success: function(data, textStatus, jqxhr) {
console.log(jqxhr.getAllResponseHeaders())
$("body").append("<br>textStatus: " + textStatus + "<br>count: " + ++n)
},
error: function(err){
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button1">click</button>
You can use jquery.data() to store a boolean to indicate whether your function has been run before.
$(document).on('click', '#button1', function(e) {
$button = $("#button1");
if ($button.data("pressed") !== true) {
$.ajax({
url: 'http://non-existentpage',
data: {},
method: 'POST',
success: function(data) {
alert('ajax');
$button.data("pressed", true);
},
error: function(err) {
alert('ajax');
$button.data("pressed", true);
}
});
}
});
#button1 {
border: 1px solid #000;
display: inline;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button1">ajax</div>
You could also add a condition checking if the button has already been clicked by setting a variable to true after it has been clicked:
window.document_clicked = false;
$(document).on('click', '#button1', function(e){
if(!window.document_clicked){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
window.document_clicked = true;
},
error: function(err){
}
});
}
});
Adding async: false to your current function
or USE .click
$('#button1').click(function(e){
});
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
$(document).on('click', '#button1', function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
async: false,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
e.stopImmediatePropagation();
return false;
});
Try this instead
$('#button1').click(function(e){
$.ajax({
url: 'http://www.page.com',
data: data,
method: 'POST',
success: function(data){
},
error: function(err){
}
});
Much simpler and it should fix that issue of multiple ajax calls.
You also shouldn't have to return false.

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) {
}
});
}
}

Variable not working in simple Ajax post

Can't seem to get the variable getID to work. I'm trying to change the html of the div. I know that the variable has the right value.
$('.cardid').change(function() {
var getID = $(this).attr('value');
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: "id="+getID,
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
});
Write data in $.ajax as data: {id : getID}, instead of data: "id="+getID,
Use val to get the value of an input :
var getID = $(this).val();
As you're making a POST request, you should also use the data argument to let jQuery properly send the value :
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: {id:getID},
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
You can try this:
$('[id="'+getID+'"]').html(data);
and yes you should pass it this way:
data:{id:getID}

Categories

Resources