1

I have a PHP website, which has a lot of forms that goes to certain pages on submit. So they look like this:

<form method='post' action='form_target.php'>
    <input type='text' name='fieldname' />
    <button type='submit'/>
</form>

I guess the same thing can be done with $.post('form-target.php');, without actually leaving the page. But I'm trying to prevent writing JavaScript code for a lot of different forms.

So is there a simple way to detect forms on the page, and convert them to AJAX calls? Maybe by bind onsubmit() , or onclick(); events to a $.post(); call?

Any help to implement this will also be appreciated.

Bpainter
  • 130
  • 3
  • 16
jeff
  • 11,519
  • 28
  • 67
  • 126

4 Answers4

4

You can attach the .submit event to all forms to catch the submission, then use .preventDefault() on the event object to prevent actual page submission (stop it from changing page). Then serialize the form's data (make a name-value paired string), get the url from the action attribute of the form element and then call jquery's ajax function

using $("form") with nothing else as part of the selector will attach this to all forms on the page

HTML

<form method='post' action='form_target.php'>
    <input type='text' name='fieldname' />
    <button type='submit'/>
</form>

JAVASCRIPT

$("form").submit(function(e){
    e.preventDefault();
    var data = $(this).serialize();
    var url = $(this).attr("action");
    $.ajax({
       url:url,
       type:"POST",
       data:data,
       success:function(){
          //do something when post succedes 
       },
       error:function() {
          // do something when it fails
       }
    });
});

JQuery .ajax

JQuery .serialize

JQuery .submit

To further extend this you could make it so each form executes a specific success method, this would help in the case that you need something specific to happen for a specific form submission.

First give each form a data-* attribute that we can later use in the submit event to trigger a specific function for that form.

<form method='post' action='form_target.php' 
                    data-onerror="nameSubmitError" 
                    data-onsuccess="nameSubmitSuccess">

Then create the two functions that we named in the data-* attributes

function nameSubmitError() {
  //Do some code that will handle the error
}

function nameSubmitSuccess() {
  //Do some code that will handle the success
}

And in the .submit event

$("form").submit(function(e){
    e.preventDefault();
    var data = $(this).serialize();
    var url = $(this).attr("action");
    var errorCallback = $(this).data("onerror");
    var successCallback = $(this).data("onsuccess");
    $.ajax({
       url:url,
       type:"POST",
       success:function(){
          //Check that we have a defined function before trying to execute it
          if( typeof(window[successCallback]) == "function" ) {
             //We do have a defined function so execute it
             window[successCallback]();
          }
       },
       error:function() {
          //Check that we have a defined function before trying to execute it
          if( typeof(window[errorCallback]) == "function" ) {
             //We do have a defined function so execute it
             window[errorCallback]();
          }
       }
    });
});

Of course putting all the callback functions in the global space would pollute it so you could setup all the functions into a single object and use the objects name instead of window

var formCallbacks = {
    nameSubmitError:function() {
      //Do some code that will handle the error
    },
    nameSubmitSuccess: function() {
      //Do some code that will handle the success
    }
};

And in the .submit event change window to formCallbacks

//window[errorCallback]();
//Becomes 
formCallbacks[errorCallback]();
Patrick Evans
  • 38,456
  • 6
  • 62
  • 84
  • wow, how did you style those links at the end? – jeff Sep 23 '13 at 20:26
  • 1
    `` around the links – Patrick Evans Sep 23 '13 at 20:26
  • I tried your solution, (after loading jquery) console does not show any errors but forms still submit by going to the page. success and error functions are not called either. It's like I haven't added the script at all. Should I write this script after the forms ? **Edit** : I wrapped your code in `$document.ready(function(){});` now it works but gives an error. I will try to fix it :) Thanks for your help! And thanks to all the other answers. – jeff Sep 23 '13 at 20:36
  • Oh, I have added `data:data,` after `type:"POST",`, now it completely works :) Thank you again ! – jeff Sep 23 '13 at 20:47
  • Yea forgot to add the data option sorry, edited to correct, and also added how you can extend this so you can execute specific callbacks for each form. – Patrick Evans Sep 23 '13 at 20:50
  • I find all those form attributes unnecessary. It makes the unobtrusive script intrusive, one of the things I dislike about DOJO. Just have the callbacks defined in code and you will be fine. – mplungjan Sep 24 '13 at 04:19
1

Yes, you can try http://malsup.com/jquery/form/ , this is very simple to use..

<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
    <script src="http://malsup.github.com/jquery.form.js"></script> 
    <script> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
            // bind 'myForm' and provide a simple callback function 
            $('#myForm').ajaxForm(function() { 
                alert("Thank you for your submit!"); 
            }); 
        }); 
    </script> 
</head>
<body>
    <form id="myForm" method='post' action='form_target.php'>
       <input type='text' name='fieldname' />
       <button type='submit'/>
    </form>
</body>
</html>
amilkcar
  • 21
  • 2
0

http://api.jquery.com/submit/

$( "form" ).on( "submit", function( event ) {
    // Your AJAX call
}
conrad10781
  • 2,084
  • 16
  • 17
0

You can do it like this:

$('form').on('submit', function() {
  $.post(
    $(this).prop('action'), // Your url action
    $(this).serialize(),    // Your data
    success: function() {   // Your callback function
      alert('Submitted');
    }
  );
});
MurifoX
  • 14,374
  • 3
  • 34
  • 59
  • 1
    dont forget to `preventDefault` or `return false` to prevent the page from changing – Patrick Evans Sep 23 '13 at 20:26
  • @PatrickEvans yes I was gonna ask that. And what is prop? Can I use `attr()` instead of it ? and moreover, will it convert "form_target" to "http://mysite.com/form_target" ? – jeff Sep 23 '13 at 20:27
  • and this gives the error: Uncaught SyntaxError: Unexpected token : – jeff Sep 23 '13 at 20:33