Jquery AJAX: How to Change button value on "success"? - ajax

I have multiple buttons on one page. Upon click, I track the button id, send the button value to backend php code that returns me updated value by changing the database. I am able to get back everything i need except this: Setting the button value on success!! This is the code i'm using:
$(document).ready(function(){
$("input[type='button']").click(function(){
var selected = $(this).attr("id");
var val = prompt("Enter new value",0);
$.ajax({
url:'updateCostItems.php',
data:{toupdate:selected, updatewith:val},
type:'GET',
dataType:'json',
success:function(json){
$(this).val(json.update);
},
error:function(xhr, status){
alert("Problem");
},
complete:function(xhr, status){
}
});
});
});

I think this is not correct, because the callback is run in the global scope.
Untested, but try just before $.ajax to write var $this = $(this) and then in your callback use $this.val(json.update)
Edit: Updated code snippet to ensure local $this by declaring with var. Other posts suggest using var button = $(this) which is probably better in bigger projects where keeping track of the variables is more challenging - but all the answers are the same really.

The problem is that 'this', inside the ajax request, points to the xhr object, not the button. You should store the reference to the button prior to do the call, like var button = $(this); and later updating it button.val(json.update);

Store the button in a local variable in the outer loop, then refer to that variable in the inner scope of the success handler:
$(document).ready(function(){
$("input[type='button']").click(function(){
var $btn = $(this)
var selected = $btn.attr("id");
var val = prompt("Enter new value",0);
$.ajax({
url:'updateCostItems.php',
data:{toupdate:selected, updatewith:val},
type:'GET',
dataType:'json',
success:function(json){
$btn.val(json.update);
},
error:function(xhr, status){
alert("Problem");
},
});
});
});

