How to submit data to Flask from an Ajax call, and return its response in Flask from another Ajax call? - ajax

Sorry if the title is a little confusing. A kind user here on StackOverflow helped me make my Flask app display some scraped data, only now I have added a parameter in the function so that I can scrape the data I want to search for. I have an input box, and I want to be able to get the data from it, and pass it as a string in my python function in Flask
Current HTML Side
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>NBA Data Web App</title>
</head>
<body>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
<form id = "nameForm" method = "POST" role = "form">
<input name = "text">
<button id = "searchBtn"> Search </button>
</form>
<div id = "container"></div>
<script type = "text/javascript">
//Function to take place when our search button is clicked
$('button#searchBtn').click(function() {
$.ajax({
url: '/_get_data',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log = response;
},
error: function() {
alert('Failure in first Ajax call');
}
});
/*Everything below this was working before, as I only made one ajax call when a button was pressed. Now, when I press the button, I want to pass its contents as a string to my scrape_data() function in Flask, and return, and display, its contents as shown below. */
//Declare our list so we can print something, and loop through it later
var data_list;
//Variable for our HTML table
var rowMax = 29, html = "<table><tr>";
//Post request
$.post('/_get_data', {
//If done, do this
}).done(function(response) {
/* Assign our scraped data to our variable that was declared earlier,
which is turned into an array here in JS */
data_list = response['data'];
//Declare some variables for making our table
var perRow = 1, count = 0, table = document.createElement("table"),
row = table.insertRow();
//Loop through the data and add it to the cells
for (var i of data_list) {
//Insert a cell for each piece of data
var cell = row.insertCell();
//Add the data to the cell
cell.innerHTML = i;
//Increment our count variable
count++;
//If we have met our set number of items in the row
if (count % perRow == 0) {
//Start a new row
row = table.insertRow();
}
}
//Add the table to our container in our HTML
document.getElementById("container").appendChild(table);
//If request fails
}).fail(function() {
alert("request failed");
});
});
</script>
</body>
</html>
Python (Flask) Side
rom flask import Flask, render_template, jsonify, request, escape, url_for
#Get our lists to post
headers = data_headers()
#Start the flask app
app = Flask(__name__)
#Start page
#app.route('/')
def index():
return render_template('index.html')
#What happens when our button is clicked
#app.route('/_get_data', methods = ['POST'])
def _get_data():
text = request.form['text']
#Here, I am trying to assign the contents of the input box of the form to a variable, so I can pass that variable as a parameter for my function.
data = scrape_data(text)
#Return the json format of the data we scraped
return jsonify({'data' : data})
#Run the app
if __name__ == "__main__":
app.run(debug = True)
I am currently getting error 405 method not allowed. I'm not sure if my syntax in the first Ajax call is incorrect, or if I need to break this up into two different #app.route(urls) since each call is going a different way.

If you use the method attribute of form element and do not specify the action, request will be sent /. What is happening here is when you click on search button it will send two post requests one to '/' and '/_get_data' from ajax. In Flask routing if you do not explicitly provides methods=[] that route will allow GET only. Remove the method attribute from you form, you should not get method not allowed error.

Related

Context from Django Render Not Displaying Till Refresh?

I am using an AJAX call to POST a value to my views.
From my views I am finding the product based on the value(id) passed to my view. I add it to my invoice and apply it to my context which I render at the bottom of my view. The context will not be displayed until I refresh, but I can't have that. I am stuck.
...
elif request.is_ajax():
product_id = request.POST.get('value')
if product_id:
product_info = Product.objects.get(id=product_id)
new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info)
invoice.attached_products.add(new_invoice_product)
context['attached_products'] = invoice.attached_products.all()
...
return render(request, 'inventory/invoice_create.html', context)
You can't just re-render client's HTML DOM by your server directly.
Through DjangoTemplate Engine, it just render then respond with HTML itself. This means you can't update client's DOM with ajax unless you update root element, <html>. (and this will be as same as reloading page!)
So you may want to update DOM tree with some data, do with ajax call then update with jsonfile only. If you use JsonResponse, then you can get it with AJAX response object.
Then What you have to do is NOT django template but JavaScript programming.
In your views.py, do like this:
# in your views.py
...
elif request.is_ajax():
product_id = request.POST.get('value')
if product_id:
product_info = Product.objects.get(id=product_id)
new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info)
invoice.attached_products.add(new_invoice_product)
context['attached_products'] = invoice.attached_products.all()
# return render(request, 'inventory/invoice_create.html', context) # NOT render but do like this:
return JsonResponse({
'new_data': {
'id': new_invoice_product.id
# and other informations you want...
}
})
In your HTML, do like this:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
// in your HTML
// guessing you're using jquery..
$.ajax({
url: "test.html",
context: document.body
}).done(function (json) {
$('yourSelector').append(json['new_data']['id']);
});
</script>
Remember, this code is just snippet not Fully working code. If you want to know further examples, take a look at link:
https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

Refresh form in Django without reloading page

Hi I'm new in Ajax and django and I want to refresh my form. I try some code but it didn't work. I'm sure what I want to do is very basic.
Here my html:
<div class="row" style="padding-top:20px;">
<div class="col-md-12" id="testAjax">
{% load crispy_forms_tags %}
{% crispy form %}
</div>
</div>
I want to refresh my form in the div testAjax.
Here my view:
def createPin(request):
error = False
if request.method == "POST":
form = CreatePinForm(request.POST)
if form.is_valid():
pin = form.save(commit=False)
pin.customer = request.user.customer
pin.save()
msg = "pin saved"
return redirect('/pin/CreatePin', {'form': form, 'msg': msg})
else:
error = True
else:
form = CreatePinForm()
return render(request, 'createPin.html', {'form': form, 'error': error,})
My Ajax:
function refresh()
{
$form=$('#createPin');
var datastring = $form.serialize();
$.ajax({
type: "POST",
url: '/pin/CreatePin/',
dataType: 'html',
data: datastring,
success: function(result)
{
/* The div contains now the updated form */
$('#testAjax').html(result);
}
});
}
Thanks alot for your help.
When I need to do some operations and I don't want to reload the page I use a JQuery call to Ajax, I make the pertinent operations in AJAX and then receive the AJAX response in the JQuery function without leaving or reloading the page. I'll make an easy example here for you to understand the basics of this:
JQuery function, placed in the template you need
function form_post(){
//You have to get in this code the values you need to work with, for example:
var datastring = $form.serialize();
$.ajax({ //Call ajax function sending the option loaded
url: "/ajax_url/", //This is the url of the ajax view where you make the search
type: 'POST',
data: datastring,
success: function(response) {
result = JSON.parse(response); // Get the results sended from ajax to here
if (result.error) { // If the function fails
// Error
alert(result.error_text);
} else { // Success
//Here do whatever you need with the result;
}
}
}
});
}
You have to realize that I cannot finish the code without knowing what kind of results you're getting or how do you want to display them, so you need to retouch this code on your needs.
AJAX function called by JQuery
Remember you need to add an url for this Ajax function in your urls.py something like:
url(r'^/ajax_url/?$', 'your_project.ajax.ajax_view', name='ajax_view'),
Then your AJAX function, it's like a normal Django View, but add this function into ajax.py from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.utils import simplejson
#csrf_exempt
def ajax_view(request):
response = []
#Here you have to enter code here
#to receive the data (datastring) you send here by POST
#Do the operations you need with the form information
#Add the data you need to send back to a list/dictionary like response
#And return it to the JQuery function `enter code here`(simplejson.dumps is to convert to JSON)
return HttpResponse(simplejson.dumps(response))
So, without leaving the page you receive via javascript a list of items that you sended from ajax view.
So you can update the form, or any tag you need using JQuery
I know that this can be so confusing at the beginning but once you are used to AJAX this kind of operations without leaving or reloading the page are easy to do.
The basics for understanding is something like:
JQuery function called on click or any event you need
JQuery get some values on the template and send them to AJAX via
POST
Receive that information in AJAX via POST
Do whatever you need in AJAX like a normal DJango view
Convert your result to JSON and send back to the JQuery function
JQuery function receive the results from AJAX and you can do
whatever you need

redirect to another page after ajax function

Can anyone help me with, I am trying to create a download counter to my website.
I have a ajax script that counts up by 1 when the users clicks the download link, the issue I am having is on some browsers it goes to the download link before completing the ajax count script.
Is there a way that I can redirect to the download file once the script has completed. At the moment I have as follows
This is the link :-
<a href='downloads/".$downfile."' onclick=\"Counter('$referid');\"'>Download File</a>
This is the counter script:-
<script type="text/javascript">
function Counter(id)
{
$.get("clickcounter.php?id="+id);
{
return false;
}
}
</script>
This is the php script (clickcounter.php)
<?php
include('dbutils.php');
$referid = $_GET['id'];
$q = "SELECT * FROM downloads WHERE downid =".$referid;
$r = mysql_query($q);
while ($row = mysql_fetch_array($r))
{
$click = stripslashes(trim($row['downcount']));
$download = $row['downfile'];
}
$countup = $click + 1;
$qUpdate = "UPDATE downloads
SET downcount=$countup
WHERE downid=$referid";
$rUpdate = mysql_query($qUpdate);
?>
A few relatively small modifications should solve the problem. First, change the onclick to the following:
onclick=\"Counter('$referid', this); return false;\"
What we have done is to send in this as the second argument to the Counter function so we have a reference to the clicked link. Secondly, we have added return false, which blocks the browser from navigating to the url specified in the href.
The modified counter function looks like this:
function Counter(id, link) {
$.get("clickcounter.php?id=" + id, function() {
location.href = $(link).attr("href");
});
}
We now have a reference to the clicked link. A function has now been specified as the second argument to $.get(). This is the success-function, which is called when the ajax call has been successfully called. Inside that function we now redirect to the url specified in the href attribute on the clicked link.
I feel I should point out that the recommended way is to bind the onclick using jQuery separate from the html. The referid can be stored in a data attribute (which I chose to call data-rid):
<a href='downloads/".$downfile."' class='dl' data-rid='$referid'>Download File</a>
Then you bind the onclick for all download links (a elements with a "dl" class):
$(function() {
$("a.dl").click(function() {
var id = $(this).attr("data-rid");
var href = $(this).attr("href");
$.get("clickcounter.php?id=" + id, function() {
location.href = href;
});
return false;
});
});​
(I feel I should point out that the code has not been tested, so it's possible that a typo has snuck in somewhere)

How do I repopulate form fields after validation errors with express-form?

Using node.js and express (2.5.9) with express-form.
How should I repopulate form fields with the submitted values?
I have a get and a post route. If there are validation errors when the form is posted, I redirect the user back to the get, the problem is that the repopulated locals don't show up (I do have autoLocals: true, so I assume it's because I am redirecting and res is reset.)
So how do you guys repopulate and what's your application flow, do you res.send instead of res.redirect and set up the whole thing again? That seems repetitive.
Here's an example of my post route:
app.post(
'/projects/:id'
, form(field("title").required("title", "Title is required)
, function (req, res){
if (!req.form.isValid){
res.redirect('/project/'+req.params.id+'/edit');
}
else{
// save to db
}
});
I am working with expressjs4.0 to repopulate the forms fields after validation you do:
router.route('/posts/new')
.get(function(req, res) {
res.render('posts/new', new Post({}));
});
The second argument in res.render below will set some variables in the view.
res.render('posts/new', new Post({}));
In my view I then set my form fields as follows:
...
<input type="text" name="title" value="<%- post.title %>">
<textarea name="article"><%- post.article %></textarea>
...
When you submit this form, it should be caught by your router like so:
router.route('/posts')
.post(function(req, res) {
var post = new Post(req.body)
post.save(function(err) {
if (err) {
res.locals.errors = err.errors;
res.locals.post = post;
return res.render('posts/new');
}
return res.redirect('/posts');
});
...
})
This line of code, resets the form fields in your view
res.locals.post = post;
I hope someone finds this useful ;)
Not sure if it's best practice, but when I have validation failure, I don't redirect I just re-render the view (often by passing control to the 'get' callback). Somethign like this:
function loadProject(req,res, id){ /* fetch or create logic, storing as req.model or req.project */}
function editProject(req,res){ /* render logic */ }
function saveProject(req,res){
if(!req.form.isValid){
editProject(req,res);
}else{
saveToDb(req.project);
res.redirect('/project'+req.project.id+'/edit');
}
}
app.param('id', loadProject);
app.get('/projects/:id/edit', editProject);
app.post('/projects/:id', saveProject);
I had to work on similar problem recently and used two node modules: validator and flashify.
In the form view I configured my form fields as follows:
div.control-group
label.control-label Description
div.controls
textarea(name='eventForm[desc]', id='desc', rows='3').input-xxlarge= eventForm.desc
div.control-group
label.control-label Tag
div.controls
select(id='tag', name='eventForm[tag]')
tags = ['Medjugorje', 'Kibeho', 'Lourdes', 'Fatima']
for tag in tags
option(selected=eventForm.tag == tag)= tag
Notice the naming convention of the form fields. Then in my config file I set one global variable, which is really just a placeholder for when the form first loads:
//locals
app.locals.eventForm = []; // placeholder for event form repopulation
The validation logic is in my router file and looks like this:
app.post('/posts', function(req, res){
var formData = req.body.eventForm;
var Post = models.events;
var post = new Post();
post.text = formData.desc;
post.tag = formData.tag;
// run validations before saving
var v = new Validator();
var isPostValid = true;
// custom error catcher for validator, which uses flashify
v.error = function(msg) {
res.flash('error', msg);
isPostValid = false;
}
v.check(post.text, "Description field cannot be empty").notEmpty();
v.check(post.tag, "Tag field cannot be empty").notEmpty();
Then I check to see there are errors, and if so, pass the form data back to the view:
// reject it
res.render('Event.jade', {page: req.session.page, eventForm: formData});
Notice this evenForm data gets passed back to the view, which repopulates the default values.
The final step is to include the flashify component in your form view.
div(style='margin-top: 60px').container-fluid
include flashify
The code for the flashify view looks like this:
if (flash.error != undefined)
div.container
div.alert.alert-error
b Oops!
button(type='button', data-dismiss='alert').close ×
ul
each error in flash.error
li= error
if (flash.success != undefined)
div.container
div.alert.alert-success
b Success!
button(type='button', data-dismiss='alert').close ×
ul
each success in flash.success
li= success

Update using Prototype and Ajax

I am using Ajax and Prototype. In my code, I need to update the contents of a div.
My div:
<div id="update">
1. Content_1
</div>
My code:
Element.update($("update"),"2.Content_2");
Expected output:
<div id="update">
1.Content_1
2.Content_2
</div>
How can I do this in Ajax and Prototype?
AJAX usually means you are executing a script on the server to get this result.
However, in your example it looks like you simply want to append some text.
To append text you could simply add the text to the end of the innerHTML:
$("update").innerHTML = $("update").innerHTML + "2.Content_2";
If you are wanting to execute a server script, I'd do this: (I haven't used Prototype for a while, things might have changed)
function getResult()
{
var url = 'theServerScriptURL.php';
var pars = '';
var myAjax = new Ajax.Request(
url,
{
method: 'post',
parameters: {},
onComplete: showResult
});
}
function showResult(originalRequest)
{
$("update").innerHTML = originalRequest.responseText;
}
This code will call 'theServerScriptURL.php' and display the result in the div with id of 'update'.

Resources