Suppose you have an array in javascript - [1,2,3] and you want to send it via AJAX post to Flask.
So that in JS:
array = new Array()
array.push(1);
array.push(2);
array.push(3);
var data = JSON.stringify(array);
$.ajax({
type: "POST",
url: "myurl",
data: data,
dataType: 'JSON',
success: alert("messagesent!")
})
And in Flask view :
#bp.route('myurl',methods=['GET', 'POST'])
def myfunction(address):
if request.method == "POST":
FirstSet = request.form['data']
x = json.loads(FirstSet)
However now I dont know how to access the particular values of x list(?), because trying to access it like this :
print(x[1])
does not work...Thanks in advance for looking at it :)
EDIT:
The bigger picture:
I trigger ajax request onclick but after I append all the values that I want to to the array that i want to send. It looks like this:
$("#firstSet").on("click",function(){
array =[]
$("#myDiv").children().each(function()
{
var star = $(this).children("li.star.selected").length
array.push(star)
})
alert(array)
$.ajax({
type: "POST",
url: "myurl",
data: {"data":array},
success: alert("messagesent!")
})
})
This alerted array is not NoneType (and I just get my array values) but what I receive in Flask side is an empty list or NoneType (depenending on how i request it)
Since you're sending JSON you should use Flask to get that JSON with the appropriately named .get_json():
# ...
FirstSet = request.get_json()
Then FirstSet will contain:
[1, 2, 3]
Also ensure your AJAX has the appropriate contentType:
// ...
contentType: "application/json",
dataType: "JSON"
Edit: I'm including all the Javascript/JQuery that I'm testing with in case it helps you. I wrapped everything in a DOM ready function.
<script>
$(document).ready(function() {
$("#firstSet").on("click",function(){
array = [];
var listItems = $("#myDiv li");
listItems.each(function(idx, li) {
var star = $(li);
array.push(star.length);
});
alert(array);
$.ajax({
type: "POST",
url: "/testing",
contentType: "application/json",
dataType: "JSON",
data: JSON.stringify(array)
});
});
});
</script>
And the HTML:
<button id="firstSet" name="firstSet">testing</button>
<div id="myDiv" name="myDiv">
<ul id="myList">
<li data-value="1">1</li>
<li data-value="2">2</li>
<li data-value="3">3</li>
</ul>
<input id="listChoice" size="15" name="size" type="text" />
</div>
And the Flask code:
#bp.route('/testing',methods=["GET","POST",])
def testing():
if request.method == "POST":
print(request.get_json())
return render_template('testing.txt')
Related
I have to submit user form data. I have done this by using ajaxSubmit but its add one more new JS file into my application. I want to get this done by using angularjs http service. My question is that by using ajaxSubmit I need to send userId id request body and the form data is handle by the ajaxSubmit method itselft. I just want to send the data in a way that ajaxSubmit is doing.
HTML
<form role="form" action="profile_pic">
<div class="cover-50 pull-left pos-relative upload-photo">
<input type="file" onchange="angular.element(this).scope().uploadProfilePic(this)" accept="images/*" capture>
<label>Upload Media</label>
</div>
</form>
Controller
$scope.uploadProfilePic = function(){
$http({
'method': 'POST',
'url': /upload/user/image,
'data': {
'userId' : 457
},
});
// $form.ajaxSubmit({
// type : 'POST',
// url : '/upload/user/image',
// data : {
// 'userId' : 457
// }
// });
}
You could use FormData() to append additional properties to send through $http post.
var data = new FormData();
data.append('userId', 457);
data.append('file', uploadFileUrl);
data.append('abc', "XYZ");
return $http.post('/upload/user/image', data, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).then(function (results) {
//results.data
});
need to define the name as ID in the URL and need to post an object containing data.
$scope.dvModel.naam is the name that acts as the ID.
filteredObject is the object containing the data, obviously.
This is how I call the service, seems ok according to some examples.
saveDVservice.query($scope.dvModel.naam, filteredObject);
This is the actual service.
.factory('saveDVservice', ['$resource', 'CONSTANTS', function($resource, CONSTANTS) {
'use strict';
return $resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
}]);
This is what I see in my network tab at Query String Parameters:
0:A
1:D
10:n
11:h
12:i
13:l
14:f
15:e
2:A
3:C
4:
5:P
6:a
7:n
8:n
9:e
Which is the name, but looks like an array.
Request Payload contains the actual object in correct order.
Can one give me some guidance on how to handle this?
As I understand, you want to put $scope.dvModel.naam into URL and you want filteredObject to be a request payload. Then you need an object that contains everything that's in filteredObject and additionaly under the key name a value equal to $scope.dvModel.naam.
Also, the definition of your resource probably should change - in second argument $resource requires you to tell it the way of extracting URL data from given object:
$resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {name: '#name'}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
Unfortunately, $resource isn't the best $http wrapper to use when your payload data is separated from URL data. Maybe it would be better to wrap the filteredObject data in payload in some other object? Then your $resource object would be much nicer, like {name: ..., data: {"0": "A", "1": "D", ...}}
Since default action for query is {method: 'GET', isArray: true}, I'd leave that be and use another default, save instead. That should work out-of-the-box.
app.factory('DVService', function ($resource) {
return $resource(CONSTANTS.REST_BASE_URL + '/dv', {name: '#name'}, {});
});
.
app.controller('MainCtrl', function ($scope, DVService) {
var postData = {
name: 'name',
fooProp: 'foo',
barProp: 'bar'
};
// save/post
DVservice.save({dv: postData}).$promise.then(function (response) {
console.log(response);
});
//query/get
DVService.query({name: 'name'}).$promise.then(function (response) {
console.log(response);
});
});
In Pyramid:
class ProjectorViews(Layouts):
def __init__(self, request):
self.request = request
#view_config(renderer="json", name="updates.json", request_method="POST")
def updates_view(self):
print self.request.params
JS:
$(function() {
function get_updates () {
data = JSON.stringify({'a':1});
$.post('/updates.json', data, function(res) {
});
}, 'json').done(function() {
});
}
get_updates();
});
The console shows self.request.params returns NestedMultiDict([('{"a":1}', u'')])
How do I get the keys and values in the NestedMultiDict object?
If I do self.request.params.getall("a"), it reports
KeyError: "Key not found: 'a'"
And if I do self.request.json_body, it reports
ValueError: No JSON object could be decoded
$.post() always sends data with application/x-www-form-urlencoded content type. Use $.ajax() to send the data with correct content type:
$.ajax({
url: url,
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(...);
On the Pyramid side request.json_body is the correct way to access... well, JSON body of the request.
I'm trying to save data which comes from an AJAX POST request in JSON but
There is empty $this->request->data in controller.
My AJAX call:
$.ajax({
type: "POST",
url: 'localhost/pages/register',
dataType: 'json',
data: pass_data,
});
JSON data:
var email = $("#email").val();
var verifyemail = $("#verifyemail").val();
var password = $("#password").val();
var confirm_password = $("#vPassword").val();
var pass_data = {
'data[User][email]':email,
'data[User][verifyemail]':verifyemail,
'data[User][password]':password,
'data[User][confirm_password]':confirm_password,
}
I'm use CakePHP 2.3. and jQuery 1.7.
Do you have any ideas?
I am having some trouble fetching a collection. I'm using the console's network inspector to see if I can figure out what's wrong and the only thing I see is the format of the Request Payload.
When making a .fetch() the Request Payload is being sent in this format:
query=this+is+my+query
This returns a 400 Bad Request status from my server. I have tested using:
$.ajax({
contentType: 'application/json',
async : false,
type:'POST',
url: '/search',
data: JSON.stringify({"query":"this is my query"}),
dataType: 'json',
success: function(data) {
alert('yup');
},
error: function(data) {
alert('nope');
}});
which returns my data as expected. In this case the Request Payload is in this format:
{"query":"enterprise search is gonna rock","scope":null}
I've tried passing in headers with my fetch:
my_results.fetch({data:{"query":"this is my query"}, type: 'POST', dataType: 'json', contentType: 'application/json'});
Here is what my Model and Collection look like:
EnterpriseSearch.Result = Backbone.Model.extend();
EnterpriseSearch.Results = Backbone.Collection.extend({
model: EnterpriseSearch.Result,
url: "/search"
});
Any help would be appreciated.
Try using data: JSON.stringify({"query":"this is my query"}) in your fetch options, just like you do when using $.ajax. jQuery will default to application/x-www-form-urlencoded for form data.