2

I'm getting a "canceled" status whenever I do a jquery $.post(). It seems like an asynchronous problem? I access the local project with http://127.0.0.1:8933/myproject/default/index.html

index.html:

<script>
    $(document).ready(function() {
         $('#mybutton').click(function() {
                var post_url = get_url();  // resolves to "/myproject/default/process_func"
                var data = ...;
                do_action(post_url, data); 
         });
    });
</script>

<a href="" id="mybutton"> Click me! </a>

util.js:

function doPost(url, data) {
    $.post(url, data).then(doSuccess, doFail):

    function doSuccess(data) {
           alert('Successful!');
    }
    function doFail(data) {
           alert('Failed!');
    }
}

function do_action(url, data) {
    var jsondata = JSON.stringify(data);
    // some other stuffs...

    doPost(url, jsondata);
}

The idea is to post some data back to the server for processing using json data. A user will click on the anchor button, the do_action() will fire, and then it'll be posted in doPost().

This seems to work since my I'm seeing the json data passed to my processing function on the server. However, I'd see the alert message "Failed!" pop up every time even though the data has been processed. In chromium's debug panel, I see under "Network" tab that the post has a status of "(canceled)" and the entire line would be highlighted in red. The Type stated is "Pending".

I think this is an asynchronous problem, but I'm unsure how to fix it.

Bak
  • 365
  • 1
  • 4
  • 12

2 Answers2

7

Use this, to cancel the default navigatin behavior of the <a>:

$('#mybutton').click(function(e) {  // <-- Add `e` here
    e.preventDefault();  // <-- Add this line
    var post_url = get_url();
    var data = ...;
    do_action(post_url, data); 
});

I believe the AJAX request is being aborted by the browser because when clicking the link, although the request does get sent off, the link tries to navigate to a new page so the browser must abort open AJAX requests.

Ian
  • 50,146
  • 13
  • 101
  • 111
  • 1
    Thanks. That worked. I'm not familiar with javascript, but I thought the `.then()` in the `doPost()` would wait until the request was fulfilled. – Bak May 08 '13 at 15:59
  • 1
    It does, but the original action (clicking the link) doesn't. – JJJ May 08 '13 at 16:00
  • @Bak Exactly what Juhana said. The actions are completely different and separate. – Ian May 08 '13 at 16:02
0

You can try this...

$('#mybutton').live("click", function(e) {  
    e.preventDefault();
    var post_url = get_url();
    var data = ...;
    do_action(post_url, data); 
});

Depending on the version of jQuery you are using, you can use jQuery.live() or jQuery.on() method

When the e.preventDefault() method is called if this method is called, the default action of the event will not be triggered.

Resources:

heyomi
  • 385
  • 5
  • 18