componentDidMount() {
$.ajax({
type: "GET",
url: "/tweets",
dataType: "json",
success: function (data){
//$('#tweetsList').append(data);
this.setState({tweetsList: data});
},
error: function (error) {
console.log(error);
}
});
}
the above block of code gives me a this.setState function not found error. I am trying to render json from my Tweets controller to my main.jsx file.
The context of this changes in the ajax call. this no longer refers to your component. You need to reference the original context.
componentDidMount() {
const self = this;
$.ajax({
type: "GET",
url: "/tweets",
dataType: "json",
success: function (data){
//$('#tweetsList').append(data);
self.setState({tweetsList: data});
},
error: function (error) {
console.log(error);
}
});
}
The problem is this in your success callback function refers to that function and therefore doesn't have any setState method. You can pass context to jQuery ajax call like this:
$.ajax({
type: "GET",
url: "/tweets",
dataType: "json",
context: this,
success: function (data){
//$('#tweetsList').append(data);
this.setState({tweetsList: data});
},
error: function (error) {
console.log(error);
}
});
See jQuery ajax docs about context property for more info.
Related
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 think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?
You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am new to AJAX and I need to find a way to return an AJAX JSON response back to the calling function. Is there any way to achieve this.
My code snippet:
function requestAjaxWebService(webServiceName, method, jsonData) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
return returnData;
}
jQuery.ajax() performs asynchronous HTTP request. Hence, you can't return its response synchronously (which your code is trying to do).
If the request succeeds, the success(data, textStatus, jqXHR) handler will get called at some point (you don't know when).
Here is one way you could modify your code:
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data, textStatus, jqXHR) {
callback(true, data); // some method that knows what to do with the data
},
error: function(jqXHR, textStatus, errorThrown){
callback(false, errorThrown);
}
});
}
callback should be a reference to a method like:
function onData(isSuccess, dataOrError)
{
if (isSuccess) {
// do something with data
} else {
console.error(dataOrError);
}
}
Update If the settings object is needed in the callback for some reason:
function onData(isSuccess, settings, jqXHR, errorThrown)
{
if (isSuccess) {
// do something with the data:
// jqXHR.responseText or jqXHR.responseXML
} else {
// do something with error data:
// errorThrown, jqXHR.status, jqXHR.statusText, jqXHR.statusCode()
}
}
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
var settings = {
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
};
settings.success = function(data, textStatus, jqXHR){
callback(true, settings, jqXHR);
};
settings.error = function(jqXHR, textStatus, errorThrown){
callback(false, settings, jqXHR, errorThrown);
};
$.ajax(settings);
}
requestAjaxWebService("name", "POST", "json", onData);
You can also use .done() and .fail() callbacks of jqxhr object instead of callbacks in settings object, as obiTheOne's answer suggests. It may look neater, but is not actually important here.
jQuery.ajax is an asynchronous function, so normally it doesn't return anything.
You can anyway return a value to the original function by setting the async option to false, but is not recommended, because a synchronous request will block the rest execution of the rest of your code until a response will be returned.
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
async: false,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
}
take a look at this example: jsbin sync ajax example
You should instead use a callback (the standard way) to handle the response
function onSuccess (data) {
console.log(data);
}
function onFail (error) {
console.log('something went wrong');
}
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: onSuccess,
error: onError
});
}
Or you can return a Promise (a sort of async object) that will change value as soon as the request will be fullfilled
function requestPromise (webServiceName, method) {
return $.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
});
}
requestPromise('...', 'GET').done(function (data) {
console.log(data);
});
refs:
jquery.ajax params
I'm trying to make global ajax handler. so first let me show you the function
var data = {
test : 1
}
$.when( $.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
})
).then(function( data, textStatus, jqXHR ) {
console.log('then me')
});
this way it works.
and outputs
first me
then me
But I want this ajax to be a function
So this is how I'm trying to make it.
var data = {
test : 1
}
$.when(globalAjax(data)).then(function( data, textStatus, jqXHR ) {
console.log('then me')
});
function globalAjax(data) {
$.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
})
}
this way console outputs then me and then first me.
How to ask to wait ajax inside a function?
You need to return a promise in globalAjax:
function globalAjax(data) {
return $.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
});
}
And you don't need to use the $.when function:
globalAjax(data).then(function(data, ...) { ... });
$.when is, mainly, to wait for the completion of two or more deferreds or promises.
function globalAjax(data) {
return $.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
});
}
you need to return a promise from your function.
$.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
}).then(function( data, textStatus, jqXHR ) {
console.log('then me')
});
You dont need when $.ajax already returns a promise.
You need to return the ajax promise from globalAjax so that it can be passed to $.when
function globalAjax(data) {
return $.ajax({
type: 'POST',
url: ajaxurl,
data: data,
dataType: "json",
success: function (data) {
console.log('first me')
}
})
}
Demo: Problem, Solution
$.when()
If a single argument is passed to jQuery.when and it is not a Deferred
or a Promise, it will be treated as a resolved Deferred and any
doneCallbacks attached will be executed immediately.
In your case since there is no return from the method, it will pass undefined to $.when which is causing the behavior
since a promise is returned there is no need to use $.when()
globalAjax(data).then(function (data, textStatus, jqXHR) {
console.log('then me')
});
Demo: Fiddle
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)
}