Advertisement
AGE1985

ajax_form.js

Dec 24th, 2014
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. $('form').submit(function() {
  2. var valuesToSubmit = $(this).serialize();
  3. $.ajax({
  4. type: "POST",
  5. url: $(this).attr('action'), //sumbits it to the given url of the form
  6. data: valuesToSubmit,
  7. dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
  8. }).success(function(json){
  9. //act on result.
  10. alert('Hello world');
  11. });
  12. return false; // prevents normal behaviour
  13. alert('False');
  14. });
  15.  
  16. $('#form').on('ajax:success', function(event, data, status, xhr) {
  17. alert('hello world');
  18. });
  19.  
  20.  
  21.  
  22. $(document).ready(function(){
  23.  
  24. $(document).bind('ajaxError', 'form', function(event, jqxhr, settings, exception){
  25.  
  26. // note: jqxhr.responseJSON undefined, parsing responseText instead
  27. $(event.data).render_form_errors( $.parseJSON(jqxhr.responseText) );
  28.  
  29. });
  30.  
  31. });
  32.  
  33. (function($) {
  34.  
  35. $.fn.modal_success = function(){
  36. // close modal
  37. this.modal('hide');
  38. alert('hello world');
  39. // clear form input elements
  40. // todo/note: handle textarea, select, etc
  41. this.find('form input[type="text"]').val('');
  42.  
  43. // clear error state
  44. this.clear_previous_errors();
  45. };
  46.  
  47. $.fn.render_form_errors = function(errors){
  48.  
  49. $form = this;
  50. this.clear_previous_errors();
  51. model = this.data('model');
  52.  
  53. // show error messages in input form-group help-block
  54. $.each(errors, function(field, messages){
  55. $input = $('input[name="' + model + '[' + field + ']"]');
  56. $input.closest('.form-group').addClass('has-error').find('.help-block').html( messages.join(' & ') );
  57. });
  58.  
  59. };
  60.  
  61. $.fn.clear_previous_errors = function(){
  62. $('.form-group.has-error', this).each(function(){
  63. $('.help-block', $(this)).html('');
  64. $(this).removeClass('has-error');
  65. });
  66. }
  67.  
  68. }(jQuery));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement