views:

132

answers:

4

I have this swf (flash) file that provides the json that needs to be sent to the server.

I wrote a very simple jQuery:

function submitForm(swf_json) {
$('#swfjson').val(swf_json); #swfjson is an input of type hidden
$('#titleForm').submit();
}

and the swf will call the submitForm above and I receive the request.POST in django as usual.

But, django is interpreting the swf_json as a string "Object object"

    >>>type(request.POST['swfjson'])
    <type 'unicode'>

Of course I can pass the json as a string to the view function. Doesn't seem good to me. Any other way of passing the json object to the django view?

+1  A: 

Try jQuery function post

$.post("your/url/", 
       {"id":id}, 
       function(data){},
       "json");
Dingo
I don't think this will solve the problem since it will still send a json object.
Goose Bumper
+1  A: 

Of course django sees the string "Object object". That's excatly what jQuery writes into the input field. And what subsequently gets submitted. (Demo)

The swf_json parameter is an object to javascript. If you want to submit it as string I suggest slightly modifying the swf so that it passes a string to your function instead of an json object. Assuming you construct your json via string concatenation just add extra quotation marks at the end and beginning before calling submitForm

Instead of

{
  "firstName": "John",
  "lastName": "Smith"
} //json object

try this

'{
  "firstName": "John",
  "lastName": "Smith"
}' //string

If I remember correctly http://www.json.org/json2.js allows conversion between json and strings

jitter
Thanks, Thats what I thought. Simple to just pass the string around. But I receive a json from the swf, how do I in the javascript convert it into a string.
Lakshman Prasad
check expanded answer (at end)
jitter
Very nice answer.
Goose Bumper
A: 

As an alternative to jitter's answer, why not simply parse the json object using Python's json library. This way you don't need to parse through the string manually. As an added bonus it's more future-proof in case your client decides to pass more than one value through the json object.

Goose Bumper
setting an input value and submitting that form is simpler than using an ajax post. This way impedes my development as I cant create a json object in a python test.
Lakshman Prasad
+1  A: 

You must first "serialize" your JavaScript object into a JSON string using a library such as http://json.org/json2.js (there is no appropriate function built into JQuery.)

Tom