Synchronous in angular controller - angularjs

In the following code, the controller is not invoking the third $http.get() call and instead goes directly goes to the end.
I want to execute all $http.get() requests. In my code, the third $http.get() depends on the second $http.get() result. Additionally, the second $http.get() depends on the first $http.get() result.
Code
Does anyone have an idea why the third $http.get() is not being invoked?

with the way you structured your code, this code below will run before the third $http.get
orderDetails['orderData'] = data;
orderDetails['kitNames'] = kitNames;
orderDetails['proteins'] = proteins;
orderDetails['dietaries'] = dietaries;
orderDetails['ingredients'] = ingredients;
you would have to put it in the third $http.get and every other code that depends on it, and that should solve your challenge
Also, your code can be refactored, so it is more readable and understandable for you to read

Suggestion:-
Actually this is a big issue with angular http call, Because http call does not support async :false
See my answer in this discussion : Angularjs $http VS jquery $.ajax
Your code look like a lot of confusions for call new http method inside of inside methods.
And your code looks like not standard format also gives lot of confusion.
So if you change any code in this file after some day's, then you need to put a microscope glass in your eye, and will see one by one lines. it's will take more times. So avoid http call only for this type of situation.
Solution:-
Avoid http call means, pleas do with Ajax call with async:false option
The code look like
$.ajax({
type: "GET",
dataType: "Json",
url: 'Your URL',
**async: false,**
success: function (returndata, status, jqxhr) {
$(this).html(returndata).hide().fadeIn();
}).fail(function() {
alert("error");
})
});
Explanation About Async:false
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

Related

AngularJs $http get not working 1st time but does on subsequent invocations

All:
I have an Iframe tag on a simple HTML page and inside this Iframe tag is a HTML form - lets call it a widget. Its a form where the user can enter search criteria and click on a button to obtain the search results. I have decided to use Angularjs to make the necessary DB calls to a REST service that returns the search results back to the widget for display.
In testing this I enter a value in a textbox on the widget, that value being a value that I know exists in a particular table I'm testing against.
Here is my $http get call:
$http
.get('http://localhost/XXXXService/folder/getfolders/' +
$scope.formData.srchterm **==>** mapped to search textbox
).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
//$scope.formData = response;
//$scope.nrdFolderDataArray = response;
console.log('Success retrieving data.');
console.log(response.length);
console.log('response:');
console.log(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('Error occurred retrieving data.');
console.log(response.status);
console.log('returned data count:');
console.log(response.size);
console.log('response:');
console.log(response);
});
This call is inside a function called "submitForm" that is mapped to the widget with a "ng-submit="submitForm()" attribute on the submit button. And yes there are several log statements so I can try and figure out what is going on here. And what is happening is this: after entering a value in the textbox, THE FIRST TIME the search button is clicked the .get command does not work. I does not make the call to the REST service. I know this because I wrote the REST service and made sure I put in plenty of log statements while doing so and there are no log statements in the log file from the REST service. Instead the errorCallback block runs and I see all those log statements in the console. The "response" (object?) after THE FIRST call looks like this:
Object {data: null, status: 0, config: Object, statusText: ""} Method = GET Status = (canceled) type xhr
Further, in FF there is no response data to view in the Net tab of Firebug upon THE FIRST call, but there is response data to view in all subsequent calls.
So, interestingly enough each subsequent invocation of that $http.get call works! I see log statements in the log file from the REST service method and the successCallback block runs and I can see my data via those console.log messages.
Also, if I were to change the search value in the text box, which would then be THE FIRST TIME we would be searching for data for that new key, once again, the call does not work, but does work on subsequent clicks on the "search" button for that new key value.
I really am not sure if I have a CORS issue here since, other than THE FIRST calls each subsequent $http.get call works like a champ. Its just that very first call or first call after the search key has changed that the $http.get does not want to work.
I have tried setting headers in the .get call and I have tried using
#CrossOrigin(origins = "http://localhost/7001") as per
https://spring.io/guides/gs/rest-service-cors/ but I continue to have this issue on the first time invoking this .get call.
I've been dealing with this issue for way too many hours now and would sure appreciate some input as to why this is happening.
I'm sorry for being verbose here. I wanted to explain my issue thoroughly.
Please help.
Thank you
-g

cannot access $scope variable out side a function

