Reputation: 71
I am submiting form using $('#myForm').submit
my rest service accepts content-type of application/x-www-form-urlencoded
, but when using submit() I can't see the request in XHR tab in browser developer tools and the form parameters doesn't reach the Rest service, I could use AJAX post and specify content-type, but Rest service produces octet stream in other words the response contains a downloadable file csv/pdf, what could be the solution to submit form correctly?
Upvotes: 1
Views: 966
Reputation: 1566
After reading your modified Question usually if the parameters are empty at the API it could be caused by the following.
Upvotes: 0
Reputation: 8496
Why you are not using $.ajax() with type:"post" ?. you can set header easily there
// Request with custom header
$.ajax({
url: 'foo/bar',
type: 'post',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: {}, // object of your data
success: function(response){
alert(response)
}
});
IF your api response is in octet stream or downloadable file then you have to create virtual form and post it through jQuery, Because through AJAX it is not possible to download file.. When file is download content of current page will remain same event form is posted.
function autoGenerateAndSubmitForm(method, url, post_data) {
var element = document.getElementById("virtual_form");
if(element != null )
{
element.parentNode.removeChild(element);
}
var form = document.createElement("form");
form.setAttribute("id", "virtual_form");
form.setAttribute("style", "display:none;");
//form.setAttribute("target", "_blank"); // remove comment if you want to open it in new tab
form.method = method;
form.action = url;
for(i in post_data)
{
var element=document.createElement("input");
element.value=post_data[i];
element.name=i;
form.appendChild(element);
}
document.body.appendChild(form);
form.submit();
form.parentNode.removeChild(form);
}
Call below function with your poper arguments
autoGenerateAndSubmitForm('POST','your_url',{your_post_data_object:"Here"});
Upvotes: 1