parth pahariya parth pahariya - 4 years ago 190
Javascript Question

posting form by jquery not working

Basically i have submitted the form data by using jquery event in order to prevent page reload. Now , the informations of the form are not being displayed?



$("#btn-ser1").click(function() {
$("#form").submit(function() {
alert("you are submitting" + $(this).serialize());
});
});

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<body>
<form method="post" id="form">
First Name :
<input name="fname">Last Name :
<input name="lname">Address :
<input name="address">Contact No. :
<input name="contact">Country:
<input name="country">City:
<input name="city">
</form>
<button type="button" id="btn-ser1">Serialize</button>
</body>

</html>




Answer Source

You aren't submitting, neither preventing the default action. You need:

$("#btn-ser1").click(function () {
  // remove this event handler                                                « #1
  // $("#form").submit(function (e) {
    // prevent refresh or default action                                      « #2
    e.preventDefault();
    // change $(this) to $("#form") as you are binding it to the button, not the form.
    alert("you are submitting" + $("#form").serialize());
    // submit to the server                                                   « #3
    $.post("path/to/post", $("#form").serialize());
  // });
});

You forgot to do the #1, #2 and #3 as mentioned.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download