ajax success function cant change button text - javascript

I have a simple but strange question, I am not able to change the value of the button in an ajax post success callback, I am sure the callback gets executed as the alert was shown. Also, those buttons are created statically, I did not create them dynamically using Jquery.
Below is my ajax:
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "/?handler=Queue",
data: $.param(params),
dataType: "json",
success: function (response) {
$("#btn-queue-lib").val("Cancel Queue");
alert(response.responseText);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
However, if I change the problem line outside of ajax, it works fine:
$("#btn-queue-lib").val("Cancel Queue"); // Either Here
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "/?handler=Queue",
data: $.param(params),
dataType: "json",
success: function (response) {
alert(response.responseText);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
$("#btn-queue-lib").val("Cancel Queue"); // Or Here

I have found out the problem, I dunno for some reason the server is returning the success message but actually returning a badrequest. Hence I mistaken that the success function should be called. If I put the problem line in the error callback, it works fine. Thanks guys for your efforts !!!
~ (^_^)∠※

document.getElementById('btn-queue-lib').innerText = 'Cancel Queue'

change
$("#btn-queue-lib").val("Cancel Queue");
to
$("#btn-queue-lib").text("Cancel Queue");
and place the statement in ajax success function right before alert.

In Success use
$("#btn-queue-lib").html("Cancel Queue");

Even I have faced the same issue... I managed it as below hope it will help for too
function changeAfterAjax(){
$.ajax({
type: "GET",
url:"https://reqres.in/api/users?page=2",
//data: $.param(params),
dataType: "json",
success: function (response) {
$("#btn-queue-lib").text("Cancel Queue");// this is also works fine
//changeBtnTxt('btn-queue-lib','Cancel Queue');
//alert(response);
},
error: function (xhr) {
console.log(xhr);
}
})
}
function changeBtnTxt(id,txt){
$("#"+id).text(txt);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="changeAfterAjax()" id="btn-queue-lib">Click to chanage after ajax</button>

Related

hide() / show() not working after ajax request

$.ajax({
type: "POST",
url: '/test/',
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", Cookies.get('csrftoken'));
},
success: function (data) {
console.log(data);
},
error: function name(resp) {
// this part is not working
$('#steps-uid-0-p-0').show();
$('#steps-uid-0-p-1').hide();
}
});
I am unable to show and hide a div, if the response from ajax is an error. It works well in the console. I have tried using setTimeout() but is there any other solution?

Ajax Response is not defeined

I am quite green when it comes to AJAX and am trying to get an email address from an ASP.Net code behind function
When using the below code I am getting the error as per the title of this issue.
This is the code I am using
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
});
which is an adaptation of the code from this site.
ASP.Net Snippets
When changing the line
success: OnSuccess to success: alert(response) or success: alert(data)
I get the error up, but if I use success: alert("ok") I get the message saying ok so I suspect that I am getting into the function as below.
<System.Web.Services.WebMethod()> _
Public Shared Function FindEmailAddress(ByVal id As String) As String
Dim response As String = GetEmail(id)
Return response
End Function
I would be extremely grateful if someone to help me and let me know where I am going wrong on this one.
thanks
I think you have can check the state of failure by using this code below as I think there is wrong syntax used by you.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: JSON.stringify({id: ' + $(".txtRequester").val() + ' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, header){
console.log(data);
},
error: function (response) {
alert(response.d);
}
});
}
});
then definitely you will get error response, if your success won't hit.
You have not called the function thats why its never get called.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
ShowCurrentTime();
});
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Onsuccess(response);
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
This will help :)
use ajax directly ,
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
var cond = $(".txtRequester").val();
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: {id:cond},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
Change $('.txtRequester') to $('#txtRequester')
and
Change $("txtRequester").val to $('#txtRequester').val()

JQuery-Ajax code doesnt seem to go within the Success block

