The way I approached this: I removed the entire form tag and placed all form elements, such as input, textarea tags, in a div and used a single button to call the javascript function. Like this:
<div id="myform"> <textarea name="textarea" class="form-control">Hello World</textarea> <button type="submit" class="btn btn-primary" onclick="javascript:sendRequest()">Save changes</button> <div>
Javascript:
function sendRequest() { $.ajax({ type: "POST", url: "/some/url/edit/", data: { data: $("#myform textarea").val() }, success: function (data, status, jqXHR) { console.log(data); if (data == 'success') { $('#mymodal').modal('hide'); } } }); return true; }
I thought why use form when we submit the actual request using AJAX. This approach may require additional efforts to reset form elements, but it works for me.
Note The answers above are more elegant, but my use case was a bit different. There were many forms on my web page, and I did not think that registering event listeners for each submit button is a good way. So, I made each submit button call the sendRequest () function.
Yashas May 12 '19 at 3:57 2019-05-12 03:57
source share