Donatas
Donatas

Reputation: 71

JQuery submit form parameters are empty

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

Answers (2)

Frank Odoom
Frank Odoom

Reputation: 1566

After reading your modified Question usually if the parameters are empty at the API it could be caused by the following.

  1. Form is Not Properly Serialized
  2. The Content Type Specified Is Not what your API is Accepting
  3. When you are using ajax make sure your form does not specify any action and methods else there might be a problem.
  4. The model the API is expecting doesn't match what the form has submitted
  5. When using Ajax change your button type to "button" instead of "submit".

Upvotes: 0

Haresh Vidja
Haresh Vidja

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

Related Questions