How to use Ajax Form
Ajax, which is widely used by web designers, is a popular characteristics of web 2.0. But you may have been sicked with sending form's data via ajax.The bad code may be as follows:
var url = $('#url_add').val(); var cname=$('#class_name').val(); var sub_class_name=$('#sub_class_name').val(); var parent_id=$('#parent_class').val(); $.post(url,{'class_name':cname,'sub_class_name':sub_class_name,'parent_class':parent_id},function(data) { if(data.indexOf('error')!='-1') { alert('add failed.'); } else { parent.location.reload(); } $('#debug').html(data); // });
You may be tired of writing the form's values.Fortunately ,3 items was given in the code above,you may ignore the complication and the lengthiness .Why not use a automate way to deal with it? ,this is Ajax Form!
With Ajax Form , you can send you form easily.Some code may be as follows:
HTML CODE:
Save |
$('#saveRole').click(function() {//the button of saveRole $('#roleForm').submit(function(ret){//send the form with Ajax From plugins var object = getObjectFromStr(ret);//change the String to json Object //'errmsg',which the flag of operation result, is a property of the json setted in server side var message = object.errmsg; if (message) { alert(message);//you can show the message in your own way,just use alert now. //in my server side when operate failed,'error' will be added to the property of errmsg if (message.indexOf('error') == -1) { //show success here } } },null,'json'); });
That is not the end of the effective of Ajax Form. We have just see the process of sending a form's data, which will result in inserting some data into your database.But when you modify one record from your database,you may deal with putting the record's some fields into a form, we have been tired of getting data form a form ,now it up to setting a form data.Don't worry , Ajax Form has the solution. Let us see a demo:
HTML CODE:
1 | name area | remark | ">detail | ">modify | ">delete | ">assign menu |
JS CODE:
$('.modifyRole').live('click',function() {//modify role var modifyUrl = $(this).attr('href'); var rowId = $(this).parent().attr('rowId'); var modifyFormAction = 'web/user/roleAction-toModify.action?rowId=' + rowId; $('#roleForm').setWebData(modifyUrl,modifyFormAction); return false; });
As you have seen,when you click the link of 'modify',the form will be filled with the data requested from the server side.You get the data via ajax, this means you can use the same ui as creating one record you have just used and giving customer a better user experience,and the last but does not represent is not important , ajax can improving the time of server's response.