How I can send data from Flask to JavaScript? - javascript

Hello I am new and building an application in Flask and Javascript. I have a problem with sending data from Flask do JavaScript.
I have code in routes.py
#app.route('/mapaa',methods=['GET','POST'])
def mapa():
user_id = current_user.get_id()
slownik = {}
if 'event_form' in request.form:
name = request.form['name_event']
all_data = Event.query.filter_by(name=name).all()
for row in all_data:
date_st_string = str(row.date_start)
date_end_string = str(row.date_end)
slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
return jsonify(slownik)
return render_template('mapaa.html', title='Mapa')
I want to send jsonify(slownik) to my code in JavaScript but I dont want to do it with render_template bacause it refresh a page and I need this data to display it on the map using JavaScript. I tried return jsonify(slownik) but it return me the data on new page. How I can send the data when the user click event_form button to JavaScript without refreshing page?

You can use ajax for sending post request without refreshing the page.
Note- include jquery before this
<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>
javascript code
$("#id_of_btn").click(function () { // make ajax request on btn click
$.ajax({
type: "POST",
url: "/mapaa", // url to the function
data: {
name: $("#id_of_input_tag").val(), // value of the form
},
success: function (response) {
console.log(response); // response contains the json
},
});
});
make sure you don't use form tag.
Edit:
If you want to send more data via forms, you could use
data: $('form').serialize()
this will take the name attribute of input tag and add it in the request.data
So if you have this
<input type="text" id="element_id" name="username" >
You can use the value of name attribute like this request.data['username']
follow this tutorial

Related

Django: Passing multiple keys into AJAX including a JavaScript seralised form and parsing them in python

What I need
I'm trying to find a way to send a multi layered dictionary via AJAX to my server, including a JavaScript seralised form with the use of serialize().
The issue
When I use data: frm.serialize();. It's a single layered json and it is easily parsed when returned to server with result:
<QueryDict: {'csrfmiddlewaretoken': ['6aTZ7xey90sczae15069ZlbIiE7gVWW69RyeJBptUxadbgnBo8t8R0Nskg8S8Jzb', '6aTZ7xey90sczae15069ZlbIiE7gVWW69RyeJBptUxadbgnBo8t8R0Nskg8S8Jzb'], 'days': ['Mon', 'Wed'], 'no_weeks': ['1']}>
Then when using a nested dictionary with
data: {'form':frm.serialize(),'additional_data':12,'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()}```
I get:
<QueryDict: {'form': ['csrfmiddlewaretoken=IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg&days=Mon&days=Thu&no_weeks=2&csrfmiddlewaretoken=IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg'], 'additional_data': ['12'], 'csrfmiddlewaretoken': ['IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg']}>
What i've tried
I have attempted with use of this answer to use urllib to parse the form section of the data into a separate variable. Like so:
x = parse_qs(urllib.parse.urlparse(request.POST['form']).query)
This returns an empty dicitonary.
Code
HTML
<form method="post" id="replicate_form">
[..more code]
</form>
Javscript
function send_replication_data() {
var frm = $('#replicate_form')
var form_server_response = submit_formdata(frm)
}
// parent function to handle replcation form saving
$('#create_replicate_booking_button').on('click', function() {
send_replication_data()
});
// submit booking data ajax
function submit_formdata(frm) {
var tmp = $.ajax({
type: frm.attr('method'),
async:false,
url: window.location.href,
data: {'form':frm.serialize(),
'additional_data':12,
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()}
});
return tmp.responseJSON;
}
Possibly I could somehow make use of whatever Django is doing in it's middleware to a parse the form data in the first scenario?
The .serialize() method creates a text string in standard URL-encoded notation.
You could use urllib.parse.parse_qs to parse a query string(form data sent to server by GET) or request.POST['form'] since it uses the same encoding.
Query strings are element of urls, while request.POST['form'] has no attribute called query
from urllib import parse
x = parse.parse_qs(request.POST['form']).query)

How to run a python script inside javascript and refresh the view in django

I have a python script that takes in some data and manipulates it. However i need it to run on the client side inside the javascript to process some data and refresh the view.
The python file that manipulates data works well as I have tested it inside the IDLE shell
DataManipulation.py
class ModifyData(object):
#Bunch of functions to manipulate data
below is the function used to render the view with url '.../test' which also works perfectly.
views.py
def test(request):
template = 'app/test.html'
file = 'documents/Sample.csv' #File to be loaded
args = {'test': file }
return render(request, template, args)
After loading this page, i use a javascript library that displays the data on the page in a table, the user can then manipulate the data like multiply a column by 3, but where I am stuck is how to take my DataManipulation.py file to modify the data and updates the page with the updated column on a button click
Since executing python client side is not an option, you have two options.
re-write ModifyData in Javascript and use it client side.
When a user does something like multiply a column by 3:
Use client side JS to make an ajax request to the server
Have your server call ModifyData, and then return the data to the client
have client update view with new data
I would recommend porting your python code to JS, but if that isn't possible #2 will always work. How you implement will just depend on how you manage data in the client.
I think you should pass the data into template, and then use javascript to manipulate the data, after that you can use ajax to update your page without refresh, example:
<!--html-->
<button onclick="deleteUser({{ request.user.pk }})">Submit</button>
<!---->
function deleteUser(userid) {
var post_data = {
'userid': userid,
}
$.ajax({
type: "POST",
url: "/deleteuser",// the view function to post
data: post_data,
contentType: 'application/json;charset=UTF-8',
success: function(result) {
// do something after post
...
}
});
}
the view function:
# url(r'^/deleteuser$', views.delete_user)
def delete_user(request):
if request.method == 'POST':
# do something
userid = request.POST.get('userid')
user = User.objects.get(pk=userid)
# dict contain response data
response_data = {...}
# return response
return HttpResponse(json.dumps(response_data),content_type='application/json')

