Friendly King
Friendly King

Reputation: 2476

Having trouble getting the data from AJAX using Python

I am having trouble retrieving the data on the server side from the AJAX using jQuery 1.9.1.

Here is my server side Pyramid code:

@view_config(route_name='ajax_contact_handler', renderer='json')
def ajax_contact_handler(request):
    contact_id = request.POST.get('contact_id', None)

    # Use contact_id to perform some DB operations

    return dict(cid=contact_id)

Here is my jQuery code:

$(document).ready(function() {

    $("#connect_button").click(function() {

        var user_id = 3; // Just for the example
        $.ajax({
            type: "POST",
            url: "/ajax_contact/",
            dataType: "json",
            data: {"contact_id": user_id},
            cache: false,
            success: function(result) {
                $('#connect_button').html("Contact Added").css("background-color","rgb(151,151,151)");
                $('#connect_button').unbind('click');
            }
        });

    });
});

On the server, I am not getting the contact_id and therefore, it is being set to the default None.

What I am doing wrong? And how do I get the contact_id parameter to use in the server code? Also, do I need to have xhr=True in my view_config decorator – when it is present, and I manually navigate to the ajax_contact page I receive a 404 (is that the expected result)?

Thanks for your help.

EDIT Some more information:

Request URL:http://localhost:8080/ajax_contact/
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:16
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:pdtb=hide; auth_tkt="52932923705e421fe29f3fec53ed7408523e1f3f1!userid_type:int"
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/user/jz/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
{"contact_id":4}:
Response Headersview source
Content-Length:13
Content-Type:application/json; charset=UTF-8
Date:Sat, 21 Sep 2013 22:40:49 GMT
Server:waitress

Upvotes: 0

Views: 1456

Answers (1)

am_
am_

Reputation: 2418

Try with data: JSON.stringify({'contact_id' : '3'}) and see if that helps.

As for xhr=True param, this is what the documentation says: This value should be either True or False. If this value is specified and is True, the WSGI environment must possess an HTTP_X_REQUESTED_WITH (aka X-Requested-With) header that has the value XMLHttpRequest for the associated view callable to be found and called. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries.

If xhr is not specified, the HTTP_X_REQUESTED_WITH HTTP header is not taken into consideration when deciding whether or not to invoke the associated view callable.

EDIT Also do you need to pass the id as JSON? It's been a while since I've worked in python/pyramid, but I think the way you try to retrieve your id now through request.POST.get('contact_id') you should try to just post it as a regular POST param instead.

So remove dataType and try data: {contact_id: '3'} in your $.ajax() call.

The reason for this is that you need a valid key in your request in order to be able to retrieve it through request.POST. request.POST also requires that your content type is set to application/x-www-form-urlencoded. If you need to retrieve JSON through request.POST add a key infront of the json ie: foo = {json here..}

Upvotes: 1

Related Questions