Pass a string variable from javascript file to a python function - python

I have an ag-grid. Clicking on its context menu is opening a modal that has a drop-down menu that I want to populate dynamically by fetching the data from a SQLite database.
I want to pass a string variable - network_num from my .js file to a python function. I will then use this variable to execute a query to fetch data from the database. I should then send the fetched data in JSON format to .js file to populate the drop down menu. I am using ajax to send the variable, but it is not working. Please help.
Here is the code
$.ajax({
url: "/get_activity",
type: "POST",
dataType: "json",
data: {
network_num: network_num,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
alert("Successfully sent the variable");
},
error : function(xhr,errmsg,err) {
alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
def get_activity(request):
print("Get activity function is running")
#I have my sql query here that I want to execute

Assuming you already have the infrastructure built, in python, request should be passed as a dictionary object, so unless the caller is doing something crazy, it should just be request['network_num']

Related

Fetching data after a certain time interval(10 sec) from a continuously increasing database like mysql using flask

I want to create an api using python and flask that fetches data in regular time interval(10 sec) from a continuously increasing database where data is continuously coming and stored.I don't want to fetch the old data which were already fetched.
Say you currently have an API endpoint that returns all the database stored data:
#app.route('/data', methods=['post'])
def data():
all_the_data = Data.query.order_by(Data.created.desc()).all()
return jsonify(results=all_the_data)
So your ajax call currently doing something like:
$.ajax({
type: "POST",
url: "/data",
dataType: "json",
success: function(data) {
console.log(data);
update_graph(data);
}
});
You just need a way for the system to filter what's going out, back to the client-- so we instead of querying all the data, we can filter based on a reference:
#app.route('/data', methods=['post'])
def data():
client_data = request.json
reference = client_data.get('reference')
if reference:
# we have a reference, so lets filter the query:
query_data = Data.query.filter(Data.id>reference).order_by(Data.created.desc()).all()
else:
# no reference, so send the lot!
query_data = Data.query.order_by(Data.created.desc()).all()
return jsonify(results=query_data)
Then your ajax request needs to get the last reference from the last query it did-- and supply that to the API endpoint:
$.ajax({
type: "POST",
url: "/data",
data: JSON.stringify({ reference: 999 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log(data)
update_graph(data["results"]);
}
});
So you just need to work out how to get that reference value from the last set of values you recieved (the API could send that back as another key, or you could poll your current set within javascript, etc).

URL sent to Django using AJAX is different when printed from Django

I have a JQuery event that, when a link is clicked, an AJAX POST request is sent to a Django function. There I print the recieved url and do other stuff with it. However, when it is printed (by Django) some characters in the url are changed.
The specific url this happened with was :
https://www.catholicleague.org/05press_releases/quarter%204/051110_put_on_notice.htm
Which was printed as :
https://www.catholicleague.org/05press_releases/quarter+4/051110_put_on_notice.htm
Where %20 was changed to +
Here is the AJAX and Django code:
$("a").on("click", function(e){
e.preventDefault();
if(e.target.href){
let clicked_source = e.target.href;
let csrf_tok = parent.document.getElementById("csrf_tok").value;
$.ajax({
url: "/change_origin/",
data: JSON.stringify({"clicked_source":clicked_source}),
type: "POST",
beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrf_tok );},
success: function(response) {
console.log(response.msg)
},
error:function(error) { console.log(error); }
});
}
});
def change_origin(request):
if request.method == 'POST':
received = ast.literal_eval(request.body.decode())
print(received)
clicked_source_url = received['clicked_source']
return JsonResponse({'msg': "ok"})
Where decode is used as the JSON object is received in Python as a byte-like object. And ast is used to turn the string representation of the object to an actual object (or dict) for access.
I need either:
1) A way to just send a string from Ajax to Django
2) A better way to deal with the received object as I believe using .decode() might be the one causing this issue.
EDIT: The link is the second link in the "origin" part of this article
https://www.snopes.com/fact-check/an-unmerried-woman/

I am getting jQuery Jtable error while fetching data from the python server

