'How to post form data via ajax to a python script?

I'm struggling with a python program and an ajax request. I'm trying to get some data from my Javascript into the python program, the normal method I've been using .getfirst(field name) doesn't work which I assume is because the request is via ajax (sorry, I'm quite new to all this) so I've tried using the following code

Python:

import MySQLdb
import cgi, cgitb

def index(req):

    # Create instance of FieldStorage
    form = cgi.FieldStorage()

    # Get data from fields
    dtbox = form.getvalue('dt')
    tmbox = form.getvalue('tm')

    con = MySQLdb.connect('localhost', 'root', '', 'mydb')

    with con:
        cur = con.cursor(MySQLdb.cursors.DictCursor)
        s = "SELECT tmp, watts FROM currentcost WHERE dt ='" + dtbox + "' and tm like '" + tmbox + "%'"
        cur.execute (s)
        rows = cur.fetchall()

        x=""
        y=""
        for row in rows:
            x=x+row["watts"]+","
            y=y+row["tmp"]+","

    x="data:["+x+"]"
    y="data:["+y+"]"

    con.close()

    req.write(x)

Javascript snippet:

function draw(handleResponse) {
    $.ajax({
        url: "/currentcost.py",
        data: {dt: frm.dt, tm: frm.tm},
        success: function(response){
            handleResponse(response);
        }
    });

<form name="frm" target="ifrm">
    <iframe name="ifrm" id="ifrm" style="display:none"></iframe>
        <fieldset style="width:300px">
            <legend>Chart Date and Time</legend>
            Alter the date and time settings <br>
            Date:
            <select name="dt">

I'm expecting the form values dt and tm to be transferred to the python program where it will pick them out and run through my select query ... all I get back is a blank :-(

Thanks in anticipation of your help

Chris



Solution 1:[1]

Your ajax call should be of type "POST", and you can serialize the fields from the form using .serialize().

$.ajax({
    url: "/currentcost.py",
    type: "POST",
    data: $("form[name='frm']").serialize(),
    success: function(response){
        handleResponse(response);
    }
});

Edit

You should not typically use GET requests for form submission. That said, the ajax GET should look like:

 $.ajax({
    url: "/currentcost.py",
    data: {dt: $("#dt").val(), tm: $("#tm").val() },
    success: function(response){
        handleResponse(response);
    }
 });

This assumes you have inserted the attribute id="dt" into the first element and id="tm" into the second element.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1