Pistacchio
Pistacchio

Reputation: 465

Answering to ajax request from python web app

I have a python web server set up by using Flask and I'm trying to send to it an ajax request and then handle the answer.

This is the js code:

var ajaxObj = setXMLHttpRequest();

function setXMLHttpRequest(){
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else if(window.ActiveXObject){
        xhr = new ActiveXObject("Microsoft.XMLHTTP0");
    }
    return xhr;
}

function sendAjaxRequest(){
    var url = "/refresh";
    ajaxObj.open("GET", url, true);
    ajaxObj.onreadystatechange = function(){ajaxAnswerManager()}
    ajaxObj.send(null);
}

function ajaxAnswerManager(){
    if(ajaxObj.readyState == 4){
        var result = ajaxObj.responseText;
        alert(result);
    }
}

As you can see I send the request to the /refresh route, but I'm not sure what function I should define after the app.route(/refresh) on the server.py file, and most of all how to send the answer back.

I tried by defining a simple function and sending back results with both return and print, but it did not work, sometimes i get 500 internal server error and other times the alert will just print me back the page from wich the ajax request was sent.

https://i.sstatic.net/T1GGO.jpg https://i.sstatic.net/KZYaB.jpg

I looked for a solution or a tutorial on the web but I couldn't find any that suits my case (actually I only found one)

So, how can I answer to an ajax query from pyhton?

Upvotes: 0

Views: 647

Answers (1)

HarshuEdu
HarshuEdu

Reputation: 41

First of all, please start using jquery for handling AJAX requests. It is much easier to use and cleaner to work with. The above code snippet can be implemented with just the following code:

$.ajax({
  url: '/refresh',
  type: 'GET',
  success: function(response){ alert( response ); }
})

In the python script, you can do the following to return whatever you want:

@app.route('/refresh')
def refresh:
    var_you_want = 'whatever you want to return'
    return json.dumps({ 'data': var_you_want })

The 500 internal server would indicate an error in the python code itself. Also, because you are the above python code sends a json object, it is a good idea to parse it in the success function:

$.ajax({
  url: '/refresh',
  type: 'GET',
  success: function(response){ alert( JSON.parse(response) ); }
})

Upvotes: 2

Related Questions