Guest User

Untitled

a guest
Oct 18th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. /* HTML: */
  2.  
  3. <form id="foo">
  4. <label for="bar">A bar</label>
  5. <input id="bar" name="bar" type="text" value="" />
  6.  
  7. <input type="submit" value="Send" />
  8. </form>
  9.  
  10. /* JQuery: */
  11. /**** Method 1 *****/
  12.  
  13. // Variable to hold request
  14. var request;
  15.  
  16. // Bind to the submit event of our form
  17. $("#foo").submit(function(event){
  18.  
  19. // Prevent default posting of form - put here to work in case of errors
  20. event.preventDefault();
  21.  
  22. // Abort any pending request
  23. if (request) {
  24. request.abort();
  25. }
  26. // setup some local variables
  27. var $form = $(this);
  28.  
  29. // Let's select and cache all the fields
  30. var $inputs = $form.find("input, select, button, textarea");
  31.  
  32. // Serialize the data in the form
  33. var serializedData = $form.serialize();
  34.  
  35. // Let's disable the inputs for the duration of the Ajax request.
  36. // Note: we disable elements AFTER the form data has been serialized.
  37. // Disabled form elements will not be serialized.
  38. $inputs.prop("disabled", true);
  39.  
  40. // Fire off the request to /form.php
  41. request = $.ajax({
  42. url: "/form.php",
  43. type: "post",
  44. data: serializedData
  45. });
  46.  
  47. // Callback handler that will be called on success
  48. request.done(function (response, textStatus, jqXHR){
  49. // Log a message to the console
  50. console.log("Hooray, it worked!");
  51. });
  52.  
  53. // Callback handler that will be called on failure
  54. request.fail(function (jqXHR, textStatus, errorThrown){
  55. // Log the error to the console
  56. console.error(
  57. "The following error occurred: "+
  58. textStatus, errorThrown
  59. );
  60. });
  61.  
  62. // Callback handler that will be called regardless
  63. // if the request failed or succeeded
  64. request.always(function () {
  65. // Reenable the inputs
  66. $inputs.prop("disabled", false);
  67. });
  68.  
  69. });
  70. /*****************/
Add Comment
Please, Sign In to add comment