3

I’m using JQuery 1.9.2, although this question might not concern JQuery. I’m auto-submitting an HTML form using this code …

<script type="text/javascript">
    $(function() {
        $('#autolaunch').submit(); 
    }); 
</script>
…
<form id="autolaunch" name="autolaunch" action="${ltiLaunchUrl}" method="post">
    <input type="hidden" name="lti_version" value="${lti_version}" />
    <input type="hidden" name="lti_message_type" value="${lti_message_type}" />
    …
    <input type="hidden" name="lis_person_name_given" value="${lis_person_name_given}" />
</form>

The action of the form is a different domain than the server on which this page is accessed. My question is, how can I add a header when submitting this data? The header I want to add would look like name = "LTI-Authorization" and value = “Token consumerKey:consumerSecret”.

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
Dave A
  • 2,780
  • 9
  • 41
  • 60

2 Answers2

0

you cannot add a header to a form.

Instead of header add a new hidden input.

<input type="hidden" name="LTI-Authorization" value="Token consumerKey:consumerSecret" />

You can add header by using ajax request or XHR.

$.ajax({
    type: 'POST',
    url: url,
    headers: {
        "LTI-Authorization":"Token consumerKey:consumerSecret"
    },
    data: {
       "lti_version":"${lti_version}" // all other data
    }
}).done(function(data) { 
    alert(data); 
});
Vishnu
  • 11,614
  • 6
  • 51
  • 90
  • Does this make the outgoing request look the same as if the header were added? – Dave A Jul 29 '15 at 18:45
  • @DaveA No it is not the same. You have to check the input value in the backend instead of headers. You can use ajax request to add the header, see the updated answer. – Vishnu Jul 30 '15 at 02:53
  • Also I didn't think you can submit an AJAX request to a different domain than the domain from which the AJAX request is originating. Is this true? – Dave A Jul 30 '15 at 16:21
  • If that domain allows you can. http://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work – Vishnu Jul 30 '15 at 16:25
  • http://stackoverflow.com/questions/19085965/jquery-ajax-access-control-allow-origin – Vishnu Jul 30 '15 at 16:25
  • What if you don't want to use ajax but need to redirect to where the form post. Not everything is ajax. – Sam Nov 03 '17 at 17:22
  • @Sam https://stackoverflow.com/questions/9516865/how-to-set-a-header-field-on-post-a-form – Vishnu Nov 04 '17 at 04:57
0

You can add a header in Jquery just that needs taking a handle of the javascript XMLHttpRequest object while you do a Jquery form submit. I have answered the same question here. You'd be doing something like this:

xhttp.open("POST", "/v1/target-endpoint.do", true);
xhttp.setRequestHeader("custom_header", "test value of custom header");
xhttp.send($("#custom_form").serialize());

where xhttp is your XMLHttpRequest object.

Himadri Pant
  • 2,171
  • 21
  • 22