Submit AJAX Post onchange
11,899
Use this in your form:
<input ... onchange="mySubmit(this.form)" ... >
Change the script to this:
function mySubmit(theForm) {
$.ajax({ // create an AJAX call...
data: $(theForm).serialize(), // get the form data
type: $(theForm).attr('method'), // GET or POST
url: $(theForm).attr('action'), // the file to call
success: function (response) { // on success..
$('#here').html(response); // update the DIV
}
});
}
Comments
-
Pontus Svedberg almost 2 years
I'm trying to figure out why this isn't working, I don't want to have a submit button to click, It does work if I have one though, instead I use
onchange="this.form.submit()"
and that posts the form as it normally would, not AJAX background style, I didn't code the ajax part, I found it and made it work for my situation, but as far as I know$('#ajaxform').submit(function ()
, submit is submit? Why isn'tonchange="this.form.submit()"
and<input type="submit" />
the same type of submit? What am I missing?<form method="post" action="~/getAJAX.cshtml" id="ajaxform" name="form"> @* -------- Div to hold form elements -------- *@ <div class="reportDateDiv"> @* -------- Text --------- *@ <a class="blackColor fSize18 RPtxt">Reporting Period</a> @* -------- Start day box -------- *@ <input type="text" name="inputDate" spellcheck="false" class="datepickerS metricDateTextbox capitalFirst" onchange="this.form.submit()" value="@inputDate" autocomplete="off" placeholder="@placeholderStartDate.ToString("MMM d, yyyy")" readonly="readonly" /> @* -------- Text --------- *@ <a class="blackColor fSize16 RPtxt RPtxtTo">to</a> @* -------- End day box --------- *@ <input type="text" name="endDate" spellcheck="false" class="datepickerE metricDateTextbox capitalFirst" onchange="this.form.submit()" value="@endDate" autocomplete="off" placeholder="@noEndDate.ToString("MMM d, yyyy")" readonly="readonly" /> </div> </form> <script type="text/javascript"> $('#ajaxform').submit(function () { // catch the form's submit event $.ajax({ // create an AJAX call... data: $(this).serialize(), // get the form data type: $(this).attr('method'), // GET or POST url: $(this).attr('action'), // the file to call success: function (response) { // on success.. $('#here').html(response); // update the DIV } }); return false; // cancel original event to prevent form submitting }); </script>