3

I've spent all day tinkering with this app trying to get some simple information passed to the back end of the application. I am using a simple flask app and trying to send data from a search query to the back end using ajax. However, I have been completely unsuccessful. Any help would be greatly appreciated.

Below is 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>

1 Answer 1

3

Your code snippet has a few issues, mostly:

  • Your AJAX request is not bind to the button click event, so clicking the button does nothing.
  • You have two html elements with the same id textbox, id are supposed to be unique.
  • To get an html element by id use "#textbox"

On the server side (Flask):

  • Use the function get_json() of the request
  • To process the POST request you need to check for POST not 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 something like textbox-form, finally change your 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')
Sign up to request clarification or add additional context in comments.

7 Comments

I changed the code to what you have. It works now. Could you explain what I was mostly doing wrong?
Masejo Thank you so much I really do appreciate it.
@ Daniel Mesejo One last question: how does it know what button I click?
$("button").click means select the button objects and add the function as a callback, as you only have one button object it only applies to that one if you had more than one you will have to use a more specific selector, pointing to the id or class like $("#mybutton").
Thank you for the info. Can I ask one more? I can't seem to get the search to render on the template. In other words: when I post with a search query, nothing gets returned to the template and displayed like I would want. Any ideas?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.