Updating server side Flask sessions with AJAX not working - ajax

I'm trying to figure out why my AJAX script won't update my Flask app's server side session.
Implemented Flask-Session with sqlalchemy. I can see the table in the database and the encrypted session data.
init.py
...
from flask_session import Session
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
Session(app)
...
config.py
...
SESSION_TYPE = 'sqlalchemy'
SESSION_SQLALCHEMY_TABLE = 'app_sessions'
Ajax call works as I am getting the correct response.
$.post("/ajax_fnc/_update_session", post_data)
.done(function(data) {
console.log(data)
})
Flask app returns updated cart_data:
...
#app.route('/ajax_fnc/_update_session', methods=['POST'])
def ajax_update_session():
session['cart_data']['qty'] = 1
return jsonify(session['cart_data']['qty'])
Browser console logs the updated and correct response from the Flask app. But refreshing the site loads the session with a cart data quantity of 0. So it didn't work.
How do I update the server side session with AJAX and get it to persist? What am I missing?
Note: Initializing the session with a cart quantity of 0 on the server side works just fine. Just when I attempt an update with Ajax it doesn't stick. I've spent more than half a day searching for answers but can't seem to find what I'm missing (or not understanding).

Shoot, after a lot more digging it turns out that my initialize function was being called every single time an http request was made. So... of course an ajax update would never persist.
Relocated the initialize function and the server side session works fine.

Related

Could not get session during GET method

Using Laravel 8 and axios.
During POST method, there's no problem accessing the session.
But when I switch to the GET method in between, the session is blank.
POST = session is ok
GET = session is blank
POST again = session is still there
It just happened all of a sudden. I'm pretty sure I did not do any major changes.
Any idea? Thanks a lot!

overcoming access-control-allow-origin in simple web map site

I am trying to set up a simple web page, that will draw a map with some openstreetmap data. I am serving the page for now with a (python) simpleHTTPserver on port 8000 of my local machine.
In my page I run a script that sends an AJAX request to openstreetmap.org:
$(document).ready(function() {
console.log ("Document is loaded.");
var map = L.mapbox.map('mapsection', 'examples.map-vyofok3q');
$.ajax({
url: "http://www.openstreetmap.org/api/0.6/way/252570871/full",
dataType: "xml",
success: function (xml) {
var layer = new L.OSM.DataLayer(xml).addTo(map);
map.fitBounds(layer.getBounds());
}
}); // end ajax
});
(The L. refers to Leaflet javascript libraries I included.) I am having trouble with same origin policy errors. Chrome says, "XMLHttpRequest cannot load http://www.openstreetmap.org/api/0.6/way/252570871/full. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
In serving the HTTP locally I followed the advice from a promising SO answer Can I set a header with python's SimpleHTTPServer? and so I ran $ python ajax-allower.py
where ajax-allower.py contains the code below. Can you explain why I still get the error, and suggest how I can get around it?
#!/usr/bin/env python
# runs the simple HTTP server while setting Access-Control-Allow-Origin
# so that AJAX requests can be made.
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Access-Control-Allow-Origin", "http://www.openstreetmap.org")
#self.send_header("Access-Control-Allow-Origin", "*")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
The ajax request fails because the object in question has been deleted.
If you try it with an object that still exists (e.g. http://www.openstreetmap.org/api/0.6/way/666/full), your jQuery code should perfectly work. Or if you grab the full history of the deleted object (http://www.openstreetmap.org/api/0.6/way/252570871/history), but that's probably not really what you want, I suppose.
It should be said, that the API probably should also send the CORS-headers for the failing (HTTP 410 Gone) requests, so that your client can detect the error code. This looks like a bug that should be reported on github.

prevent ajax request caching in IE during post method

How to prevent IE from caching the request sent to the server?
i tried by setting ("Cache-Control: no-cache) in the https response object but still the IE is caching my request data.
Please find tmy project details as below:
in my application i am sending login request to the server. so after i login if i take the memory dump using winHex tool i am able to get the password details in the memory.
i am clearing the dialog refrense also but still the request data is getting cached.
Please suggest me some work arround for this
You could try to add a parameter to your URL with a random value, this will prevent that the URL is always thesame.
Example:
Normal URL:
www.test.com/test.php
Fake different URL:
www.test.com/test.php?_dc=12353somerandomval
Make sure the _dc parameter always has a different value, you can (for example) use JavaScript date object for this (It returns the current time in milliseconds, which will virtually always be different):
params: {
_dc : new Date().getTime()
}
In a project I did a while back I had the exact same issues, I searched around and saw a few things that recommended adding a time stamp to the request, that does work too, but this was the most elegant way that worked for me.
$('document').ready(function () {
$.ajaxSetup({
cache: false
});
});

wev2py 1.99.2: saving sessions to database

In web2py version 1.99.2, at the beginning of default.py controller I wrote the following:
session.connect(request, response, db, masterapp=None)
I'm using sql server 2008 express edition. In db.py I have:
db = DAL('mssql://sa:mypass#.\SQLEXPRESS/mytest')
Now, sessions are created in the database as expected. Then in default.py controller I added:
#auth.requires_login()
def test():
return dict()
Also, default/test.html view was created. But, when I try to browse to the default/test.html page it redirects to the user/login page. The problem goes away, if I switch to the default file-based session. What's wrong with my code?
Try moving
session.connect(request, response, db, masterapp=None)
to db.py, right after you define the db connection. When auth is defined (I assume you have defined it in db.py or another model file), it needs to have access to the session, so you have to connect to the session first.

CakePHP Concurrent AJAX Requests Blocking

I am working with CakePHP on an app which has to run a time-consuming task via a single AJAX call, with secondary periodical AJAX calls checking on the progress of the task.
The Problem
While the time-consuming task (which takes >30 seconds) is running via it's AJAX request to CakePHP, the secondary progress AJAX request seems unable to be "blocking".
To clarify, the secondary progress AJAX request does not return any error, it simply does not return any response until the original time-consuming request finishes.
Once this original AJAX request finishes, the secondary progress AJAX request returns as expected.
It seems that execution of the progress request is being queued until the first AJAX call finishes, as the progress returned is 100%.
What I've Tried
I have tried multiple suggested solutions, including:
Changing the session handler to 'cake' in core.php - no fix
Setting the config security level to 'medium' in core.php - no fix
Disabling user agent checks in core.php - no fix
Testing multiple concurrent AJAX calls to a plain PHP script on the same server - works as expected
Any Ideas?
So it seems as though the issue is caused by CakePHP - has anyone experienced this in their own CakePHP app?
Thanks!
Session handling is set to file in php
from php.ini
[Session]
; Handler used to store/retrieve data.
; http://php.net/session.save-handler
session.save_handler = files
This prevent php from running more than one instance of session per user.
To prevent this run this in your php code:
session_write_close();
Just know session is now closed, so writing to session is no longer an option.
For some clarification, are you using the built-in AJAX helper (on prototype) or some external library like jQuery?
Usually, the javascript library of choice has an {async: true} available to force concurrency. See this example:
$.ajax({
type: 'GET',
url: '/fetch.php',
async: true,
success: function(data, status) {
$('#status').html(status);
}
});
For the built-in CakePHP AJAX helper, this option should do the trick: $options['type']. More info here. Do note that the AJAX helper is deprecated as of version 1.3 and the jsHelper should be able to takeover, see the request() method here for instance (also has an option called async).

Resources