113

Im trying to submit a HTML form using AJAX using this example.

My HTML code:

<form id="formoid" action="studentFormInsert.php" title="" method="post">
    <div>
        <label class="title">First Name</label>
        <input type="text" id="name" name="name" >
    </div>
    <div>
        <label class="title">Name</label>
        <input type="text" id="name2" name="name2" >
    </div>
    <div>
        <input type="submit" id="submitButton"  name="submitButton" value="Submit">
    </div>
</form>

My script:

<script type="text/javascript">
    $(document).ready(function() { 
        $('#formoid').ajaxForm(function() { 
            alert("Thank you for your comment!"); 
        }); 
    });
</script>

This is not working, I'm not even getting the alert message and when I submit I don't want to redirect to another page, I just want to show the alert message.

Is there a simple way of doing it?

PS: I have several fields, I have just put two as an example.

ʇolɐǝz ǝɥʇ qoq
  • 770
  • 1
  • 13
  • 28
Oliveira
  • 1,289
  • 2
  • 11
  • 14
  • can u not do away with the "form" html component? and use jquery to post on come button's click handler – gawkface Sep 19 '18 at 07:21

3 Answers3

190

Quick Description of AJAX

AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.

Really quickly there are 4 general web actions GET, POST, PUT, and DELETE; these directly correspond with SELECT/Retreiving DATA, INSERTING DATA, UPDATING/UPSERTING DATA, and DELETING DATA. A default HTML/ASP.Net webform/PHP/Python or any other form action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax.

My code specifically for you (described in code comments):

/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post with element id name and name2*/
  var posting = $.post(url, {
    name: $('#name').val(),
    name2: $('#name2').val()
  });

  /* Alerts the results */
  posting.done(function(data) {
    $('#result').text('success');
  });
  posting.fail(function() {
    $('#result').text('failed');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formoid" action="studentFormInsert.php" title="" method="post">
  <div>
    <label class="title">First Name</label>
    <input type="text" id="name" name="name">
  </div>
  <div>
    <label class="title">Last Name</label>
    <input type="text" id="name2" name="name2">
  </div>
  <div>
    <input type="submit" id="submitButton" name="submitButton" value="Submit">
  </div>
</form>

<div id="result"></div>

Documentation

From jQuery website $.post documentation.

Example: Send form data using ajax requests

$.post("test.php", $("#testform").serialize());

Example: Post a form using ajax and put results in a div

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form action="/" id="searchForm">
            <input type="text" name="s" placeholder="Search..." />
            <input type="submit" value="Search" />
        </form>
        <!-- the result of the search will be rendered inside this div -->
        <div id="result"></div>
        <script>
            /* attach a submit handler to the form */
            $("#searchForm").submit(function(event) {

                /* stop form from submitting normally */
                event.preventDefault();

                /* get some values from elements on the page: */
                var $form = $(this),
                    term = $form.find('input[name="s"]').val(),
                    url = $form.attr('action');

                /* Send the data using post */
                var posting = $.post(url, {
                    s: term
                });

                /* Put the results in a div */
                posting.done(function(data) {
                    var content = $(data).find('#content');
                    $("#result").empty().append(content);
                });
            });
        </script>
    </body>
</html>

Important Note

Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)

abc123
  • 16,261
  • 6
  • 46
  • 76
  • @abc123 how can I set Authorization request header in this ? I tried `beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "*****"); xhr.setRequestHeader("contentType", "application/json;charset=UTF-8"); },` But this does not set any header – mahendra kawde Oct 05 '15 at 06:52
  • @mahendrakawde you would need to utilize `$.ajax` which I can write an example of if you'd like but that is really a separate question – abc123 Oct 06 '15 at 12:59
  • @abc123 i do have thread initiated for that. let me share it with you. – mahendra kawde Oct 06 '15 at 13:01
  • @abc123 please see this http://stackoverflow.com/questions/32943042/basic-authentication-using-jquery-ajax – mahendra kawde Oct 06 '15 at 13:02
  • What if the POST request url is a different url? I notice they use studentFormInsert.php in action.. So if i wanna use http://localhost:3000/, I assume we should use http://localhost:3000/ in the action, but it doesn't work.. Pls help! – munmunbb Mar 15 '17 at 20:09
  • @WendyMunmunWang you need to point it to your actually service endpoint (the page that has the method you are calling). Normally localhost:3000 wouldn't be the endpoint it is the domain...you would need `localhost:3000/myEndpoint` so: `
    ` You also don't need localhost:3000 unless it isn't the domain that the javascript is being served on. Since this seems more appropriate to a chat...chat room is http://chat.stackoverflow.com/rooms/138238/wendymunmunwang
    – abc123 Mar 16 '17 at 15:03
  • 1
    can we avoid using form post at all and simply do jquery post on a button's (which is an html button not part of any form div) click handler. This way event.preventdefault wont be needed either? – gawkface Sep 19 '18 at 07:24
  • 1
    @harshvchawla of course, but then your select query for the variables pulled from the html element is different – abc123 Sep 25 '18 at 20:20
28
var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })
Varun S
  • 331
  • 2
  • 7
  • 1
    success/complete function will happen when the call is completed and it receives a 200 OK from the server – Varun S May 01 '13 at 18:00
  • hi i put: $(document).ready(function () { $('#formoid').submit(function () { var postData = "text"; $.ajax({ type: "post", url: "url", data: postData, contentType: "studentFormInsert.php", success: function(responseData, textStatus, jqXHR) { alert("data saved") }, error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); } }) }); its not working actually.. any modification on php side is needed? – Oliveira May 01 '13 at 18:23
  • 4
    good example and well written, please post some answer with it though not just example code with no explanation. – abc123 May 01 '13 at 18:23
  • 2
    I don't get how to connect that with the form I wish to post – Piotr Kamoda Mar 30 '17 at 12:31
  • Why is there no explanation? – Rich Feb 01 '18 at 21:26
  • This use of success is not deprecated https://stackoverflow.com/questions/15821141/deprecation-of-success-parameter-in-jquery-ajax – drooh Dec 04 '18 at 21:00
3

If you add:

jquery.form.min.js

You can simply do this:

<script>
$('#myform').ajaxForm(function(response) {
  alert(response);
});

// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>

NOTE:

You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.

Community
  • 1
  • 1
Martin Zvarík
  • 1,232
  • 13
  • 23