I
I
IgFil2020-05-27 08:07:15
Python
IgFil, 2020-05-27 08:07:15

Why does js not see the response to the ajax request?

My server returns a response to an xhr request, but the xhr.responseText function does not receive a response from the server.
The response from the server comes in HTML format.

<script language="JavaScript">
            window.onload = function(){
                var inp_message = document.querySelector('input[name=message_inp]');
                document.querySelector('#go').onclick = function() {
                var params = 'message=' + inp_message.value;
                ajaxPost(params, "cgi-bin/message_input.py");
                }
            }
            function ajaxPost(params, action){
            var xhr = new XMLHttpRequest();
            xhr.open("POST", action, true);
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(params);
            output = xhr.responseText;
            return output;
            }
            window.setInterval(function(){
                var id_message = document.querySelector('p:first-child');
                var params = 'id=' + id_message.id;
                builder = ajaxPost(params, "cgi-bin/message_output.py");
                console.log(builder);
                //document.querySelector('#text_holder').innerHTML = builder;




            }
            ,10000);
        </script>

#!/usr/bin/env python
import cgi
import sqlite3
form = cgi.FieldStorage()
id = form.getfirst("id")
conn = sqlite3.connect("chat_database.db")
cursor = conn.cursor()
messages = cursor.execute("SELECT * FROM chat WHERE id > ?", (id, ))
conn.commit()
print("Content-type: text/html\n")
if messages != "":
    for message in messages:
        print("<p id="+str(message[0])+">"+"Test"+"</p>")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
smilingcheater, 2020-05-27
@IgFil

XHR is an asynchronous request. You can get a response from the server on events. Read https://learn.javascript.ru/xmlhttprequest , everything is there.

R
Rais, 2020-05-27
@0pauc0

How are you handling the cursor?
For the first time I see that the result from cursor.execute is immediately driven as a list.
After cursor.execute we usually take the result with cursor.fetchall().
Or does the same way work for you?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question