I have a variable defined in a controller:
app.controller('myController',['$scope','ajaxCall',function($scope,ajaxCall){
$scope.interviewer = {};
ajaxCall.get(/* A url */).then(function(response){
$scope.interviewer = response.data;
console.log($scope.interviewer);
});
console.log($scope.interviewer);
ajaxCall is a custom service which is used to make ajax calls. Inner console is working fine(i.e. it is showing the complete data) but the outer console is printing an empty object.Why?
Because the first A in AJAX means "Asynchronous".
The function passed to then() is executed asynchronously, a long time after the last console.log() line. It's executed once the response to the asynchronous HTTP request comes back from the server.
If it was synchronous, we wouldn't bother with promises and callback functions. We would just do
var response = ajaxCall.get(url);
But that isn't possible, so we do
ajaxCall.get(/* A url */).then(function(response){
which means: please send this request, and when the response is available, then call this function. I'll do plenty of other things in the meantime.

AngularJS $http.Post -> open the urllink + $http.get getting it

im still new with Angular and am trying to grasp the concept.
Currently I cant post code, but this is hopefully not a problem.
I have used https://docs.angularjs.org/api/ng/service/$http ... especially $http.post in order to Post some data I clicked in the current window
The following Code didnt work due to the error "$http function is not defined", even though $http was already declared... in the correct order I might add (I found other ppl who had issues with that due to the fact that they switched the parameters $scope, $http)
Thats my first Question is there a simple reason? I can add code tomorrow if necessary.
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Second Question: Well, but $http.post(..) with parameter url to the second site worked fine.. and in order to use the data i most likely need to use $http.get() at the second site... which I understand.
But how do I need to configure the $http.post that I actually open the url in my browser?
Well I hope you can help me ... sry that I currently can't give you my codeexamples, but I hope it's enough :)

AngularJS $http success but not working

i'm using angularJS and SLIM PHP restful server, the PHP service is working and actually i have already used $http.get() with no problems in this application ...
But now a strange thing is happening, i created a new function in the same way that the others, and it get .success(function(data)) with no problems, i actually can console.log(data) and it shows the right results, but when .success() finish and return, i recieve a undefined result.
ps: there is no error in browser console.
var markerOptions = [];
loadMarkers();
console.log(markerOptions);
function loadMarkers() {
$http.get('http://localhost/rest/getMarkers').success(function(response){
console.log(response);
markerOptions = response;
});
}
Console.log() inside success() return the right data
Console.log() after loadMarkers() return undefined
#MarcKline's comments are correct. Anyways, following what I think you're trying to achive by this piece of code of yours, you can assign the returned data from the ajax response to a scope variable (assuming you're using $scope), e.g $scope.markerOptions = response. You can declare markOptions as a scope variable by var $scope.markOptions = [] (...and, of course, log it by console.log($scope.markOptions) accordingly). Also, define $scope.loadMarkers = function() {...} and call it by $scope.loadMarkers()
The scope will be updated as soon as the client-side gets its ajax response.
Hope it helps your current needs in addition to a better understanding of javasciprt's async approach that some of its principles were explained to you by the comments.

jQuery Promises and Backbone

I found this snippet of code that does what I want it to:
var promise = this.model.save();
$.when(promise).then(function() {
console.log(promise.responseText);
});
I want to get back the responseText from my Backbone call to this.model.save(). This code was documented here. But it's not logging anything, even if I pull a raw text string in the console.log() call.
Could someone please explain in layman's terms what a jQuery promise is? I've read about them, but I don't think I quite got what they were. That might help me understand why this code isn't working for me. If I console.log(promise) in between the first and second lines of code, then I get the responseText. So something is happening in either the $.when or the then that is causing this to go wrong.
EDIT:
After reading the article, I discovered I could do this:
var promise = this.model.save();
$.when(promise).then(null, function(obj) {
console.log(obj.responseText);
});
But I don't understand what the null represents. then seems to take two parameters, a success function and a failure function. But wouldn't the success function be first? I get a 200 response from the server.
So first off, I'm pretty sure you don't need the when part; from the jQuery docs:
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the
Promise interface, giving them all the properties, methods, and
behavior of a Promise (see Deferred object for more information).
Since Promise has a then method already, you can just do:
this.model.save().then(null, function(obj) {
console.log(obj.responseText);
});
(The fact that the above code almost reads like an English sentence is a major advantage of using Deferreds, for me at least.)
As for your null argument, the docs are again pretty clear. There are three signatures for then (and that's just to cover the different jQuery versions; any given version has less):
deferred.then( doneFilter [, failFilter ] [, progressFilter ] )
deferred.then( doneCallbacks, failCallbacks )
deferred.then( doneCallbacks, failCallbacks [, progressCallbacks ] )
As you can see, all three take the "done" function first, and the failure function second. This does seem to imply that you're getting a failure, which is confusing. One way to avoid the problem is to not use then at all. Instead, try the following:
this.model.save().always(function(obj) {
console.log(obj.responseText);
});
That will make your function get called no matter what happens. However, you probably should figure out what's going on, so you might want to instead add a success and failure callback to do some debugging:
this.model.save().done(function() {
// Success case
}).fail(function() {
// Failure case
});
Because this.model.save returns a promise, you can do the following instead:
this.model.save()
.done(function(response) {
console.log("Success!");
})
.fail(function(response) {
console.log("Error!");
});
(That's easier than the whole $.when bit.)
My guess is that although your response is returning a 200 code, it is still "failing" because the response data type doesn't match up with what you're expecting (what's set in the dataType attribute in the $.ajax call).
I am a big fan of using promise, and I think the promise means very similar things in different packages.
To answer your question, which previous answers didn't, the "then" function is a function of a promise, the "when" function is a fail-save, incase the object is not a promise, a "when(obj)" will make sure it is a promise, so that you can use the elegant xxx.then(success(){},error(){}).
btw, the "deferred" that machineghost said is the package that let you use promise.
For starting to know promise and how to use it. check out this tutorial. It explains every thing very clearly, it is the article that made me so into promises.
http://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/
Now, as machineghost said, it seems your sync call is getting an error, according to a REST API documentation,https://parse.com/docs/rest# (don't know if it is the same as backbone), the server will response a JSON object for a "create" request in this format:
{"createdAt": "2011-08-20T02:06:57.931Z","objectId": "Ed1nuqPvcm"}
My guess is, maybe your server did not respond the request with the correct JSON, so the save() think the operation failed because there was no "createAt" field, event thought your sever did created the item.

Resources