$(this) will not refer to the button at the time the success function is called. You will need to pass the button (or the button's id) along as a parameter to your callback. Storing a single global variable is not sufficient since you could potentially click on a 2nd button before the first ajax call returns.

Related

Ajax call after postback in jquery function in mvc3

I am having problem for Ajax call from Jquery function after postback in mvc3. The action method mentioned in the ajax section below doesn't get called after postback whereas it works fine before postback.
actually I am trying to get value for textbox. here is my Jquery function..
$("#ddlDiagnosis").change(function () {
alert($("#ddlDiagnosis").val());
var selection = $("#ddlDiagnosis").val();
var datatosend = { selectedValue: selection };
$.ajax({
url: "home/GetDiagnosisICDCode",
type: 'POST',
data: { selectedValue: $(this).val() }, //datatosend,
datatype: 'json',
success: function (data) {
var elements = "";
$.each(data, function () {
$("#txtICDCode").val(this.ICDcode)
})
}
});
});
You need to change URL like this
url: "/home/GetDiagnosisICDCode",
and GetDiagnosisICDCode must be public method.
You cannot force to make ajax calls after a postback as the state of the page is changing after the full postback. So it wont happen. The function which is containing the ajax call should be executed to make the ajax request. For this you may use jquery's $(document).ready(function(){});Encapsulate your method using jquery's Initialization function. In a sequence, say you can make an ajax call first then you can make a full postback. But the reverse is not possible by maintaining the state of the page.

ajax call not responding with $.post

What i am trying to do is to get the value of the selected elements by jquery selection. After that, those value are post to php script via ajax and then retrieve the data from the database and display it on the same page (something called autocompete).
var marvalue=$("input[name=m_status]:checked").val();
var fromhvalue=$("#fromheight").val();
var tohvalue=$("#toheight").val();
var value = $("#edu_det1").val();
alert (value);
var regvalue = $("#religion").val();
alert (regvalue);
var occvalue = $("#occupation").val();
alert (occvalue);
var convalue = $("#country").val();
alert (convalue);
Alert is there to check the correct values. As you see the code above this will get the values from the different input elements.
Below is the code i used to post to php
/*
$.post("regsearch.php", {queryString: ""+value+"",queryString1: ""+marvalue+"",queryStringfage: ""+fage+"",queryStringtage: ""+tage+""+queryStringfromh: ""+fromhvalue+""+queryStringtoh: ""+tohvalue+""+}, function(data) { // Do an AJAX call
$('#suggestions').fadeIn(); // Show the suggestions box
$('#suggestions').html(data); // Fill the suggestions box
});
*/
The problem :
when the comment is removed nor the alert popup and neither the result displayed. Ok about the result as no query is posted.
Major part is that when i use the below code which hold only m_status and edu_det1 it works.
marvalue=$("input[name=m_status]:checked").val();
alert (marvalue);
var value = $("#edu_det1").val();
alert (value);
The post code for above is
$.post("regsearch.php", {
queryString: ""+value+"",
queryString1: ""+marvalue+"",
queryStringfage: ""+fage+"",queryStringtage: ""+tage+""
}, function(data) {
// Do an AJAX call
$('#suggestions').fadeIn(); // Show the suggestions box
$('#suggestions').html(data); // Fill the suggestions box
});
The code for age and it verification is not added here. What is the problem and how to sort this out?
It will be better if you use jquery serialize() function. This will make your life easier to work with forms.
var querstring = $(form).serialize();
above will help
I guess using ajax post jQuery.ajax() will do the same thing and you can even serialize the fields in your page.
http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
I have done similar type of code
UserName is the field Which I am passing
var data = $('#Username').serialize();
$('#usernameCheck').empty();
if (!$("form").validate().element("#Username"))
return;
$.ajax({
url: '/SignUp/CheckUsername',
type: 'POST',
data: data,
async: true,
success: function (result) {
if (result == 1) {
$('#usernameCheck').html('<font color=green>Username available</font>');
usernameOK = true;
}
else if (result == 2) {
$('#usernameCheck').html('<font color=red>Username not available</font>');
usernameOK = false;
}
else {
$('#usernameCheck').empty();
usernameOK = false;
}
}
});
First of all you should use your console to see Javascript errors, as I'm sure this will generate some. For example that querystring is undefined.
I'd also console.log instead of alert, it is less annoying and more informative.
Then: you dont need to use f.e. ""+marvalue+"" - just use marvalue. On the other hand f.e. queryString should be quoted...
$.post("regsearch.php", {'queryString':value,'queryString1': marvalue,'queryStringfage':fage,'queryStringtage':tage,'queryStringfromh': fromhvalue,'queryStringtoh':tohvalue}, function(data) {
$('#suggestions').fadeIn();
$('#suggestions').html(data);
});

mootools inline Ajax call not working

I am trying to use mootools ajax requests to record clicks on outgoing links. So far here is what I'm doing.
Each link looks like follows:
<div id="1">
StackOverflow
</div>
The javascript function clickRecord(id) is defined as follows:
function clickRecord(id){
var u = "record.php";
var req = new Request({
method: 'post',
url: u,
data:{'id':id},
onComplete:function(response){
}
}).send();
}
The problem I have is this. If I add a return false; to the onclick="" declaration, everything works fine, of course the problem there is that click does not take the user to the intended page. If I do not have the return false; then it seems like the ajax call is never executed.
I thought the onclick event should execute first and then only the default action should execute. Is this not the case?
There is an even stranger scenario if you use onmousedown event instead. It seems like on Firefox, if you use the onmousedown event, once you go to the new page, you cant simply navigate back to the old page, you have to refresh the old page. Else the call is not executed. This does not happen on IE.
Don't use onclick - very 1995.
Instead attach an event to the element and use event.stop(), ie:
StackOverflow
JS:
document.getElements('a').addEvents({
click: function(event) {
event.stop();
var u = 'record.php';
var req = new Request({
method: 'post',
url: u,
data: {
'id': this.get('data-id');
},
onComplete: function(response) {}
}).send();
}
});
Btw. <div id="1"> this is not valid in HTML, an ID'd needs to start with a letter.
OK. Found an answer to one of the questions:
The inline mootools request did not execute when declared through the onclick().
It seems this was caused by the script not being synchronous. So probably it returns without actually fully committing the request, and the browser then moves to another page breaking the execution. Adding a synchronous call to the script fixes the problem:
function clickRecord(id){
var u = "record.php";
var req = new Request({
async:false,
method: 'post',
url: u,
data:{'id':id},
onComplete:function(response){
}
}).send();
}
The second problem that was mentioned on the onmousedownevent, i.e. firefox not executing the ajax call if the browser navigates back is still unsolved. However I am leaving that to be as that wasn't the main question raised.

Return false not working for jQuery live

Well this has me well and truly stumped. After searching for the last few hours I still cannot seem to work out where I am going wrong.
I am trying to append an AJAX response to a container when it gets clicked. That works fine but I don't want it to append another object when the elements from the AJAX response also gets clicked.... so:
<div id="container">
<!-- AJAX response to get inserted here, for example -->
<span id="ajaxResponse"></span>
</div>
Here is my script:
$('#container').click(function(e) {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
return false;
});
So it works fine but for some reason the click event on #container also fires when I click on the AJAX response span!?
According to jQuery documentation:
To stop further handlers from
executing after one bound using
.live(), the handler must return
false. Calling .stopPropagation() will
not accomplish this.
But unless I am mistaken, I am calling false? :(
Anyone help me out on this?
UPDATED:
So the only way I can get it to work is by updating my code to this:
$('#container').live('click', function() {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
});
$('#ajaxResponse').live('click', function(e) {
return false;
});
This seems a little messy though... anyone have a better solution?
Where is live part you mention in the title of the question ?
It is how the event model works.. If you click on element which does not handle the event, the event will travel up the DOM hierarchy until it finds an element that handles the click (and stops its propagation..). Otherwise you would not be able to put an image inside a <a> tag and click on it..
You can bind a canceling handler on the inner element assuming you have someway to target it..
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
// assuming the returned data from ajax are wrapped in tags
$(current_el).children().click(function(){ return false;});
}
});
I think the return false is referring to something else in this case...
you should try calling stopPropagation() - this should stop the "click" function from propagating down to the ajaxResponse span....
One option that you may want to try is switching over to using live(). Essentially, the click event you setup is calling bind(), and the solution you referenced is using live() which is a variation on bind().
For example:
$('#container').live("click", function(e) {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
return false;
});
HTH

