Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Oct 2014
    Location
    California
    Posts
    140
    Thanks
    1
    Thanked 26 Times in 26 Posts

    Generic, Simple Form Processing with jQuery

    AJAX Form Processing

    This is a useful little script that deals with a common theme I see in user's questions regarding forms and AJAX.

    Features:

    • Automatically converts Form Inputs into POST Variables

    • Paste and Forget, additional Scripts are entirely optional.

    • HTML Compliant: It works with a regular HTML form without weird/special syntax.

    Requirements:

    • jQuery - AJAX and Event Binding is just nicer/easier with jQuery but it wouldn't be hard to create a plain JS version.

    • HTML5 Compatible Browser - I can't guarantee this works right in IE8 or older.

    How to Use:

    • Build an HTML form like you normally would using HTML5 Standards.

    • Always give inputs that should be included in your AJAX post with a name attribute.

    • Use the action attribute to point to your API/PHP File/etc.

    • Specify a callback function by adding a data-callback attribute to the form:

    PHP Code:
    <form action='formhandler.php' data-callback='myCustomFunction'
    • Create your callback in the window namespace:

    PHP Code:
    <script>
    window.myCustomFunction = function (result) {
        
    // Do something with your AJAX result!
    };
    </script> 
    Alternatively use the jQuery on event handler, it should expect an event called "FormHandled.FormId" where "FormId" is the id attribute of your form; so assuming the form's id attribute is MyForm:

    PHP Code:
    <script>
    $(
    document).on("FormHandled.MyForm", function(eresult) {
            
    // Do something with your AJAX result! 
           // Don't forget, the first parameter is always the Event Object. 
    });
    </script> 
    That's nice because you don't have to use the data-callback attribute which could confuse people looking at the markup but also because it means your markup isn't specifying what function it points to and you can have multiple handlers reacting to the same event. This is probably how I would suggest using the form but I added both options for convenience.

    The Script (Place at the bottom of your page):

    PHP Code:
    <script>
    $(
    'form').submit(function (e) {

        
    e.preventDefault();

        var 
    $this = $(this);

        var 
    formAction $this.attr("action"),
            
    formCallback $this.data("callback") || false,
            
    formId $this.attr("id"),
            
    postObject = {},
            
    0,
            
    max this.children.length;

        
    // Generic serialization of form elements
        
    for (0maxi++) {
            var 
    source this.children[i];

            var 
    key source.name || false;

            if (
    key) {
                
    postObject[key] = source.value || null;
            }
        }
        
    // Use this if you're using the jQuery serializeObject Plugin: 
        // var postObject = $this.serializeObject();

        
    $.post(formActionpostObject)
            .
    done(function (result) {
                
    result.success result.success || false;

                
    // Execute the callback if it exists
                
    if (typeof window[formCallback] === typeof function () { }) {
                    
    window[formCallback](result);
                }
                
                $(
    document.body).trigger("FormHandled." formId, [result]);

                
    // This would allow you more freedom for where you put your callback
                // But some people don't like eval. 
                /* 
                if (typeof eval(formCallback) === typeof function () { })
                {
                    var callback = eval(formCallback);
                    callback(result);
                }
                */

            
    }).fail(function (result) {
                
    console.log("Error processesing " formId);
            }).
    always(function (result) {
                
    // Add something here if you like
            
    });
    });
    </script> 

    Hopefully that's helpful to anyone just starting out and trying to do some dynamic forms to process information asynchronously. There are commented sections in the form instructing you of places you might be interested in customizing.

    Thanks,
    -Steve

    Note: I use [php][/php] tags because it highlights the code nicely. This is all just JavaScript and HTML.

    Edit: Sorry I messed up the title and forgot about keywords; this is specifically for AJAX form requests.
    Last edited by sagebrushfire; 04-11-2015 at 01:13 PM.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,956
    Thanks
    0
    Thanked 688 Times in 677 Posts
    Quote Originally Posted by sagebrushfire View Post
    • HTML5 Compatible Browser - I can't guarantee this works right in IE8 or older.
    In which case you'd use JQuery 2.1.3 rather than JQuery 1.11.2 so as to not bother with all the extra code the earlier version has specifically for handling IE8 and earlier.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Regular Coder
    Join Date
    Oct 2014
    Location
    California
    Posts
    140
    Thanks
    1
    Thanked 26 Times in 26 Posts
    Quote Originally Posted by felgall View Post
    In which case you'd use JQuery 2.1.3 rather than JQuery 1.11.2 so as to not bother with all the extra code the earlier version has specifically for handling IE8 and earlier.
    Yeah, I actually tested out this script in IE 11 in IE8 compatibility mode and it worked just fine using jQuery 1.11.1 but IE8 is where I draw the line; it's not a good use of my time to thoroughly test my scripts for IE8 so I just say, "Use at your own risk."


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •