Abhay
Abhay

Reputation: 149

Accessing passed data through ajax call in my python script

I've been breaking my head since morning over this, but can't get it work. Basically, what I want to do is that upon clicking 'Send' in an html page, the account number (it's value in a textfield) should be sent to my python script. Now, how can I access the passed account number in my python script. I'm using django.

This is the ajax call from the html page:

$('#b2').click(function() {
    $.ajax({
        url : "../../cgi-bin/testjson.py",
        type : "post",
        datatype : "json",
        data : {
            ac_number : $("#account_number").val()
        },
        success : function(response) {
            var handle = document.getElementById("displaytext");
            handle.innerHTML += '<p> Button clicked</p>';
            handle.innerHTML += '<p> Value received is: </p>' + response.data[0];
        }
    });    
}); 

Upvotes: 0

Views: 1602

Answers (2)

RickyA
RickyA

Reputation: 16029

In django so you can access request.POST:

urls.py

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
    url(r'^testjson', 'testjson.views.testjson'),
)

views.py

from django.shortcuts import HttpResponse

def testjson(request):
    ret = "not a post"
    if request.method == 'POST':
        ret = str(request.POST)
    return HttpResponse(ret)

Upvotes: 0

mariodev
mariodev

Reputation: 15559

Inside your python file:

import sys
import cgi


sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n") 
sys.stdout.write("\n")

form = cgi.FieldStorage() 

sys.stdout.write(json.dumps({ 'data': form.getvalue('ac_number')}))

Upvotes: 2

Related Questions