Jquery ajax with google app engine post method
Question: Just trying to learn using ajax with appengine,started with the post
method,but it does not work. This is my HTML Code for the page

    
    
        <html>
        <head>
        <title> Hello </title>
    <script  src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
    var data={"name":"Hola"};
    $(document).ready(function(){
    $('#subbut').click(function(){
    $.ajax({
    
     url: '/test',
     type: 'POST',
     data: data,
     success: function(data,status){
    
        alert("Data" + data +"status"+status);
      }
     });
     });
     });
     </script>
     </head>
     <body>
     <form method="post" action="/test">
     <input type="submit" id="subbut">
     </form>
     <div id="success"> </div>
     </body>
     </html>
    

Here goes my python code to render the above html code , its handler is /test1

    
    
    from main import *
    
    class TestH1(Handler):
          def get(self):
                  self.render('tester.html')
    

And this is the python script to which AJAX request must be sent to,handler is
/test.

    
    
        from main import * 
        import json
        class TestH(Handler):
            def post(self):
                 t=self.request.get('name')
                 output={'name':t+" duck"}
                 output=json.dumps(output)
                 self.response.out.write(output)
    

Expected behavior is that when i click on submit button,i get an alert message
saying "Hola duck" , get nothing instead. Any help would be appreciated as i
am just starting with AJAX and Jquery withGAE


Answer: At first, I suppose you should suppress default behavior of form submitting
when you press submit button by adding "return false" to the .click function.
But I suppose it would be better to use just

    
    
    <input type="button" id="subbut"> 
    

instead (even without form).

Then you should add "dataType: 'json'" to your ajax call to tell jQuery what
type of data you expect from server. Doing this you will be able to get
response data by property names like "data.name". So:

    
    
    var data={"name":"Hola"};
    $(document).ready(function(){
        $('#subbut').click(function(){
            $.ajax({
                url: '/test',
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function(data,status){
                    alert(data.name);
                    alert("Data" + data +"status"+status);
                }
           });
           return false;
        });
    });
    

and it would be better if you set appropriate content type header to your
response:

    
    
    response.headers = {'Content-Type': 'application/json; charset=utf-8'}
    self.response.out.write(output)
    

