anraT
anraT

Reputation: 543

Send object from view to function controller in Web2py

I trying to send un object from a view to controller (Web2py) in the same way that:

How to pass a JSON object to web2py using JQuery Ajax

The ajax part is:

var testObject = {};
testObject.value1 = "value1value!";
testObject.value2 = "value2value!";

var DTO = { 'testObject' : testObject };

var data = $.toJSON(DTO);    //Using the toJSON plugin by Mark Gibson

 $.ajax({
    type: 'POST',
    url: '/Myapplication/controllers/jsontest.json',
    contentType: "application/json; charset=utf-8", 
    data: data,
    dataType: 'json',
success:  function(data){  alert('yay'); }
});

and the function jsontest is in /Myapplication/controllers/default.py I have

def jsontest():
   import gluon.contrib.simplejson
   data = gluon.contrib.simplejson.loads(request.body.read())
   return dict()

Doing the same test I got a good string in var data = $.toJSON(DTO); .I got the json.js in https://sites.google.com/site/jollytoad/json.js?attredirects=0

but nothing is transmited to the jsontest function. Can anyone explain me what is wrong? I thing my url could be bad ... etc Thanks for the answer...

Upvotes: 1

Views: 1470

Answers (1)

Anthony
Anthony

Reputation: 25536

url: '/Myapplication/controllers/jsontest.json'

The above is not a valid web2py URL ("controllers" is the name of the folder that holds the controller files, but it does not appear in the URL). The correct URL would be:

url: '/Myapplication/default/jsontest.json'

If the Javascript is in a web2py view file (rather than a separate .js file), then the preferred way to generate the URL is via the URL() function:

url: '{{=URL('default', 'jsontest.json')}}'

For more details, see the book sections on dispatching and the URL() function.

Note, your code assumes either the existence of a /views/default/jsontest.json view file or that you have enabled the generic.json view (see here for more details). However, the jsontest() function doesn't actually return anything to the view or do anything with the JSON data.

Upvotes: 2

Related Questions