$.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?
Related
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>
I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});
I am using ASP.net MVC, and following is the Html code
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
<div id=waitscreen>
//some code
</div>
Code in external js
function _post(someparameter)
{
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
Also tried adding document ready in above code it is still not working
Above code worked fine and it show and hide as expected, but now I need to repeat ajax call in every page so I decided to move in external JS file now same code is not showing waitscreen.
Things I tried:
Loaded external script in head - Not working
Loaded external script at end of page - Not working
Question: I want to make hide and show work from external JS file
The following code snippet should help you. Tested by including the external JS file in the <head> of the main document and just below the inclusion of jQuery.
// main window
var json = {"key": "value"}
console.log('before calling _post()');
_post(json); // call external JS
// code in external JS say test.js
function _post(someparameter)
{
console.log('external JS called!');
$.ajax({
type: "POST",
url: 'http://www.niketpathak.com',
dataType: 'json',
data: someparameter,
async: true,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
// $("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
//delaying the error callback
setTimeout(function() {
$("#waitscreen").hide();
console.log('after completing the http-request');
}, 500);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=waitscreen>
Waitscreen....
</div>
Also, note that I have used async: true (which is also the default) since setting it to false is deprecated and not a good idea as it blocks the UI.
My ajax code in External.js file,
function _post()
{
var data = {
Email: "a#a.com",
Password:"1111"
}
$.ajax({
type: "POST",
url: "/Home/hello/",
dataType: 'json',
data: data,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
In my HomeController, I have hello method like this,
[HttpPost]
public ActionResult hello(LoginViewModel data)
{
ViewBag.Message = "Your contact page.";
return Json(data, JsonRequestBehavior.AllowGet);
}
And in my all the views I have the "waitscreen" div.
Now I just reference the External.js file to my _Layout page, I just drag and drop after jquery reference.
<script src="~/Scripts/External.js"></script>
Then in end of the same _Layout page, i just call the method like this,
<script>
_post();
</script>
Everything working properly.
Note: If you have only one parameter in your hello action method and suppose you have written like (int x) then in that case it will through 500 error. Because in your RouteConfig.js its mentioned that, by default the parameter name should be id. So you need to write int id.
Hope its help.
Here is my code.
$.ajax(this.url, {
type: "GET",
//dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("x-token", token)
},
success: function (data) {
console.log(data);
},
error: function(){
console.log('error');
}
});
I am not able to send ajax request by that code. I also try hearder: {"x-token": token}, In place of beforeSend: but its also not working for me.
I have following ajax call:
$.ajax({
type: "GET",
url: "/Company/validateForm",
dataType: "json",
data: {
'txtCompanyName': txtCompanyName,
'txtCompanyContactPerson': txtCompanyContactPerson,
'txtCompanyPhone': txtCompanyPhone,
'txtCompanyFax': txtCompanyFax,
'txtCompanyEmail': txtCompanyEmail,
'txtCompanyWebsite': txtCompanyWebsite,
'txtZipcode': txtZipcode,
'txtCountry': txtCountry,
'txtAddress1': txtAddress1,
'txtAddress2': txtAddress2,
'txtCompanyRegNo': txtCompanyRegNo
},
success: function (responceMessage) {
alert(responceMessage);
if (responceMessage != "1") {
alert(responceMessage);
} else {
saveCompanyInformation();
}
},
error: function () {
alert('failure');
}
});
I have made sure that call is going to server side and returning proper message in string format.
But when call from validateForm method on server side is returned, it directly goes to failure instead of success method.
I can't figure out what I'm doing wrong here.
Console is showing:
GET http://localhost:49273/Company/validateForm?txtCompanyName=+x&txtCompanyCon…ebsite=&txtZipcode=&txtCountry=&txtAddress1=&txtAddress2=&txtCompanyRegNo= 500 (Internal Server Error)
I just made cache:false in ajax and code worked.
It was as follows:
$.ajax({
type: "POST",
url: "/Company/validateForm",
cache:false,
dataType: "json",
data:
{
'txtCompanyName': txtCompanyName,
'txtCompanyContactPerson': txtCompanyContactPerson,
'txtCompanyPhone': txtCompanyPhone,
'txtCompanyFax': txtCompanyFax,
'txtCompanyEmail': txtCompanyEmail,
'txtCompanyWebsite': txtCompanyWebsite,
'txtZipcode': txtZipcode,
'txtCountry': txtCountry,
'txtAddress1': txtAddress1,
'txtAddress2': txtAddress2,
'txtCompanyRegNo': txtCompanyRegNo
}
,
success: function (responceMessage) {
if (responceMessage != "0") {
alert(responceMessage);
}
else {
saveCompanyInformation();
}
},
error: function () {
alert('failure');
}
});