How to Capture Response of Form.Submit

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



Leave a reply



Submit