No matter what I try, this Ajax request doesnt seem to be going inside the success block. Can anyone tell me whats happening? This is driving me crazy.
$.ajax({
url: "/Index/AddItem",
type: "post",
contentType: "application/json",
data: JSON.stringify({
Srl: $("#Srl").val(),
Description: $("#Description").val(),
Comment: $("#Comment").val()
}),
headers: {
"RequestVerificationToken": "#TokenHeaderValue()"
},
dataType: "json",
success: function (data) {
alert("Done");
$('#tknGen').html(data);
}
});
Im trying to replace a with the response data. But even the alert is not getting fired. So, Im guessing its a problem with the success block
Try this
$.ajax({
url: "/Index/AddItem",
type: "post",
contentType: "application/json",
data: {
Srl: $("#Srl").val(),
Description: $("#Description").val(),
Comment: $("#Comment").val()
},
headers: {
"RequestVerificationToken": "#TokenHeaderValue()"
},
dataType: "json"
}).done(function (data) {
alert("Done");
$('#tknGen').html(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(errorThrown);
});
"done" and "fail" callback are the recommended way to handle result since Query 1.8 (at replacement for success and error).
The fail callback will show up more information about the error thrown server-side.

JQuery AJAX return XML on GET request complete

I need to execute code once my XML file (or object) has been returned successfully. Not before, and not repeatedly; just one time after the file has been returned.
Does my code already do what I am trying to accomplish? It seems to have failed a couple of times in IE and I need to be sure that it is reliable.
$(document).ready(function(){
(function GetFile(){
$.ajax({
type: "GET",
url: "Produce.xml",
dataType: "xml",
cache: false,
success: function(result) {
alert("XML File is loaded!");
alert(result);
},
async: true
});
})();
});
I know that there are onerror codes and readystatechange values that can be checked and verified... Should I be checking these values while polling the server for the XML file?
remove comma after async: true
Also, your GetFile function will execute immediately if you're not planning on calling again then might as well go with anonymous or remove that function all together
$(document).ready(function(){
$.ajax({
type: "GET",
url: "Produce.xml",
dataType: "xml",
cache: false,
success: function(result) {
alert("XML File is loaded!");
alert(result);
},
async: true
});
});
This was added as an edit by the original asker, I have converted it to a community wiki answer because it should be an answer, not an edit.
Fixed it thanks to #AndrewDouglas suggestion and here is the new code (which works great):
$(document).ready(function(){
(function GetFile(){
$.ajax({
type: "GET",
url: "Produce.xml",
dataType: "xml",
cache: false,
success: function(result) {
alert("XML File is loaded!");
alert(result);
},
error:function (xhr, ajaxOptions, thrownError){
z++;
alert(xhr.status);
alert(thrownError);
setTimeout(GetFile, 5000);
console.log("Error " +z+": " + thrownError);
},
async: true
});
})();
});
One final comment, you should be able to change setTimeout(GetFile, 5000) to setInterval(GetFile, 5000) and then it will continually poll your XML file. Doing that in the success section would make a bit more sense, however.

Jquery Display Message then Ajax then hide message

il give an example
document.ready(function() {
$("#Show").bind("click", function()
{
var F = Function2();
if (F)
{
// Do Other Stuff.
}
}
});
function Function2()
{
$("#Message").Show();
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").Hide();
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
}
</script>
<div id="Message" style="display:none;">
<!-- Loading Image In here -->
</div>
<a href="#" id="Show" onclick="return:false;">Show then Hide</false>
</code>
Now what I want to happen is for this messagebox to show however the AJAX for some reason wont show it until the AJAX Request is finished by which point it is too late. I have set async to false which hasent helped either.
I think the root of this issue is a syntax error. JavaScript is case sensitive, so the correct syntax would be lowercase show() and hide()
If you're still having an issue after fixing the syntax errors, try using the ajaxStart event to show the message and hide it on success.
//use the ajaxstart event to display the message
$('#message').ajaxStart(function() {
$(this).show("slow");
});
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").hide("slow"); //hide message on success
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
Delaying the show or hide
$("#message").delay(3000).hide("slow");
Here's a jsFiddle: http://jsfiddle.net/rs83R/
Try hiding the Message div in the click event after getting true or false.
Remove the async:false, I do not think that is anyway relevant to fixing this problem. The purpose of AJAX call is to make an asynchronous call.
Also, there is an error its not $("#Message").Show() its $("#Message").show() with all lowercase, same goes for hide().
Try changing these, I hope it should work.

Categories

Resources