tags:

views:

235

answers:

4

Hi,

Could someone provide me with the most simple code for form submission with jquery. On the web is with all sorts of gizmo coding.

Thanks in advance Dave

+1  A: 
$('#your_form_id').submit(function(){
  var dataString = $("#your_form_id").serialize();

  $.ajax({  
    type: "POST",  
    url: "submit.php",  
    data: dataString,  
    success: function() {  
      alert('Sent!');
    }  
  });

  return false;
});
Joel L
right, I want to return a value from the submit.php once the sql query is executed. like I am adding a comment to your answer
dave
@dave: See this question on how to do that: http://stackoverflow.com/questions/388436/jquery-ajax-return-value
DR
The success function is given the parameters (data, textStatus). You can behave according to the received data in the success fucnction.
ondra
A: 

What you want is jquery form plugin. It allows you to simply send normal 'form' using ajax - you can make a non-visible form and use this plugin to subnmit it. The option in Joel's answer is possible as well, it depends on the complexity of the thing you want to submit.

ondra
true, I will be adding stuffs. Does it work out to be the same as adding a comment to your answer?
dave
Yes, it does - I am not sure if stackoverflow uses the form plugin in particular though :)
ondra
A: 

Take a look at the Form plugin:

$(function() {
    $('#myForm').ajaxForm(function() { 
        alert("Thank you for your comment!"); 
    }); 
});
Darin Dimitrov
+1  A: 

here is a another solution, not as simple as the Jquery Form Plugin, but it can be useful if you want to handle errors codes and messages by yourself

look at this HTML + Javascript sample :

    <div>
      <form method="post" id="fm-form" action ="">
      <label>Name:</label>
          <input type="text" id="fm-name" name="fm-name" value="" />
          <label>Email:</label>
          <input type="text" id="fm-email" name="fm-email" value="" />
          <label>Birthdate:</label>
          <input type="text" id="fm-birthdate" name="fm-birthdate" value="" />

          <input type="submit" id="fm-submit" value="Save it">
      </form>
    </div>


<script type="text/javascript">
$(function() {

  // disable the form submission
  $("#fm-form").submit(function () { return false; });

  // post the datas to "submit_form.php"
  $("#fm-submit").click(function() {
  $.post("/ajax/submit_form.php",
      { 'fm-name':$("#fm-name").val(),
      'fm-email':$("#fm-email").val(),
      'fm-birthdate':$("#fm-birthdate").val()
      }
      ,function(xml) {
        // submit_form.php will return an XML or JSON document
      // check it for potential errors
      });
  });

});
</script>
Guillaume Boschini