Python – A simple flask application server that uses ajax and jquery to pass data

A simple flask application server that uses ajax and jquery to pass data… here is a solution to the problem.

A simple flask application server that uses ajax and jquery to pass data

I’ve been modifying this app all day, trying to pass some simple information to the backend of the app. I’m using a simple flask app and trying to send data from a search query to the backend using ajax. However, I was completely unsuccessful. Any help would be appreciated.

Here’s app.py

from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)

@app.route("/")
def index():

entries = json.dumps(scrape("video games"))
    return render_template('index.html', entries= entries)

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
    if request.method == "GET":
        #data = request.form("blah")
        #print("blah")
        search = request.json
        #new_search = json.dumps(scrape(data))
        return search
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=5000)

and index .html

    <! DOCTYPE html>
<html>

<head>
    <title>Flask app</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

</head>
<body>

<div class="topnav">
    <a class="active" href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
    <form name = "textbox" id = "textbox">
      <input id ="textbox" name="textbox" type="text" placeholder="Search.." >
      <button type="submit">submit</button>
    </form>
  </div>

<p>you searched: {{search}} </p>

<div id="div1">
  <p id="p1"></p>
  <p id="p2"></p>
  </div>

<script>

var value = $('.textbox').val();
alert(value);
$.ajax({
  type: 'POST',
  url: "/parse_data",
  data: JSON.stringify(value)
  contentType: 'application/json',
  success: function(data){
    alert("success")
  }
});

var jsonz = {{ entries|tojson }};

var s = JSON.parse(jsonz);

var i;
for (i = 0; i < s.length; i++) {
  var para = document.createElement("p");
  var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
  para.appendChild(node);

var element = document.getElementById("div1");
  element.appendChild(para);
}

document.getElementById("user").innerHTML =
obj;
"Name: " + obj.product_name + "<br>" +
"Location: " + obj.product_link;
</script>

</body>
</html>

Solution

There are some issues with your code snippet, mainly:

  • Your AJAX request is not bound (binded) to the button click event, so the button click does nothing.
  • You have two HTML elements with the same id textbox, and the ID should be unique.
  • To get the html element by id, use “#textbox"

On the server side (Flask):

  • Use the requested function get_json().
  • To process a POST request, you need to check the POST instead of GET

Try wrapping your POST request like this:

$("button").click(function (e) {
    e.preventDefault();
    var value = $("#textbox").val();
    alert(value);
    $.ajax({
        type: "POST",
        url: "parse_data",
        data: JSON.stringify({ "text" : value } ),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert(JSON.stringify(data));
        }
    });

});

Also remove the duplicate ids textbox, change the id of the form to textbox-form, and finally change the parse_data function to something like this:

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
    if request.method == 'POST':
        search = request.get_json()
        return jsonify(search)
    return render_template('index.html')

Related Problems and Solutions