I am trying to create a main authentication page where my form has three fields
- Username
- password
- type of grant
When submitting the form, I just want to display the returned response from the server to my HTML in JSON format. My AJAX call for the web service also requires setting the Authorization header. But for some reason headers are not set. I'm trying to
beforeSend : function(xhr) { xhr.setRequestHeader('Authorization', "Basic ******"); xhr.setRequestHeader("contentType", "application/json;charset=UTF-8"); }
But when I debug the code in the console, it seems like a breakpoint never goes to this function. I am new to Ajax and have tried under googling code on the Internet. I post all the code below.
CODE:
$(document).ready(function() { // process the form $('form').submit(function(event) { // get the form data var formData = { 'username': $('#username').val(), 'password': $('#password').val(), 'grant_type': $('#grantType').val() }; // process the form $.ajax({ type : 'POST', url : 'http://localhost:9090/oauth/token', beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic ******"); xhr.setRequestHeader("contentType", "application/json;charset=UTF-8"); }, data : formData, // our data object dataType : 'json', // what type of data do we expect back from the server encode : true }) // using the done promise callback .done(function(data) { // log data to the console so we can see console.log(data); alert(data); // here we will handle errors and validation messages }) .fail(function (jqXHR, textStatus){ alert('Status : ' + textStatus + '' + JSON.stringify(jqXHR)); }); // stop the form from submitting the normal way and refreshing the page event.preventDefault(); }); });
What does it mean not to set headers in my code. Please correct me.
On the Console tab (Google Chrome) on the network, I see request headers below
Accept:*
and below appears an error in the console. 
And when calling the same API from the Advanced Rest Client extension for Google Chrome, it shows me all the headers
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo contentType: application/json;charset=UTF-8 Authorization: Basic ********** Content-Type: application/x-www-form-urlencoded Accept: */* Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.8
I just launch my webpage using the file protocol.
Example: file:///E:/Mahendra/Practice%20Example/Test/OauthTest.html
I am not sure if this is causing the problem.