简体   繁体   中英

How do I submit a form without refreshing the entire page

I've looked into this some time, and all examples I've found always includes text input fields and php.

I've created a community which has a "Like-button", one click shows a higher number, click again and it drops -1, it works like a charm. But I don't like the refresh part, it messes everything up and starts at the top.

I've tried tons of Ajax/Jquery coding but can't prevent the "reload part". I don't know if I have any code to post since I never save any of the worthless codes that never works.

However, the form starts like this and includes the "submit-image":

@using (Ajax.BeginForm("Like", "Home", FormMethod.Post, null, new { id = "LikeForm" }))
{
...
<input type="image" src="../Images/star.png" name="submit" />
...
}

The result is presented in a nearby.

Everything is sent to the ActionResult Like() that saves everything in the database. The result is later presented in the View . Nothing unusual about that part I hope.

Once again, I've looked into many examples and none worked for me, my main page for information was at http://api.jquery.com/ and stackoverflow. Nothing gained in this case.

If your attempted to do it using jQuery before, I expect that your code looked something like this:

$('#LikeForm').on('submit', function() {
  // do AJAX stuff here
});

This is already close enough, just missing the part where it prevents the form from still being submitted the traditional way. If you still haven't tried so, try doing it like this:

$('#LikeForm').on('submit', function(e) {
  e.preventDefault();
  // do AJAX stuff here
});

What it does is that it prevents the default behavior of the form element (which is, to submit itself with a page reload), and just do the AJAX stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM