Jun5

Submit form via AJAX/jQuery

Recently i was working on www.quickko.com - internet application where photographers can present their “photo of live”. When i was implementing comment submission parts of a system, i was forced to find a nice library to send form via ajax. I am a fan of jQuery thats why i decided to use jQuery form plugin from http://www.malsup.com/jquery/form/. The way how You use it was really impressive.

first i have created a form in my html file:


<form id="submitComment" action="AddComment.do" method="post">
<input type="hidden" name="photo_id" value={$PHOTO->data.photokey} />
<p>Twoje imię:</p><input class="inputtext" type="text" name="author" />
<p>komentarz:</p><textarea name="comment" rows="4" cols="28"> </textarea>
<input type="submit" value="dodaj komentarz" />
</form>

then i have included following javascript on a page


jQuery(document).ready(

function(){
var options = {
dataType:        'json',
success:       updateComment  // post-submit callback
};

$('#submitComment').ajaxForm(options);
}
);

function updateComment(data) {
$(".comments").prepend('<div class="comment"><span class="author">'+data.author+'</span><span class="date">'+data.date+'</span><span class="comment">'+data.comment+'</span></div>');
$('.add-new-comment').toggle();
$('.comment-message').toggle();
}

and thats it.

Now form is automatically send via ajax. All You need to do is to point in js file $(’#submitComment’).ajaxForm(options); and when form is submitted  updateComment() is executed.

Of course thare are much more options available besides dataType (defining that return data will be formatted as json) and success (which defines the callback function). You can specify function executed before submit, timeout … and more - available on a plugin page http://www.malsup.com/jquery/form/.

I also wanted to send a form to different domain using ajax - impossible - form can be send, data can be processed by remote server, but it does not return the values, and callback never executes.

Anyway i found this plugin very easy, intuitive, and definitely will use it in my further projects.


No Responses to “Submit form via AJAX/jQuery”

You can leave a response, or trackback from your own site.


Leave a Reply

About

Impessa LTD provides IT solutions tailored to business needs. Impessa specializes in providing web and software development services including solution integration and offshore IT outsourcing across the globe.