hey guys I know this issue posted a lot, but nothing doesn't help me that is why I asking this question.Question is I am facing an issue of sending a synchronous request to php. here is my Model function which is sending request.
State.pushData = function () {
$http({
method: 'POST',
url: 'pushData.php?action=pushdata',
data: {'status': 'push', 'email' : State.campemail},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response){
if(response.error){
console.log(response.error);
return;
}
State.getCartData();
State.selectedItems = [],
});
}
this pushData function send a post request to defined url. and fetch a response. the code written is suppose to execute "State.getCartData()" function on success of request sent initially. But this is not working in this way. both request executes at once. I had tried $http with .post and then methods but same results. like this
State.pushData = function () {
$http.post('pushData.php?action=pushdata',
{'status': 'push', 'email' : State.campemail}
).then(function(response){
if(response.error){
console.log(response.error);
return;
}
State.getCartData();
State.selectedItems = [],
});
}
I want to send request asynchronously, that once pushQuote request completes after that getCartData() function will execute. please share your experience on this. thanks in advance.
got an answer to my question after some brainstorming. I return $http in my model and call .then() on returned response. it worked as I want to send request once first is completed successfully. Here is my model function
State.pushData = function () {
return $http.post('pushData.php?action=pushdata',
{'status': 'push', 'email' : State.campemail}
);
}
in above function I just send post request to server and return its response to controller function. which executes right after returning from model. here is my controller function.
scope.pushIt = function() {
var responseObj = State.pushData();
responseObj.then(
function() { //successs call back
/*Business logic*/
State.getCartData();
State.selectedItems = []
},
function() { //Error call back
/*Business logic*/
}
);
}
Beauty of this approach is you can use then method as many as you want. they will all execute one by one in chain.
scope.pushIt = function() {
var responseObj = State.pushData();
responseObj.then(
function() { //successs call back
/*Business logic*/
},
function() { //Error call back
/*Business logic*/
}
).then(
function() { //successs call back
/*Business logic*/
},
function() { //Error call back
/*Business logic*/
}
);
}