0

I am trying to build a chatbot in Flask-python which needs to interact with javascript for connecting to a URL to bring the data.

I am able to send and receive strings from javascript to Python but now i am facing issue when i am trying to send JSON data from javascript to python.

I have tried multiple things like using ajax call in JS and using request.json in python but couldn't succeed.

Below is the code i am using sending strings

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    function getBotResponse(rawText) {
        $.getJSON('https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/', {q: rawText}, 
            function(jsndata) {
            var intent = jsndata.topScoringIntent.intent;
                }
                $.get("/get", { intt: intent }).done(function(data) 
                    {
                        $('<div class="botText">'+data+'</div>').insertBefore('.msg_push');
                        $('.chat_body').scrollTop($('.chat_body')[0].scrollHeight);
                    }
                );
            }
        );
    }
</script>

And below is the python code for receiving the string and return answer:

from flask import Flask, render_template, request
@app.route("/get")
def get_bot_response():
    jsondata = request.args.get('intt')
    print(type(jsondata))
    print(jsondata)

This is working fine but when i trying to send the json in the same way i am getting errors like Internal Server Error and when i tried ajax it said BAD Request.

How i can send the json data through a variable from javascript to python?

NOTE: i am familiar with using urllib request/https requests methods in python to connect to URL and get the json data but my company's policies are not allowing that so need to find some way i can send the data from javascript.

2
  • you are importing jquery twice , just remove one link and try Commented Apr 13, 2018 at 10:31
  • You can just stringify it and send it, parse it in the other end. Commented Apr 13, 2018 at 10:40

1 Answer 1

1

You'll be getting the issue because $.get(..., { intt: XXX }) is expecting a string in place of the XXX, not an object.

The easiest way to solve this is to use JSON.stringify:

{ intt: JSON.stringify(intent) }

And then parse the JSON from string in Python

The better way to do this, of course, is to POST the JSON, rather than pass it as a URL query. URL queries can have length restrictions and speed limitations.

Sign up to request clarification or add additional context in comments.

Comments

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.