AngularJS http POST with $scope - ajax

I am trying to do a http post using AngularJS but angular is not converting my $scope variable to JSON.
Here is my code:
$http({
method: "POST",
url: "/Account/Login",
data: $scope
})
Which results in the request POST message having
"$SCOPE"
but if I change it to output any of my scope properties, it is sending the message with correct properties, e.g.:
$http({
method: "POST",
url: "/Account/Login",
data: { email: $scope.email, password: $scope.password }
})
Which results in the request POST message having
{"email":"asdasd#Asdasd.asd","password":"asd"}
Do I always have to wrap my requests like this? Or is there a way to tell AngularJS to send all properties on scope? Any Pro's / Con's?

Sending the $scope is not a good idea, It contains lot more than your email and password
You should create a property like $scope.user and then attach the model to it like $scope.user.email. Now you can send it using $scope.user
$http({
method: "POST",
url: "/Account/Login",
data: $scope.user
})
a lil about $scope
scope is an "object" that "binds" to DOM element where you apply controller. All child elements can read and modify scope data (unless you modify primitives in new scopes or they're isolated
for more official doc is they way

Related

Ajax Post Request with Flask

I am using AJAX to send a POST request to a Flask route, but I don't know how to get the post data in a format I can read.
My route looks like this:
#app.route("/sendinvites", methods=["POST"])
#login_required
def sendinvites():
print(request.get_data("emails"))
return jsonify("done")
My AJAX looks as:
$.ajax({
type: "POST",
dataType: "json",
url: "/sendinvites",
data: { emails : emails, usernames: usernames },
success: function(data) {
console.log(data)
}
});
An example of the data sent in the emails variable is:
0: Object { id: undefined, username: "me#mydomain.com" }
An example of the output from the route is:
b'emails%5B0%5D%5Busername%5D=me%40mydomain.com'
Does anyone know how I can get the post data into a dictionary object so it is easier to process?
There are many ways to do this, but first, verify that the request contains a valid JSON.
request.get_json()
request.get_json(silent=True)
With silent=True set, the get_json function will fail silently when trying to retrieve the JSON body. By default, this is set to False.
jsonify(request.json)
This will return the entire request object. You'll have to extract the required part by specifying the key posted while sending the request in your ajax code.
Refer this for Flask part, thread
Refer this for Ajax part, thread

Antiforgery token and object parameter do not post to MVC4 Controller action accordingly

I have a controller action which has a class as a parameter.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(vm.Quotation quotationheaders)
{...
and calls it using
var token = $('input[name="__RequestVerificationToken"]').val();
quotationheader.__RequestVerificationToken = token;
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '/someapp/quotation/create/',
data: quotation,
async: true,
success: function (response1) {
alert(response1);
},
error: function (error) {
ThrowException(error);
}
});
the data object contains members which also have nested array of details (qutoation header and product details). Using the code above I do not have problem with ANTIFORGERY filter. it seems the controller action reconizes it. However, the product detail properties of the quotaion (nested array of object) are all null. It wasn't able to Bind to the model although the header properties were passed accordingly.
So I did some modification and changed the data and stringify it.
data: JSON.stringify(quotation),
This time, the controller action cannot recognize the verification token. So I tried to remove the AntiForgery and saw that the details were bound accordingly.
As summary:
ajax data stringify: binding is ok but verification token is not recognized.
ajax data object: the verification token is verified and but the object detail collection properties are null.
Can any body suggest a rightful way to do this?
Thanks!

How to specify dataType: 'json' in Angular.js $http.post?

I would like to specify dataType: 'json' as in conventional jQuery $.ajax.
Is this possible with Angular.js $http.post ?
You can use the HTTP Config object to set the headers:
$http({
method: 'POST',
url: 'somewhere.xyz',
headers: {
'Content-type': 'application/json'
}
})
From http://docs.angularjs.org/api/ng.$http
Transforming Requests and Responses
Both requests and responses can be transformed using transform functions. By default, Angular applies these transformations:
Request transformations:
if the data property of the request config object contains an object, serialize it into JSON format.
Response transformations:
if XSRF prefix is detected, strip it (see Security Considerations section below)
if json response is detected, deserialize it using a JSON parser
So no need to set a data type it is done automatically
I had the same problem, responseType:'json' solved the issue
You can use responseType:'json' instead of dataType:'json'
var promise = $http({
method: 'POST',
url: 'somewhere.xyz',
responseType:'json'
});
For further reference
https://docs.angularjs.org/api/ng/service/$http#methods_jsonp

sending data from angularjs to django

I am sending a POST AJAX request using Angularjs and its $http module to Django server. Here is an example:
$http({
method: 'POST',
url: '/url/',
data: 'test data'
}).
success(function(data, status, headers, config) {
doSomeStuffWhenSuccess();
});
The problem is what I get in Django. No matter what I send the data is always the key of QueryDict object and value of that is always an empty list.
<QueryDict: {u'test data': [u'']}>
I don't have a clue why. What am I missing?
I use almost default created Django application with default middlewares only. I created only a view and set an url in url config. Version of Django is 1.3. And I configured angular's $http module to always send a header containg csrf token to satisfy Django.
I resolved this with jQuery param function. I think it's more elegant solution.
$http({
method: 'POST',
url: '/url/',
data: $.param({test: data})
})
Now it works like I wanted.
I believe django thinks you are sending a urlencoded form, ex. key=value&key2=value2...
if you'd try:
$http({
method: 'POST',
url: '/url/',
data: 'test=data'
})
You should get
<QueryDict: {u'test': [u'data']}>
You can always obtain the data (raw body content) as follows:
request.body
Hope this is what you are looking for.

How use Facebook Javascript SDK response in Ajax request?

Supposing I have the following code which returns a Javascript object which I can read in Firebug's console:
FB.api('/me',function(apiresponse){
console.log(apiresponse);
});
How can I then use the data from apiresponse in an Ajax request on the same page?
Currently my Ajax request looks as follows:
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
I know very little about Javascript, but reading around the subject leads me to think I have to convert the Javascript object to a JSON string. Is that correct? Am I on the right track?
You could put your AJAX call inside the handler for the API call like below..
FB.api('/me', function(apiresponse){
console.log(apiresponse);
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
});
one possible way:
define a global variable in your javascript, e.g. var myVar1;
set apireponse to the global variable in your FB.api callback (i.e. where u call console.log)
reference the var myVar1 in your ajax fcn.

Resources