calling function containing $http.get()
$scope.storeDb = function() {
$scope.url = '/some';
$http({method: 'GET', url: $scope.url}).
success(function(data, status, headers, config) {
console.log(data);
alert(status);
}).
error(function(data, status, headers, config) {
alert('error is ' + status);
});
}
I'm calling function from ng-click
<input type="submit", value='ask', ng-click='storeDb()'/>
The alert message is error is 0
as much as i believe that jkschneider is right and it seems you do have an error and debugging it should help you find the problem, may i point 2 mistakes please :)
1st is the misuse of th $http.get, it should look like this
$http({
method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
can be also like $http.get().success().error();
see here http://docs.angularjs.org/api/ng.$http
second of all you should use the MVVM/MVC way to get/update data in your app (i.e. you need to have a model), otherwise you might get into some other problems. i wrote a short tutorial about it with full code examples http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html
Add another function to the then handler to handle the error condition, and debug into or log the output.
Related
Very strange error I'm experiencing.
I have two methods in controller which are called by angular js http get event.
First one works fine, second one is throwing CORS error, not sure how is that possible since both of them are in same controller.
This is the error I'm getting:
These are the calls I'm doing in angularjs:
$http({
url: 'http://localhost:52876/api/Admin/GetLoanInfo',
method: "GET",
params: { loanID: querystringParam }
}).success(function (data, status) {
console.log(data);
$scope.LoanDetailsVM.LoanStatus = data.LoanStatus;
}).error(function (data, status) {
console.log(data);
});
$http({
url: 'http://localhost:52876/api/Admin/GetLoanCovenants',
method: "GET",
params: { loanID: querystringParam }
}).success(function (data, status) {
console.log(data);
}).error(function (data, status) {
console.log(data);
});
And the controller methods:
[HttpGet]
[Route("api/Admin/GetLoanInfo")]
public async Task<IHttpActionResult> GetLoanInfo(int loanID)
{
LoanApplication newApplication = null;
newApplication = db.LoanApplications.FirstOrDefault(s => s.LoanId == loanID);
return Ok(newApplication);
}
[HttpGet]
[Route("api/Admin/GetLoanCovenants")]
public async Task<IHttpActionResult> GetLoanCovenants(int loanID)
{
LoanCovenant newCovenant = null;
newCovenant = db.LoanCovenants.FirstOrDefault(s => s.LoanID == loanID);
return Ok(newCovenant);
}
I'm able to hit both methods, I have breakpoints in both of the methods, but not sure why is complaining about CORS on the first one.
Calling methods using CORS from a Web browser makes Web API being called first with an OPTIONS request (example at the end of this article).
This way, the browser knows if it can call the requested API.
In your case, the call to your endpoint seems to be crashing, which means the HTTP 500 error does not contain any CORS headers.
This explains why the web browser complaning about CORS HTTP Header missing: Reason: CORS Header 'Access-Control-Allow-Origin' missing.
If you fix your method, then HTTP OPTIONS should be ok, and the CORS erros would go away.
I am building an application using AngularJS and I have a login form from which I want to send JSON data as request body.
In my controller;
$scope.credentials = {userid: $scope.userid, password: $scope.password};
$scope.login = function () {
$http({
method : 'POST',
url : 'http://localhost/login.json',
data : $scope.credentials,
headers: {'Content-Type': 'application/json'}
}).success(function (data) {
// code
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
console.log($scope.status);
});
};
But when I am submitting the form POST request is not performing and I am getting a message in the console like;
0 function (name) {
"use strict";
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}
What am I doing wrong here?
If I changed the line
headers: {'Content-Type': 'application/json'}
to
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
the POST request is making. But I don't want to send it as form values instead I want to send the request as JSON.
You should encode javascript object to corresponding mime-type data in order to post data. If you are using jQuery, try to use $.param($scope.credentials) instead of just $scope.credentials.
I think the problem is that you're POSTing to http://localhost/login.json which is not any script that is able to receive POSTrequests with form data.
I'm trying to perform AngularJS post request via $http. My code looks like this:
$http({
url: "cgi-bin/post_event.pl",
method: "POST",
data : jsonToSend,
headers : {
'Content-Type' : "application/json",
}
}).success(function(data, status, headers, config) {
if (status === 200) {
console.log(data);
} else {
console.log(data);
}
}).error(function(data, status, headers, config) {
console.log(data);
});
While looking via Firebug I see that this part of code gets executed, but none request is triggered towards server.
Only when I click it again, request hits server and success method is being called.
Anyone knows why's that? Or maybe I'm doing something wrong here...
This code with jQuery works fine:
$.ajax({
url: "cgi-bin/post_event.pl",
type: "POST",
contentType : "application/json",
data : JSON.stringify(jsonToSend),
success : function (data) {
console.log(data);
CurrentEvent.eventname = "";
CurrentEvent.starttime = "";
CurrentEvent.eventLocation.longitude = "";
CurrentEvent.eventLocation.latitude = "";
$window.location.href = "#/host/my_events";
},
error : function (data) {
// add error to $rootScope.errors
}
});
EDIT: Ah, sorry, I should be more detailed. This is called as callback after successful ajax request. Rest of the this code is just constructing jsonToSend.
So first time this part is being called I can see in firebug it constructs $http request but I can't see it triggered on server.
Next time I click on a button that does first time ajax request success method of this one is called (but id doesn't call it via callback from ajax, but it goes directly into success method)
I have decided to not use ember-data as it's not production ready and still changing. My app only needs to make a few ajax requests anyway so it shouldn't make too big of a difference. I am having trouble understanding how to handle an ajax promise response.
When my user loads the app they already have an authenticated session. I am trying to ping the server for that users info and display it in my template. It seems my template is rendered before my ajax request returns results and then does not update with the promise.
// route
App.ApplicationRoute = Ember.Route.extend({
setupController: function(){
this.set("currentUser", App.User.getCurrentUser());
}
});
// model
App.User = Ember.Object.extend({
email_address: '',
name_first: '',
name_last: '',
name_full: function() {
return this.get('name_first') + ' ' + this.get('name_last');
}.property('name_first', 'name_last')
});
App.User.reopenClass({
getCurrentUser: function() {
return $.ajax({
url: "/api/get_current_user",
type: "POST",
data: JSON.stringify({})
}).then(function(response) {
return response;
});
}
});
In my template:
<h1> Hey, {{App.currentUser.name_first}}</h1>
How would I update the template when I receive a response or delay rendering until I have a response?
Actually the answer is quite easy: You do not need to use a promise. Instead just return an empty object. Your code could look like this:
App.User.reopenClass({
getCurrentUser: function() {
var user = App.User.create({}); //create an empty object
$.ajax({
url: "/api/get_current_user",
type: "POST",
data: JSON.stringify({})
}).then(function(response) {
user.setProperties(response); //fill the object with your JSON response
});
return user;
}
});
What is happening here?
You create an empty object.
You make an asynchronous call to your API...
... and in your success callback you fill your empty object.
You return your user object.
Note: What is really happening? The flow mentioned above is not the sequence in which those actions are happening. In reality the points 1,2 and 4 are performed first. Then some time later, when the response returns from your server, 3 is executed. So the real flow of actions is: 1 -> 2 -> 4 -> 3.
So the general rule is to always return an object that enables Ember to do its logic. No values will be displayed first in your case and once your object is filled Ember will start do its magic and auto update your templates. No hard work needs to be done on your side!
Going beyond the initial question: How would one do this with an array?
Following this general rule, you would return an empty array. Here a little example, which assumes, that you might like to get all users from your backend:
App.User.reopenClass({
getAllUsers: function() {
var users = []; //create an empty array
$.ajax({
url: "/api/get_users",
}).then(function(response) {
response.forEach(function(user){
var model = App.User.create(user);
users.addObject(model); //fill your array step by step
});
});
return users;
}
});
I'd use Ember.Deferred instead of returning an empty array as mentioned before.
App.User.reopenClass({
getAllUsers: function() {
var dfd = Ember.Deferred.create();
var users = [];
$.ajax({
url: "/api/get_users",
}).then(function(response) {
response.forEach(function(user){
var model = App.User.create(user);
users.addObject(model);
});
dfd.resolve(users);
});
return dfd;
}
});
In your model hook all you have to do is this
model: function(){
return App.User.getAllUsers();
}
Ember is smart enought and knows how to handle the promise you return, once it's resolved the model will be correctly set, you can also return a jQuery promise but it will give you some weird behavior.
You can as well set the current user as the model for your ApplicationRoute like so:
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return App.User.getCurrentUser();
}
});
Since getCurrentUser() returns a promise, the transition will suspend until the promise either fulfills or rejects.
This is handy because by the time transition is finished your model is initialized and you will see it rendered in the template.
You can read up more about async routing in Ember guides.
I have a generic-http-handler and I am calling it from jQuery.
My handler only insert values in database but does not return anything.
I am calling the handler as follow
function InsertAnswerLog(url) {
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: { 'Url': url, 'LogType': "logtype" },
success: function (data) {
},
error: function (Error) {
}
});
}
Everything is working fine for me.
But is it the best way to post the values to the server.
Or can I use it in a better way.
it seems the type of data you are sending is JSON encoded try serializing the data in this form before sending and then on the server side you should encode the data before sending it back.
serializing before sending to server
function InsertAnswerLog(url) {
var DatatoSend = { 'Url': url, 'LogType': "logtype" } ;
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: {Jsondata: JSON.stringify(DatatoSend)},
success: function (data) {
},
error: function (Error) {
}
});
}
now on the sever side scipt
// NB: i use PHP not asp.net but it think it should be something like
Json.decode(Jsondata);
// do what you want to do with the data
// to send response back to page
Json.encode(Resonponse);
// then you could in php echo or equivalent in asp send out the data
It is important that you decode the json data on the server-side script and when a response is to be sent it should be encoded back it JSON form for it to be understood as a returned json data.
I hope this helps.