Flask Ajax POST data scope - ajax

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.

Related

My question is related ajax request. I am new to ajax . So i want to know taht how to pass data in ajax dynamically?

Below code is of my ajax request where i pass return_id in data which is not dynamic. So how can i pass return id dynamically?
$ ->
$('#manualShipment').click ->
$.ajax
type: 'POST'
datatype: 'json'
data:
return_id: 274588
url: '/returns/create_shipment_manually'
success: (data) ->
$('#manualShipment').disabled = true;
$('.tracking_detail').show()
I tried to take id from view of rails but it won't work. So what would be correct way to pass data dynamically in ajax post request

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

Rails allow POST for Ajax on index action without breaking CREATE

I have a simple setup for a resource, currently in routes.rb I have:
resources :leave_requests
This works exactly as expected, on the index view I have a datatable setup using Ajax via a GET, this is also working but the URI is getting very large during the Ajax request. I would prefer this to be a POST action, for this to work I require a POST instead of a GET on the index action in my routes.
However, this will break the CREATE action i.e. will simply load the index page on submitting a new request. i.e. If I do this:
post '/leave_requests', to: 'leave_requests#index'
resources :leave_requests
How can I get these to co-exist happily?
Have you try to do something like in this Rails , Ajax , Post Function , Jquery the code looks something like
$('form').submit(function()
{
var myForm = $('form').serialize();
$.ajax
({
url:'/leave_request/create',
type:"POST",
dataType:'json',
data: myForm,
processData:false,
success: function (msg)
{
alert(msg);
},
error: function (xhr, status)
{
alert(xhr.error);
}
});
});
you can also take a look at jQuery post to Rails

Pass Codeigniter CSRF string to server via AJAX

I have enabled Codeigniter's CSRF protection on my site that uses AJAX to submit a user form and handles some other user interaction which require data submission via AJAX. As a result I came up against the "action not allowed" server side error. I quickly worked out that only the data my javascript collected and submitted via AJAX was passed to the server and as a result the CSRF code was not being sent.
The generated token tag looks like:
<input type="hidden" name="csrf_test_name" value="dsflkabsdf888ads888XXXXXX" />
So it seems to me the simplest way to submit the token to the server for verification is using a jQuery selector on csrf_test_name to get the value and then adding this to my post data for the server to verify. As per the code below:
//get CSRF token
var csrf = $('[name="csrf_test_name"]').val();
//build the form data array
var form_data = {
csrf_test_name: csrf,
... ... ...
... ... ...
}
//send the form data to the server so it can be stored
$.ajax({
type: "POST",
data: form_data,
url: ...,
dataType: "html",
success: function(msg){
... ... ...
}//end success
});//end ajax
I have followed this procedure for every ajax submission that sends data to the server and the server side error is fixed and everything works fine.
To test this I have hard coded in an incorrect CSRF token and the server detects the inconsistency and returns an erro code 500 so on the surface this works.
My question is this, is this a safe way to do this and is there an expected best practice to follow? I have done some google searching on this and it seems all the other methods are more complex and I am wondering if my way creates an attack vector that I can't see/workout.
I like to add it to the Ajax setup. Set it once and have it automatically add it to the post data for all of your requests.
$.ajaxSetup({
data: {
csrf_test_name: $("input[name='csrf_test_name']").val()
}
});
an easier method is to pass that csrf to $.ajaxSetup() that way it's included with any $.ajax() request afterward.
var csrf = $('input[name="csrf_test_name"]').val();
var data = {};
data[CSRF] = csrf;
$.ajaxSetup({ 'data': data });
then no need to include data: { csrf_test_name: 'xxx', ... } in requests after setup.

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