I have a jQuery Jtable in the front end and I am using python flask in my server.
I used python flask to fetch data from the MYSQL server which I can view in the JSON format in my browser but, unfortunately I couldn't able to make the JSON data into the Jtable.
My front end jQuery Jtable is
$('#eventsummary').jtable({
actions: {
listAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/backend/groupdata',
type: 'GET',
data: postData,
success: function (data) {
$dfd.resolve(data);
console.log("loading ");
},
});
});
}
},
fields: {
irs_type: {
title: "Date & Time",
list: true,
}
}
});
$('#eventsummary').jtable('load');
and this is the error I am getting
I am also able to view my console.log code in the browser, with no error in the console.
Can someone please help me with this
Thanks,
I achieved this by using python jsonify to add my json data to the front end Jtable.
for result in data:
json_data.append(dict(zip(row_headers,result)))
return jsonify(
{
'Result': "OK",
'Records': json_data,
}
)
Thanks
The output you are seeing is the standard jTable application error. Your listAction has passed the server response to jTable, so there is no communications error.
When the json response does NOT contain Result = 'OK' it displays the application error dialog, and shows the json Message in the dialog.
The very fact that the error dialog appears means jTable is not seeing Result = 'OK' in your server response. Look for that first, if you are still stuck please post your json response. The dialog is blank because there is no error message or jTable can't see it.

how to open a PDF file while returning the file in AJAX request success response

I get 2 dates, start and end date, via AJAX. I process the data b/w those 2 dates, generate a report and then returns an HttpResponse. The PDF report is now saved in my main project directory. Now I get a response back in AJAX. So, now how should I process the response in the success function, sent back from the sever and open a PDF file.
Thanks.
jQuery
$(function() {
$("#report_submit").click(function(){
$.ajax({
type : "POST",
url: "/reports/",
data : { 'start_date' : $("#startDate").val() , 'end_date' : $("#endDate").val() },
success : function(result){
},
error : function(result){
}
});
});
});
Django view code
def generate_report(request):
ctx = {}
if request.is_ajax():
if request.POST.has_key('start_date'):
start_date = datetime.strptime(request.POST[ 'start_date'] , '%m/%d/%Y')
end_date = datetime.strptime(request.POST[ 'end_date'] , '%m/%d/%Y')
......
# PDF GENERATED in MAIN PROJECT DIRECTORY
with open(os.path.join(os.path.dirname(__file__),'../../../../gui','Report.pdf')) as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'inline;filename=Report.pdf'
return response # so, now when I send a response back, how should I process it in AJAX success function?
pdf.closed
return render(request, 'generate_report/reports.html', ctx)
Don't try and send it in the Ajax response. Instead, get your view to generate a unique URL for the PDF, then get the JS to redirect the browser to that URL:
view:
return HttpResponse(json.dumps({'url': my_url})
JS:
$.ajax({
type : "POST",
dataType: "json",
url: "/reports/",
data : { 'start_date' : $("#startDate").val() , 'end_date' : $("#endDate").val() },
success : function(result){
var url = result['url'];
window.location = url;
},
The simplest solution would be to call window.open(pdf_url) in "success" callback, where pdf_url is the link to your generated pdf report (which you'll need to pass to response).
This problem has been discussed in the following Question... You might need to go for the jquery plugin for file download and please do not forget to set cookie in the response.
PDF file download through XHR Request
You might need to add a javascript file for the file download and also use the folowing code to generate the request to the server.
$.fileDownload(urlll,{
successCallback: function (url)
{
//success code here
},
failCallback: function (html, url)
{
//error code here
}
});
And on the server side while adding the header etc in the response do the following in response object. i.e.
aResponse.addCookie(cookie);
I hope you can solve the issue and can help others as well.. "Dangling Pointer"

how to read a file using ajax and django?

My Ajax code:
var upfile = $("#file-id").val().split(/[\/\\]/).pop();
$.ajax({
type: 'POST',
url: '/upload/',
data:{"upfile":upfile},
success: function(data) {
if (data['success'] === "true") {
}
},
dataType: 'json'
});
return false;
Django code:
In simple form submit action request.FILES.get('upfile') works. I can read the content of file using read() But in ajax, it is not working. even request.POST.get('upfile') gives me the filename string.
How to solve this issue?
It's normal, by default a form submitted with Ajax will not upload files. You need o have a look to some file upload jquery plugins (there's a few of them, I can not suggest one as I did not try any of these yet)

Categories

Resources