The below code has both success and failure handling
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
successmessage = 'Data was succesfully captured';
$("label#successmessage").text(successmessage);
},
error: function(data) {
successmessage = 'Error';
$("label#successmessage").text(successmessage);
},
});
$(":input").val('');
return false;
However we are not following the above...We are following as below
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
if(data.responseType == 'success') {
// success
}
if(data.responseType == 'failure') {
// failure
}
}
});
$(":input").val('');
return false;
Is our approach is the correct or wrong approach ??
Basically every response will be success and show error message based on the response type
Please advise. We need to follow the best practice
data. responseType doesn't return a 'success' or 'failure'. It is contains an enumerated value which represents the type of response coming back to you like text, json, arrayBuffer etc..
Hence in the second code block both if statements will be exceuted to be false and nothing will be done with the response received.
I think you should go with the first approach because
Whether you are using raw JS or a library to implement this functionality, you'll have access to the state of the request i.e. whether the request was successful; met with an error and finally whether it has been completed.
Make proper use of these events and their respective callbacks to manipulate the UI for a better user experience. For example, if the request was unsuccessful, you'd want to update the user interface to reflect that their changes weren't successful while if it was successful, you'd want to tell them so. Don't keep the user waiting!
With jQuery, you'd make use of the success and error callbacks. You also get other callbacks such as complete and beforeSend to be invoked for apporopriate use.
$.ajax({
//Other code
success: function(msg)
{
// Update the UI here to reflect that the request was successful.
doSomethingClever();
},
error: function(msg)
{
// Update the UI here to reflect that the request was unsuccessful
doSomethingMoreClever();
},
complete: function(msg)
{
// Update the UI here to reflect completion
doSomethingEvenMoreClever();
}
});
take a look at this
Related
In my ionic app I use a dataservice to get data.
On webview (ionic serve) the calls are always good. But when testing on ios device I receive null data sometimes (response from error callback).
I dont know why this is happening, it should return data. When I click again the data is received. It happens 1 out of 10 times. So what I want to do is repeat the call untill data is received but I dont know the best approach for this. Here is my code
In state resolve:
resolve: {
getNewOrders: function (OrderService) {
//get new orders
OrderService.setNewOrders();
}
}
In order service:
this.setNewOrders = function () {
$ionicLoading.show({ template: '<ion-spinner icon="ios"></ion-spinner><p style="margin: 5px 0 0 0;">Getting new orders..</p>'});
newOrders = false;
return $http({
url: api_url + "/get-new-orders",
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'}
}).then(function(response) {
if (response.data.status == 'success') {
if (response.data.returnData.length > 0) {
newOrders = response.data.returnData;
}
}
if (response.status == 'error' || response.status == 'tokenerror') {
AppService.error(response.status, response.errorMessages);
}
$ionicLoading.hide();
return response.data;
},
function(response) { // Error callback
//alert('ERROR - RELOAD DATA '+response);
console.log('ERROR - RELOAD DATA '+response);
setNewOrders(); //<<HERE I WANT TO REPEAT THIS FUNCTION IF NULL DATA IS RECEIVED
$ionicLoading.hide();
});
}
so in the error callback I want to reload the http call to get the data.
I dont know why sometimes null is returned, but when repeating the call it gets the data again. So I tought if I just repeat the call unitll data is received its ok.
But I dont know how to do this
It is not advised to make a recursive call as you might end up crashing your application. If it not getting data in 1 out 10 times, there must be something wrong, you should fix it. If you insist on using this hack, you should pass integar in params, and then in recalling the method
if(count< 5)
setNewOrders(count + 1);
If you return a promise from the error handler the result of that promise will become the result of the original promise.
What that means is that the error handler should return the result of the recursive call:
function(response) { // Error callback
//alert('ERROR - RELOAD DATA '+response);
console.log('ERROR - RELOAD DATA '+response);
return setNewOrders();
}
and if the next call is successful the response.data value will propogate back through the chain of calls.
However Haseeb is correct that you should also use a counter to limit the number of times you can recurse.
How do you catch errors/read http status code when making a rest call in one of these formats, both work to return a successful response, just no idea how to grab the info i need. I can get the object with values returned as I need, I just cant get the http status code.
methods provided by #Claies in a response to this question (Get data from $resource response in angular factory)
$scope.makeRestCall= function () {
$scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
.query().$promise.then(function(response){
});
};
$scope.makeRestCall= function () {
$scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
.query({}, function() {
})
};
I have tried to use the first method here and grab something from the function(response) such as response.status, but it returns undefined.
For reference, using this factory:
.factory("Item", function($resource) {
var endpoint = "http://some valid url";
function makeRestCallWithHeaders(id1, id2) {
return $resource(endpoint, null, {
query: {
method: 'GET',
headers: {
'id1': id1,
'id2': id2
}
}
})
}
var item = {
makeRestCallWithHeaders: makeRestCallWithHeaders
}
return item ;
})
Item returns something like this:
{firstName:Joe, lastName:smith}
I am really just trying to figure out how I can access the status code returned by the REST call. Absolute end goal is to read any error response and return error to UI written in angular as well. If there is a way to just read this in the UI, that could work too.
To read the error status you need to pass in the errorCallback to the $promise:
$scope.makeRestCall= function () {
$scope.member = Item.makeRestCallWithHeaders('123456789', '789456123')
.query().$promise.then(
function(response){
//this is the successCallback
//response.status & response.statusText do not exist here by default
//because you don't really need them - the call succeeded
//see rest of answer below if you really need to do this
// but be sure you really do...
},
function(repsonse) {
//this is the errorCallback
//response.status === code
//response.statusText === status text!
//so to get the status code you could do this:
var statusCode = response.status;
}
);
};
You shouldn't need the status in the successCallback, because it is a success and you know the success code implicitly.
Therefore the status is not available in the successCallback by default.
If, for some reason, you do need the status in your successCallback, you could write an interceptor to put this information somewhere, but be aware that the angular framework deals with the data differently in different success scenarios so you will need to write code for different cases.
I am using ng-resource to do ajax request. I want to send extra info besides the data.
For example, I have an article entity on my server
exports.fetchArticle = function(req, res, next) {
var article = req.article
return res.json({data: article, message: 'success fetch article'})
}
The reason I wrap it is that, in the case of deletion, it makes no sense to send data, I can just return res.json({data: null, message: 'deleted successfully'})
on my client side, I have:
$scope.fetchArticle = function() {
Article.get({articleId: $routeParams.articleId}, function(response) {
$scope.article = response.data
$scope.ajaxSuccess = response.message
}, function(err) {
$scope.ajaxError = err.data.message
})
}
$scope.article is not an instance of ng-resource anymore, thus I can't do further request with $scope.article, i.e. this will cause error, since $scope.article is a plain json object:
$scope.article.$update(function(response) {...})
If I simply return res.json(article) from server, it works, but I can't send along the message.
The reason I dont generate the message from client but fetch from server is that, the error message is from server, I want to keep success message consistent with the error message.
Is there any other elegant way to send the message?
Assuming that all your servers responses follow this format:
{
data: {/*...*/},
message: 'some message'
}
You could use $http's transformResponse for that, so that you get an ngResource instance that is your returned object while still processing your message. For that, you need a transform-function:
function processMessage(data, message) {
//Do whatever you want with your message here, like displaying it
}
function transform(response) {
processMessage(response.data,response.message);
var data = response.data;
delete response.data;
delete response.message;
for(var attributeName in data) {
response[attributeName] = data[attributeName];
}
return response;
}
Then you can add this function to $http's default transfroms in the config of your app:
angular.module("yourApp",[/* ... */])
.config(function($httpProvider){
//....all your other config
$httpProvider.defaults.transformResponse.unshift(transform);
});
Now all repsonses from $http get transformed by this function, triggering processMessage and leaving you with a ngResource instance of the returned object.
In my application i have used the Ext.Viewport.setMasked function, When i call the Processing mask showing properly.But not disabled when it reaches success.Here my code
{
Ext.Viewport.setMasked({
xtype: 'loadmask',
message: 'Processing...',
indicator: true
});
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url: App.gvars.apiurl + 'AddItem', // url : this.getUrl(),
method: "POST",
params: data,
useDefaultXhrHeader: false,
withCredentials: true,
success: function (response) {
var respObj = Ext.JSON.decode(response.responseText);
if(respObj[0].response=="Success"){
Ext.Viewport.setMasked(false);
Ext.Msg.alert("Success", "A new wish has been added To Ur Wish List");
viewgiftlist();
goitems();
}
else{
Ext.Viewport.setMasked(false);
Ext.Msg.alert("Error",respObj[0].errorMsg);
}
},
failure: function (response)
{
Ext.Msg.alert("Error",response.responseText);
}});
}
Please help me to solve the issue
You didnt give setmask(false) in your failure message.. are you getting success response or failure?
The correct usage is in fact Ext.Viewport.setMasked(false);
My guess is that your success conditional isn't working properly. This should be an easy fix for you if you're using console! Fire up Chrome, hit F12 and use your console. Use a console.log after you decode your response, then you can properly debug this.
var respObj = Ext.JSON.decode(response.responseText);
console.log(respObj);
Also, not sure why the success portion of your response would be an array, usually a response looks something like this:
{"success":true,"data":[{"id":"1","first_name":"Test","last_name":"Test"}],"total":1}
Obviously you can craft them how you want, but just looks strange to me. With the above JSON the conditional would be like so:
if(respObj.success) {
I have a store with a proxy configured to update my database.
proxy: {
type: "ajax",
api: {
create: MySite.app.BaseURL + 'Member.php?action=create',
read: MySite.app.BaseURL + 'Member.php',
update: MySite.app.BaseURL + 'Member.php?action=update',
destroy: MySite.app.BaseURL + 'Member.php?action=delete'
},
This all works fine but what I would really like is to be able to read the response so to report to the user success or failure of an update.
For example when an update is successful the json below is returned in the response,
{"success":true,"message":"Updated"}
And if not successful then the following is returned,
{"success":false,"message":"something terrible happened"}
I've tried adding a listener to the store as below but this doesn't seem to pick up the response.
listeners: {
success: function(response) {
console.log(response);
var data = Ext.JSON.decode(response.responseText.trim());
console.log(data);
if(data.success == 'true') {
console.log('success');
}
}
},
Could anyone help?
Stores don't fire a success event. That has to be configure in each operation using the success, failure or callback functions.
For example, when you perform a sync, you could do something like this:
myStore.sync({
success: function(batch, options) {
console.log(response);
}
});
Given stores work with bacths, to have to see the batch fields in order to know if it was okay or not.
The store will fire a 'write' event when successful. The proxy will fire an 'exception' event if there is a failure. This 'exception' event should bubble up to its parent (the store) so your listeners in the store should be for 'write' and 'exception'. You can look up the parameters to these events. For the 'write' event, the parameters should be the store itself, and the operation. The operation should have all the info you need to do the logging or whatever you want.