I need to submit data to server (using post with form) and catch a return status so that I can return a resolve or reject. I cannot use ajax to make the request neither XMLHttpRequest. I would like to know how can I submit form and return a promise (like @SomeKittens answer on 'the promise constructor'). custom.js :
var myfunction =
{
submitForm: function()
{
// Create form
var form = document.createElement('form');
form.setAttribute('action', 'server.php');
form.setAttribute('method', 'POST');
var input1 = document.createElement('input');
input1.setAttribute('type', 'hidden');
input1.setAttribute('name', 'params');
input1.setAttribute('id', 'params');
input1.setAttribute('value', 'myvalue');
form.appendChild(input1);
// Create iframe and append form to it
var $frame = $('<iframe style="width:500px;height:400px;display:none;">');
$('body').html( $frame );
setTimeout( function(){
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html(form);
// submit form
$(form).submit();}, 1 );
}
}
index.html :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="custom.js"></script>
</head>
<body>
<script>
myfunction.submitForm().done(function () {
alert('It works');
}).fail(function () {
alert('Failed');});
</script>
</body>
</html>
Thanks