Archive

Archive for the ‘javascript’ Category

Simple form submit with jQuery

November 19, 2009 5 comments

In building ajax driven apps, one of the things that you have to do is capture form submits, send them to the server, and then handle the results.  In many applications, the results are data, passed as JSON or XML or some other format that the remote service provides.  In other apps, we’re dealing with snippets of HTML that then get placed in the current page somewhere.   I want to be able to handle all forms on the pages, without needing to know in advance how many forms there are, what they are called, what’s in them, or what to do with the results.  I haven’t found a good succinct description of how to do this, so here’s mine using jQuery.  This isn’t rocket science.  Its just pulling together some of jQuery’s nice features.  There are other good ways to do this.

$(document).ready(function(){
    $("form").submit(function(){
         var thistarget = this.target;
         jQuery.ajax({
             data: $(this).serialize(),
             url: this.action,
             type: this.method,
             error: function() {
                 $(thistarget).html("<span class='error'>Failed to submit form!</span>");
             },
             success: function(results) {
                 $(thistarget).html(results);
             }
         })
         return false;
         }
    );
});

This captures all submits on all forms on the page, and uses jquery’s ajax call to post the form’s fields to the URL in the form’s action attribute, and then places the results in the element identified by the form’s target attribute.   You could easily use jQuery.post instead of ajax, and all you would lose is the error message, at least of the options I included above.  jQuery.ajax has a bunch of options, which are documented nicely here:
http://docs.jquery.com/Ajax/jQuery.ajax#options

The forms in the page look like normal forms, and don’t need any special attributes other than that we are abusing the target attribute a little to specify the target element for the results.

<form name=’myform’ id=’myform’ action=’targetURL’  target=’target element’>
First Name: <input type=’text’ name=’firstname’ id=’firstname’>
<input type=’submit’ name=’submit’ value=’Submit’>
</form>
<div id=’target element’></div>

If I submit this form, either using the Submit button or by hitting enter in the firstname field, the fields from the form (in this case just firstname) are posted to targetURL, and if the post works the results that I get back are inserted into the ‘target element’ div.  If the post fails for some reason (for example, if I get back a 404 error or something) then the “Failed to submit form!” message is inserted into the ‘target element’ div.

Note that if javascript isn’t available, the forms will still work.  We’ll just get the results in the named target window instead of having it inserted into the page.

Categories: javascript

Getting more done

May 21, 2008 Leave a comment

I was delighted to see the announcement that Zend Framework is partnering with Dojo.  Life will be easier.  I like Zend Framework.  I like Dojo (although I’ve used jQuery on some recent projects).  What could be better?  Time from idea to working solution will be shorter.  As a result, customers and users will say “Wow, how’d you do that?” and get back to working more efficiently and in ways they couldn’t before, quicker.  That’s good stuff.

Categories: javascript, PHP Tags: ,

Dynamically add fields to forms

February 15, 2008 Leave a comment

On my old site I had an example of adding fields to forms dynamically, which continued to get hits even long after I had forgotten it was there. The example looked like this:

City
Address1
ZIP
Phone Number
Name

The code looked like this:

[cc lines=”20″ lang=”html”]

function forminsertrow(theForm) {
var insertHere = document.getElementById(\’cloneme\’);
var newElement = document.getElementById(\’cloneme\’).cloneNode(true);
insertHere.parentNode.insertBefore(newElement, insertHere);
}

Search For:

City
Address1
ZIP
Phone Number
Name

[/cc]

This leaves you with kind of an ugly array that looks something like this:
[cc lang=”php”]
$_REQUEST[‘search’][0][‘field’] = ‘address:city’;
$_REQUEST[‘search’][0][‘value’] = ‘Phoenix’;
$_REQUEST[‘search’][1][‘field’] = ‘name:full’;
$_REQUEST[‘search’][1][‘value’] = ‘David’;
[/cc]
You generally need to do something with this to make it more usable. A loop like this one transforms it into a more nicely formatted array:

[cc lang=’php’]
foreach($_REQUEST[‘search’] as $key => $value){
$search[$value[‘field’]] = $value[‘value’];
}
[/cc]
I have used this approach quite successfully, and visitors seem to find it easy to work with. If I was doing this now, I would probably use a javascript library to do the clone part. For example, with jQuery, you don’t need the function at all. Just change the onclick on the button to this:
[cc lang=’javascript’]onclick=’$(“#cloneme”).clone().appendTo(“#cloneme”);'[/cc]
In fact, that’s what the working example above actually does.

Categories: javascript