How do I capture response of form.submit
You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the submit()
function doesn't actually return anything, it just sends the form data to the server.
If you really wanted to get the response in Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll need to use a library. jQuery is by far the most popular, and my personal favourite. There's a great plugin for jQuery called Form which will do exactly what it sounds like you want.
Here's how you'd use jQuery and that plugin:
$('#myForm')
.ajaxForm({
url : 'myscript.php', // or whatever
dataType : 'json',
success : function (response) {
alert("The server says: " + response);
}
})
;
Get JSON response from Form Submit
You can use jquery form handler as,
<script>
// Attach a submit handler to the form
// Attach a submit handler to the form
$("#uploadForm").submit(function(event) {
var formData = new FormData();
formData.append("uploadFiles", $('[name="file"]')[0].files[0]);
event.stopPropagation();
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data) {
alert(data);
loadFiles()
}
});
return false;
});
</script>
Refer this stackoverflow question
Submit a form and get a JSON response with jQuery
If you want to get the response in a callback, you can't post the form. Posting the form means that the response is loaded as a page. You have to get the form data from the fields in the form and make an AJAX request.
Example:
$(function(){
$('form[name=new_post]').submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(json) {
alert(json);
}, 'json');
return false;
});
});
Notice that you have to return false
from the method that handles the submit event, otherwise the form will be posted also.
Related Topics
Returning Chrome Storage API Value Without Function
Typeerror: Console.Log(...) Is Not a Function
How to Set Default Homepage in Ff and Chrome via JavaScript
Optional Chaining in JavaScript
My Very Simple Greasemonkey Script Is Not Running
Object Method with Es6/Bluebird Promises
Make Several Requests to an API That Can Only Handle 20 Request a Minute
Benefits of Prototypal Inheritance Over Classical
How to Get Evaluated Attributes Inside a Custom Directive
How to Use Underscore.Js as a Template Engine
Which Keycode for Escape Key with Jquery
JavaScript Document.Write Replaces All Body Content When Using Ajax
JavaScript "Cannot Read Property "Bar" of Undefined
Addition Is Not Working in JavaScript
How to Build/Concatenate Strings in JavaScript
Differencebetween String.Slice and String.Substring