Ajax Post Request with Flask - ajax

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

Related

Laravel open url in server side after action

is there any way to open url in "server side".
I'm using https://www.lightsms.com/ as my sms gateway. And to send sms, you need to visit (for example) https://www.lightsms.com/send.php, so i don't want to redirect user to that url. I just want to open it in server background, and close.
after route and before real redirect, example's here:
Route::get('/sms', function() {
//i need to excecute that url here
redirect('success.html');
});
Is there any way to do this?
I think you need to do this asynchronously using xhr or ajax if you use jquery, you basically post the information asynchronously and your server (your php script) just returns a json back, in your success function / promise you can get the data and do something with it if you like, this process does not require any redirect.
This is a simple example which you may need to modify:
function asyncPost(event){
$.ajax({
url: "https://www.lightsms.com/send.php",
data: {
name: "any value or variable,"
id: "any value or variable"
},
datatype: "json",
type: "POST",
success: function(data) {
console.log("success");
// do something with data if you need, data contains the returned data from your php script
},
error: function(data) {
console.log("an error occured");
}
});
}

Flask Ajax POST data scope

I need to render a Flask template but the ajax data is only accessible within the POST if statement and does not show when I call a get direct after a posted the data.
I have a working ajax here
$.ajax({
type: 'post',
url: "/query",
dataType: 'text',
data: JSON.stringify({hostname:hostname, bf_id:computerID}),
contentType: 'application/json;charset=UTF-8',
success: function () {
window.location.href = "/query";
}
});
});
The data is successfully posted and the redirect is working. But when the redirect calls the function to render the template, the posted ajax cannot be retrieved.
#app.route('/query', methods=["GET", "POST"])
def query():
hostname=""
if request.method == "POST":
#these values only exist in if statement
hostname = request.json['hostname']
bf_id = request.json['bf_id']
return render_template('query.html', hostname=hostname)
Am I using an incorrect work flow?
Am I using an incorrect work flow?
Yes.
You make the POST request with the data.
You get a response which does things with that data
You then make a GET request without the data
You get a response which can't do things with the data that it doesn't have
The point of Ajax is to make an HTTP request without loading a whole new page.
If you want to load a whole new page, then use a regular form submission without involving JavaScript at all.

proper way to send ajax json to play framework

I've read a couple of posts here regarding how to do this and I can get it working only half-way.
This works (sending json object as text):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: '{"reqid":0,"iid":2,"description":"adsf"}',
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
This does not (sending object as json):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: {"reqid":0,"iid":2,"description":"adsf"},
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
And what I really want to do is something like this (I've already set up the proper combinators):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: #Html(Json.stringify(Json.toJson(item))),
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
My controller looks like this:
def addItem(id: Long) = Action (parse.json) { implicit request =>
Logger.info("add item")
request.body.validate(Item.itemReads).map { item =>
thing.addItem(item)
Ok("Succesfully added item.")
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}
In the second case, it never gets to the logging code. Instead it returns a 400 Bad Request immediately (this is likely something triggered in the Action (parse.json) bit I think).
I'd rather send the object as json because when I convert to string and description happens to have an apostrophe in it (') that messes things up. I could probaby escape the apostrophe, but hoping that I'm missing something simple about how to do this with an object rather than a string.
Thanks
As described in the API the dataType param is for setting:
The type of data that you're expecting back from the server.
For sending the json use your second approach (don't send it as a String). Use web browser inspector to validate if correct data were send. AFAIK you shouldn't have problem with Handling the JSON request after receiving valid JSON object
If you are trying to send a non-stringified JSON object in Jquery, $.ajax automatically tries to process it with $.param,
If your data in the ajax call looks like this:
data: {"reqid":0,"iid":2,"description":"adsf"}
This is what $.ajax is doing under the hood before sending:
$.param({"reqid":0,"iid":2,"description":"adsf"})
// "reqid=0&iid=2&description=adsf"
It takes the JSON and serializes it into a form-url-encoded format. Whereas your server is expecting JSON. I would suggest the best way to get around this is to just stringify before sending:
data: JSON.stringify({"reqid":0,"iid":2,"description":"adsf"})
Source: http://api.jquery.com/jQuery.ajax/#sending-data-to-server

Attach requestbody to jQuery ajax

I am trying to attach data to my requestbody while sendign using jQuery ajax.
If I tried to do it using the extension RESTCLient is either firefox or chrome it works fine, which means that my method on the serverside is working fine.
That is why I am pretty sure that it the ajax call I am making
$.ajax({
url: 'lingosnacks/delete/'+ id,
type: 'POST',
data: $('#email').val() + $('#password').val()
dataType: "json",
success: function(data) {
console.log("FILL| Sucess| ");
console.log("FILL| Sucess| Data| " + data);
fill(data);
}
});
The data line is wrong, it should be very similar to a JSON string, like this:
data: {email: $('#email').val(), password: $('#password').val()},
You need to have the data you are sending in this format:
email=blah%40blah.com&password=pass123
You can do that with jQuery using $('form').serialize()
Also, you are missing a , after your data string in the Ajax call.
Actually data param in jQuery Ajax method is for sending url params.
You can send the same by appending then into the url but to make the code more readable e and organized i would prefer to use data variable.
So your data content should look like :
data : "email="+$('#email').val()+"&password="+$('#password').val();
I am not pretty sure if sending params like a json object will work or not because i never used it.

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.

Resources