javascriptpythonajaxmod-python

Ajax load issues with space in url


I have 2 python files: gui.py & index.py

python.py contains table with records from mysql database.

gui.py contains python.py and textfield with button to send messages.

Also, gui.py contains javascript that will load new python.py with parameters.

gui.py script

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#content").load("http://localhost/index.py");
    $("button").click(function(){
        var url = "http://localhost/index.py?name=1&message=";
        var msg = document.getElementById("message").value;
        var res = url.concat(msg);
        alert(res); //here I always can understand that result URL is okay.
        $("#content").load(res);
    });
</script>

And index.py part

cursor.execute("INSERT INTO `messages` (`sender`, `receiver`, `text`, `time`) VALUES ('" + req.form['name'] + "', '3', '" + req.form['message'] + "', now())")
});

Where req is from def index(req): I am using mod_python.

So, the problem is - when i try to send message with space is in - my table disappears (till next page refresh (but i don't need to refresh it without spaces, ajax load works good here)). And then I will see only the first word of the message. As you can see in my code, i have alert(res); if I copy that alert and just run that url - spaces works nicely.

Some details

I am using ubuntu 14.04, apache2, mod_python, python 2.7, mysql database, python-MySQLdb.


Solution

  • You should URL encode the message body to protect against special characters in the URL, like, say, space. If you did

    var msg = encodeURIComponent( document.getElementById("message").value );
    

    You may have better success.