jquery ajax post - not being fired first time

I'm trying to do an ajax post after a button is clicked, and it works in firefox but not in IE the first time the page is loaded. It does work if I refresh the page and try again second time - but not first time and this is crucial.
I've scanned over various web pages - could it be anything to do with the listener? (I've just seen this mentioned mentiond somewhere) Is there something not set correctly to do with ajax and posting when page first loads?
$(document).ready(function() {
$('#btnCont').bind('click',function () {
var itm = $("#txtItm").val();
var qty = $("#txtQty").val();
var msg = $("#txtMessage").val();
var op_id = $("#txtOp_id").val();
//if i alert these values out they alert out no prob
alert(itm+'-'+qty+'-'+msg+'-'+op_id);
$.ajax({
type: "POST",
url: "do_request.php?msg="+msg+"&itm="+itm+"&qty="+qty+"&op_id="+op_id,
success: function (msg) {
document.getElementById('div_main').style.display='none';
document.getElementById('div_success').style.display='block';
var row_id = document.getElementById('txtRow').value;
document.getElementById('row'+row_id).style.backgroundColor='#b4e8aa';
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
});
I would start debugging the click event. I.e. if you try to put .bind into a a href tag, the tag itself has a click event that may act on an unwanted way. There exist a command that are named something like event.preventDefaults() that avoids the standard feature of click. After All, you try to manipulate the DOM last of all actions (document.load).
$('#btnCont').bind('click',function () { .. }
I would also try to debug the same functionality with adding onClientClick to the tag instead of adding bind to the document load.
I hope that bring some light.

Resources