load php page from jquery ajax post unloading the current page

I need to generate a report showing in a php page which will be called by a jquery ajax call. Can any body help me on how to do this.
The jquery ajax post is as following:
$('#report_condition #Submit_rpt_betn_dates').on('click', function(){
var start_dt = $('#report_condition').find('.rpt_betn_dates').find('.start_search_date').val();
var end_dt = $('#report_condition').find('.rpt_betn_dates').find('.end_search_date').val();
alert('you want to generate report between '+start_dt+' and '+end_dt);
$.ajax({
type: "POST",
url: "./report-betn-dates.php",
data: {'startdt':start_dt, 'enddt':end_dt}, //the first parameter in the pair is actually the key for $_POST in PHP
//and it must be withing quotes for ajax to run!!
crossdomain: true,
success: function(response) {
}
});
});
I tried with $('body').html(response); within success parameter of the ajax call. But by this I cannot access the separate css file for the php page. Hence I would like to unload the page containing the ajax call and load the php page with the data sent through $_POST[].
Ajax is for partial content load, asyncronous interactions , etc.. Since what you're trying to achieve is complete new page loaded with its own static resources (css, js) this is the perfect "syncronous" scenario.
So, why wouldn't you use a simpler setup like a form which sends the required vars in post and moves the user to the correct php page?
$('#report_condition #Submit_rpt_betn_dates').on('click', function(){
var fake_form = $('<form method="post" action="report-betn-dates.php">');
var input_start = $('<input type="hidden" name="startdt">');
var input_end = $('<input type="hidden" name="enddt">');
$(fake_form).append(input_start);
$(fake_form).append(input_end):
$(fake_form).submit();
});

Ajax call in jquery to refresh database models in Django

I have a search feature I built for an administrative account in Django on the front-end that queries matched users to the admin with an option to remove them from the database. Currently, they click the button, and they are redirected to the view that handles the backend logic for removing the associated object by the primary key from the database. I am wanting to have the user remove the object on button click and then update the div that the users display in after object has been removed without the page refreshing. How can I go about this?
Here a super generic example.
You can do something like:
in your views.py:
def delete_element(request, element_id):
element = get_object_or_404(ElementClass, id=element_id)
element.delete()
return HttpResponse("success")
in your urls.py:
url(r'^element_delete/(?P<element_id>\d+)/$', 'app.views.delete_element', name="name_element_delete"),
in your template:
<script>
$(".delete-button").click(function(){
var element = this;
var url = $(this).data('url');
$.ajax({
type: 'GET',
url: url,
success: function(){
// do what you want with 'element' var
},
error: function(){
alert("Error on delete, please try again");
},
});
});
</script>

Send content created by javascript in PHP mail?

I'm using a javascript shopping cart on a store, and I want to send an order confirmation on checkout. The problem is that the cart isn't saved in database of any kind, and is printed with javascript. How would I attach it to the email? I've included the shopping cart script on the page that sends the mail.
<table class="simpleCart_items"></table> would print the cart, but how would I attach the printed cart to email?
Hidden input or something?
UPDATE
My ajax call looks like this:
var data = $('#yhteystiedot').serialize();
data.cartContent = $('.simpleCart_items').html();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "order.php",
data: data,
dataType: "text",
error: function(){ alert("Jotakin meni pahasti pieleen! Yritä uudelleen?");
},
success: function() {
$(document).html("Tilaus lähti.");
}
});
You can make an ajax call to a php function that sends an email. The argument is the content generated by javascript.
You'll need to post the cart values to serverside PHP script and recreate the HTML for the cart in order to be able to send it through email. You can do direct form post or ajax post based on your need.
I asume your $.ajax() call looks something like this:
$('form').submit(function(){
var dataTrunk = $(this).serializeArray();
dataTrunk.push( { name: 'cartContent', value: $(your_table_selector).html()});
$.ajax({
url: 'mail.php', // your mail script
data: dataTrunk,
type: 'post'
});
return false;
});
In php you would trap $_POST['cartContent'] and render it in email and send it.
If you are sending email with html and plain text body, then it would probably be a good idea to strip html elements and replace them with chars that are compatible with plain text.
// edited: I've fixed the error

Categories

Resources