Submitting A Form Via Ajax February 28, 2024 Post a Comment I have a form that looks as following: Solution 1: When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:<formonsubmit="javascript: return false;">CopyNew style:$('form').submit(function() { returnfalse; }); CopyAnd on submit you want to perform an ajax query:$('form').submit(function() { $.ajax({ }); // here we perform ajax queryreturnfalse; // we don't want our form to be submitted }); CopySolution 2: Use jQuery's preventDefault() method. Also, value() should be val().$("#submitPasswordRequest").click(function (e) { e.preventDefault(); var username = $('#passwordEmail').val(); ... }); CopyFull code: http://jsfiddle.net/HXfwK/1/You can also listen for the form's submit event:$("form").submit(function (e) { e.preventDefault(); var username = $('#passwordEmail').val(); ... }); CopyFull code: http://jsfiddle.net/HXfwK/2/Solution 3: jquery and ajax$('form id goes here).submit(function(e){ e.preventDefault(); var assign_variable_name_to_field = $("#field_id").val(); ... if(assign_variable_name_to_field =="") { handle error here } (don't forget to handle errors also in the server side with php) after everyting is good then here comes ajax datastring = $("form_id").serialize(); $.ajax({ type:'post', url:'url_of_your_php_file' data: datastring, datatype:'json', ... success: function(msg){ if(msg.error==true) { show errors from server side without refreshing page alert(msg.message) //this will alert error message from php } else { show success message or redirect alert(msg.message); //this will alert success message from php } }) }); Copyon php page$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name ... then useserversidevalidationif(!$variable) { $data['error']= true; $data['message'] = "this field is required...blah"; echo json_encode($data); } else { after everything is good do any crud or email sending and then $data['error'] = "false"; $data['message'] = "thank you ....blah"; echo json_encode($data); } CopySolution 4: You should use the form's submit handler instead of the click handler. Like this:$("#formID").submit(function() { // ajax stuff here...returnfalse; }); CopyAnd in the HTML, add the ID formID to your form element:<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post"> CopySolution 5: You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:$('form').on('submit',function(e){ e.preventDefault(); $.ajax({ type: "POST", url: "/resetting/send-email", data: $('form').serialize(), // serializes the form's elements.success: function( data ) { console.log(data); // show response from the php script. } }); returnfalse; }); Copy Share Post a Comment for "Submitting A Form Via Ajax"
Post a Comment for "Submitting A Form Via Ajax"