Search code examples
pythonajaxpyramid

post data to view using ajax


I have a template 'mytemplae.pt':

function do_option_ajax() {

               var address = document.getElementById('url').value;
               $.ajax({
                   type: "POST",
                   url: "url_option",
                   data: JSON.stringify({url: $(address)}),
                   contentType: 'application/json; charset=utf-8',
                   dataType: 'json',
                   error: function () {
                       alert('error')
                   },
                   success: function (data) {
                       alert('Success');
                   }
               })
           }


<form method="post" action="index">
  <input type="url " name="url" id='url' size="100">
    <button id="2" formaction="url_option" onclick="do_option_ajax()">Confirm</button>
</form>

in .py file:

config.add_route('option', '/url_option')
@view_config(route_name='option', renderer='json', request_method='POST')
def option(request):
    url = request.params['url']
    # do something and create json_result
    return json_result

with these I want to send back json_result to the view and do something with it, but it returns an empty view with jsob obect printed: enter image description here


Solution

  • You need to prevent the default form action from firing in Javascript. At the moment your onclick handler is invoked and a millisecond later the standard HTML form submit kicks in. The standard form submit receives the data from the server and displays it as a new page.

    To prevent this you need to do something like

    <form id="myform">
      <input type="url " name="url" id='url' size="100">
        <button id="2">Confirm</button>
    </form>
    
    
    $("#myform").on('submit', function (e) {
    
        var address = document.getElementById('url').value;
        $.ajax({
            type: "POST",
            url: "url_option",
            data: JSON.stringify({url: $(address)}),
            ...
        });
        e.preventDefault();
    });
    

    Note that I'm listening for the form submit event, not the button click, and also I removed action and method attributes from the form as they only do harm in this case.