Minor question (solution seems simple but i can't seem to find it on google). I would like to use the data-setting inside my error: function. I know this may sound cryptic but allow me to use an example.
I have the following Ajax-Call (Jquery).
$.ajax({
type: "GET",
url: "Search.aspx",
data: {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
},
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
// RIGHT HERE, i want to use action,userSearchString,Docbase that were passed to Search.aspx
// Prefferably i would like to use the data as a whole object and pass it too LogException
$("#FindUsersModal").modal("hide")
LogException(errStatus, thrownError, "SearchUsersByInput", params);
}
})
Would anyone care to point me in the right direction?
Thnx for your time.
why not creating the data as an object on the function level and then access it from error callback? for example:
function foo(){
var jsonData = {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
}
$.ajax({
type: "GET",
url: "Search.aspx",
data: jsonData,
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
// RIGHT HERE, i want to use action,userSearchString,Docbase that were passed to Search.aspx
var something = jsonData.action;
$("#FindUsersModal").modal("hide")
LogException(errStatus, thrownError, "SearchUsersByInput", params);
}
})
}
The idea here is simple, just store your data in a variable outside the scope of the function, and you can use it where ever you want it within the function.
Here is what you need to do
var myData = {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
}
$.ajax({
type: "GET",
url: "Search.aspx",
data: myData,
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
console.log(myData);
//You can perform any action with myData here
}
})
Related
I use Jquery to parse an json from url: the code is like this:
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
});
}
everything works fine, but if the server is not reachable I'm not able to detect it: I tried to do something in error: function, but seems that the code in error is fired only if the json has an error
have you got some ideas?
thank you!
You need to test the statusText from the jQuery textStatus response object. You can take advantage of your browser's developer console to inspect this object. You can expand the properties and methods for your perusal, however you wanna use it. Just click on the returned message of the console.log() to see these properties and methods that you wan't to use for error detection.
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(textStatus) {
console.log(textStatus);
console.log(textStatus.statusText, textStatus.status);
}
});
}
fetchdata();
Right now I have a code like this:
$.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
});
If I am not mistaken, checkAgainstDBHelperWH is known as a callback function. The function executes once the servers sends back response for this particular HTTP /ajax request.
I want to try writing something like the one below, but I don't know what are the effects or is it even logical:
var request = $.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
})
arrayOfPromises.push(request);
$.when.apply(null, arrayOfPromises).done(function () {
//...some javascript here
});
I want to understand if the .done(function () is fired after the callback function checkAgainstDBHelperWH is completed? Or whatever I am trying to write above does not flow consistently with how ajax works?
Thanks!
I tested it, your code only work if the function(in this case, 'checkAgainstDBHelperWH') doesn't call ajax.
If you want to wait finishing the inner ajax process, use then() and return inner ajax.
var ajaxs =
$.get("xxx").then(function() {
return $.get("yyy").done(function() {
});
});
Here is the jsfiddle.
I'm not sure whether this way is general or not.
I have the below javascript function that takes POST data and sends post request to server using Ajax
function postData(post_data) {
console.log(post_data, "----------->");
var data = post_data;
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
// Can we access the post_data inside this error function ?
},
}
);
};
So what my actual point is, because of some reason the server is sending a 500 response and so the execution point is coming to error: function (jqXHR, textStatus, errorThrown, data), here I want to access post_data to display something to the user.... So can we access the post_data inside ajax error function above?
In case someone looks for a generic way to do this, here is how i did it: In case your handler functions are defined where their scope don't allow you to access some variables, you can add them to the ajax object itself in the function beforeSend. You can then retreive it in the ajax object by using this.
$.ajax({
url:'/dummyUrl',
beforeSend: function(jqXHR, plainObject){
plainObject.originalUrl = 'myValue';
},
success: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
$('#myValue').html(this.originalUrl);
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">waiting result</div>
<div id="myValue"></div>
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function (jqXHR, textStatus, errorThrown, data) {
// handle error
console.log(post_data); // and the magic happens
},
}
);
};
Above this issue you were having wrong key "dataType" i have modified it. Secondly, "post_data" is in your scope you can access it without any issue.
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataType: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function ( jqXHR jqXHR, textStatus, errorThrown) {
// post data is in your scope you can easily access it
console.log(post_data); // and the magic happens
},
}
);
};
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 have an ajax call and it retunrs some value. Now i need to check the value in javascript. How can i do it
$('#cm').blur(function () {
var cmnumber = document.forms['myform']['cm'].value;
$.ajax({
type: 'get',
url: "/validatecm/" + cmnumber,
cache: false,
asyn: false,
data: cmnumber,
success: function (data) {
alert(data)
},
error: function (data) {
alert(data)
}
})
});
Now i need to access the "data" in my javascript submitformfunction. Any help wil be appreciated
success: function(data) {
console.log(data);
useInAnotherFunction(data);
}
function useInAnotherFunction(data)
{
...use here
}
If you use console.log(data); you can view clearly data what you have
You are already accessing the data here
alert(data)
If you still want to access it outside your success callback then make it like this
success: function(data) {
YourFunctionCall(data)
}