jquery.iframe-post-form.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * jQuery plugin for posting form including file inputs.
  3. *
  4. * Copyright (c) 2010 - 2011 Ewen Elder
  5. *
  6. * Licensed under the MIT and GPL licenses:
  7. * http://www.opensource.org/licenses/mit-license.php
  8. * http://www.gnu.org/licenses/gpl.html
  9. *
  10. * @author: Ewen Elder <ewen at jainaewen dot com> <glomainn at yahoo dot co dot uk>
  11. * @version: 1.1.1 (2011-07-29)
  12. **/
  13. (function ($)
  14. {
  15. $.fn.iframePostForm = function (options)
  16. {
  17. var response,
  18. returnReponse,
  19. element,
  20. status = true,
  21. iframe;
  22. options = $.extend({}, $.fn.iframePostForm.defaults, options);
  23. // Add the iframe.
  24. if (!$('#' + options.iframeID).length)
  25. {
  26. $('body').append('<iframe id="' + options.iframeID + '" name="' + options.iframeID + '" style="display:none" />');
  27. }
  28. return $(this).each(function ()
  29. {
  30. element = $(this);
  31. // Target the iframe.
  32. element.attr('target', options.iframeID);
  33. // Submit listener.
  34. element.submit(function ()
  35. {
  36. // If status is false then abort.
  37. status = options.post.apply(this);
  38. if (status === false)
  39. {
  40. return status;
  41. }
  42. iframe = $('#' + options.iframeID).load(function ()
  43. {
  44. response = iframe.contents().find('body');
  45. if (options.json)
  46. {
  47. returnReponse = $.parseJSON(response.html());
  48. }
  49. else
  50. {
  51. returnReponse = response.html();
  52. }
  53. options.complete.apply(this, [returnReponse]);
  54. iframe.unbind('load');
  55. setTimeout(function ()
  56. {
  57. response.html('');
  58. }, 1);
  59. });
  60. });
  61. });
  62. };
  63. $.fn.iframePostForm.defaults =
  64. {
  65. iframeID : 'iframe-post-form', // Iframe ID.
  66. json : false, // Parse server response as a json object.
  67. post : function () {}, // Form onsubmit.
  68. complete : function (response) {} // After response from the server has been received.
  69. };
  70. })(jQuery);