Submitting HTML form using Jquery AJAX

前端 未结 3 1377
闹比i
闹比i 2020-11-22 03:56

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

My HTML code:

3条回答
  •  逝去的感伤
    2020-11-22 04:40

    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  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');
      });
    });
    
    
    
      


    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

    
    
        
            
        
        
            

    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)

提交回复
热议问题