kenny kenny - 2 months ago 18
HTML Question

Difference between jquery post and html form post

im searching for a while but i dont get it:

What is the different between a Jquery $.post and when i submit a normal html form with post?

My jquery code:

$.post( "/test", query , function( data ) {
console.log(data)
});


My html code:

<form method="post" action="/test" >
<input id="query" type="text" name="q" >
<input type="submit" value="Search">
</form>


Im using express and when i do the jquery post the code below wont work. The sever will just send the redirect as data and will not redirect the page. But when i use the form it will redirect the page tp /newpage. Why is that happening? Is there a way a that jquery will work the same way like the html form does?

router.post('/test', function(req, res) {
res.redirect('/newpage');
}


I see can see in chrome that jquery use type "xhr" and the form use "document" ... can i change that?

Answer

What is the different between a Jquery $.post and when i submit a normal html form with post?

For the most part, nothing. Both issue an HTTP POST request with the values from the form. One just does so in the context of the page, the other does so in an AJAX context without refreshing the page.

The sever will just send the redirect as data and will not redirect the page.

Therein lies a bit of a misunderstanding on your part. The server never redirects the browser. All the server ever does is send a header back to the browser suggesting that the browser perform a redirect.

When the browser receives that header in the context of a page loading request, it performs the redirect. When the JavaScript code receives that header in the context of an AJAX request, it ignores it. AJAX responses, by design, don't reload the page.

If you want the form post to result in a server-initiated redirect, use a normal form POST. You can still initiate this form POST from JavaScript, just not using $.post() since that's an AJAX request. Instead, you might do something like $('form').submit() or $('form input[type="submit"]').click(). It may take some tinkering.

If, on the other hand, you want to use AJAX then any conditional redirect logic in response to the completion of the AJAX request would need to be in the client-side logic.

Comments