3

I do a jQuery ajax POST which successfully delivers the correct data to the server. After the POST is complete, the browser has redirected to the post url page... which I don't want. Neither of the alerts occur. The POST data has arrived at the server just fine.

i.e. after the ajax is performed within a page at http://myDomain/myPage.html as shown below, the browser address bar shows http://myDomain:39991/updateEnabled and no alerts have happened.

   var enabledAjax = $.ajax({
        url: 'http://myDomain:39991/updateEnabled',
        method: 'POST',
        data: $('#enabledForm').serialize(),
        dataType: 'jsonp'
    });
    enabledAjax.done(function (msg) {
        alert('done')
    })
    enabledStatus.fail(function (jqXHR, textStatus) {
        alert('textStatus');
    })

In express, i have router.post('/updateEnabled', urlEncodedParser, updEnab);

Within updEnab all I do at the moment is a console.log of req.body and res.end()

I've tried a 'success' method within the ajax params but that doesn't work either. What am I doing wrong that is causing the redirect to the POST url?

RoyHB
  • 1,715
  • 1
  • 22
  • 38
  • Use `event.preventDefault()` or `return false;` to stop redirection – Tushar Jun 09 '15 at 07:06
  • How do you trigger your code? From the id `#enabledForm` I think you're most probably clicking on a button inside a form, which fires the form's action. – Jack Jun 09 '15 at 07:09

2 Answers2

2

hello when you submit form this is submitting normally so you need to use this.

event.preventDefault()

this will stop stop normal submitting of form.

Aabid
  • 953
  • 5
  • 23
  • 2
    I upvoted this answer because it led me to http://stackoverflow.com/questions/20352799/ajax-form-submit-with-preventdefaultusing where I figured out where event was coming from. It stops the unwanted redirects but now the ajax is failing, I'll post a new question with the updated code that doesn't redirect but also doesn't work :-) – RoyHB Jun 09 '15 at 07:57
1

To stop the redirection you can use the return statement like this:

 enabledAjax.done(function (msg) {
    return false;
})
Sudhanshu Saxena
  • 1,199
  • 12
  • 32