<form action="do_something" method="post" id="do_something_form"> Field 1: <input type="text" name="field1" id="field1" /> <br /> Field 2: <input type="text" name="field2" id="field2"/> <br /> <input type="submit" value="Submit" /> </form> <script> jQuery('#do_something_form').submit(function(event){ // stop normal form submitting event.preventDefault(); // get form's fields var field1_val = jQuery('#field1').val(), field2_val = jQuery('#field2').val(), url = jQuery(this).attr('action'); // send request jQuery.post(url, // ajax url { field1: field1_val, field2: field2_val }, // data passed to server side function(response){ // callback // do things with response data, ex: alert(response["message"]); if (response["success"] == true) { // ... } }, "json" // response's format ); }); </script>
Then at backend:
def create @form = params if some_condition @result = { :success => true, :message => "Resource has been created successfully!", :other_data => {} } else @result = { :success => false, :message => "Creation failed! Please try again!" } end render :text => @result.to_json end
http://api.jquery.com/jQuery.post/
No comments:
Post a Comment