-4

I have a college assignment in which I need to create a small chatting web site. I'm using Python for the back-end code and Flask as the framework. Basically, I want to get the user input from the front-end, run it with a Python code I developed, and send it back as an answer. How would be the easiest way to do that? I've read a lot about jQuery and AJAX, but I'm very bad at JS. Any tips?

What I need is to,after processing this string, send to the site whatever was processed. I tried to follow this post How do I send data from JS to Python with Flask? and it worked for my POST, but not my GET. It always returns as undefined. I tried changing to dict, trying to make different calls, but I can't find what will work specifically with what I actually need. Thanks!

EDIT!: After trying out @arsho 's code, I got kind of lost. It works and I saw how it was implemented, but couldn't exactly make it work with what I have. This is what I came up with:

test
https://pastebin.com/4i2hDRSJ

Sorry if I'm not being very clear. I translated the variable names for easier understanding.

Pastebin with the html my friend made me:

test
https://pastebin.com/m7FQCgAm

Scripts.js:

test
https://pastebin.com/pM1L77p7

Thanks again.

fallremix
  • 13
  • 5

1 Answers1

1

I am giving a head start for your project. I am giving a simple AJAX search example using Flask.

The application.py contains:

from flask import Flask, render_template, request, url_for, redirect
app = Flask(__name__)

@app.route('/show_search_result', methods=['GET','POST'])
def show_search_result():
    if request.method == "POST":
        word = request.form.get("word")
        word_lower = word.lower()
        data = {
            "name" : "Ahmedur Rahman Shovon",
            "country": "Bangladesh",
            "gender": "Male"
        }
        if word_lower in data:
            value = data[word_lower]
            return value
        else:
            return "No data found"
    else:
        return redirect(url_for('show_index'))

@app.route('/')
@app.route('/index')
def show_index():
    return render_template("ajax.html")

if __name__ == '__main__':
    app.run(debug=True)

And in ajax.html we call the ajax requests like below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="Ahmedur Rahman Shovon">
    <title>Ajax Example</title>
    <link href="https://fonts.googleapis.com/css?family=Exo+2:400,400i,500,500i,600,600i,700,700i,800,800i,900,900i"
          rel="stylesheet">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <!-- Font Awesome CSS -->
    <link rel="stylesheet"
          href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card bg-light mb-3 content">
                <h5 class="card-header">
                    <i class="fa fa-globe"></i>
                    Search Developer's Information (e.g.: name, country, gender etc.)
                </h5>
                <div class="card-body message_area" id="message_area">
                </div>
                <div class="card-footer">
                    <div class="input-group">
                            <span class="input-group-addon">
                                <i class="fa fa-book"></i>
                            </span>
                        <input type="text" class="form-control" id="search_word_text"
                               placeholder="Search a word and press enter"/>
                        <span class="input-group-btn">
                                <button class="btn btn-dark" id="search_btn" type="button">
                                <i class="fa fa-search"></i> Search
                                </button>
                            </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- jQuery -->
<script
  src="https://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
    function create_message_div($original_word, $ajax_data){
        $html_data = "<div><p><b>Search Term: </b><i>"+$original_word+"</i></p>";
        $html_data += "<p><b>Result: </b><i>"+$ajax_data+"</i></p>";    
        $html_data += "<hr/></div>";
        return $html_data;
    }

    function search_word(){
        $search_word_value = $("#search_word_text").val();
        $("#search_word_text").val("");
        $.ajax({
            url: '{{ url_for("show_search_result") }}',
            data: {
                "word" : $search_word_value,
            },
            type: 'POST',
            success: function(response) {
                $new_div = create_message_div($search_word_value, response);
                $("#message_area").prepend($new_div);
            },
            error: function(error) {
                console.log("Error");
            }
        });             
    }

    $("#search_btn").on("click", function () {
        search_word();
    });
    $('#search_word_text').on('keypress', function (e) {
        if(e.which === 13){
            search_word();
        }
    });
})

</script>

</body>
</html>

The output:

AJAX EXAMPLE

N.B.: I have posted the full working code to show a complete view how AJAX works with Flask. Modify it as per your requirement.

Community
  • 1
  • 1
arshovon
  • 13,270
  • 9
  • 51
  • 69
  • Many thanks for that! I can't check it out right now, but as soon as I can, I'll put it to work and see how it fits in my project. Thanks! – fallremix Oct 30 '17 at 15:22
  • it's not working as I expected :( I'll edit the main post. – fallremix Oct 30 '17 at 23:56
  • The flask Jinja 2 tags will not work in external JS. Try updating `url: '{{ url_for("show_search_result") }}',` to `url: '/show_search_result',` – arshovon Oct 31 '17 at 04:34
  • I have found multiple errors and it not possible to debug those without all files and or in pastebin. Create a github repo, upload your code and then we can debug those. Or you can try modifying my code as it is working fine. – arshovon Oct 31 '17 at 05:25
  • 1
    After doing a bunch more research, I fixed a few errors in my script and, on sucess, I can alert my result :). Now, I gotta fix the "undefined" return issue, where I'll probably need something like a callback function. I'm reading up this thread: https://stackoverflow.com/questions/4580265/jquery-ajax-return-undefined Hopefully it'll work out – fallremix Oct 31 '17 at 09:32