How to pass authorization header in $.post() method using Javascript? - javascript

I want to pass Authorization header while POSTing data to server.
I tried
$.ajax({
url : <ServiceURL>,
data : JSON.stringify(JSonData),
type : 'POST',
contentType : "text/html",
dataType : 'json',
success : function(Result) {
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', <Authorization Header Value>);
},
error: function (RcvData, error) {
console.log(RcvData);
}
});
But REST service returns error (error code : 500). The same service was working fine with $.post() before adding authorization.
could anyone tell me "How to pass authorization header in $.post()??"

Use
contentType: 'application/json',
You may have gotten data and contentType mixed up.
contentType is the Content-type header you send.
data changes how jQuery treats the data you receive.

The jQuery $.ajax() method accepts a headers value in the settings object.
So:
$.ajax({
// url, data, etc...
headers: {
"Authorization" :"Basic " + myBase64variable,
"Content-Type" :"application/json"
}
});
Source: http://api.jquery.com/jquery.ajax/
PS: Seems you can also pass in a new settings object in the beforeSend parameter. I didn't know this, so thanks for asking this question :)

Related

Request [/.../_search] contains unrecognized parameters: [_], [callback] AJAX and elasticsearch 5.x

I have part AJAX code, but it returns status 400 Bad Request
{
"error" : {
"root_cause" : [
{
"type" : "illegal_argument_exception",
"reason" : "request [/.../_search] contains unrecognized parameters: [_], [callback]
My code is blow:
jQuery.ajax({
url:url/_search?pretty=true',
type: 'POST',
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(query)
}).done(function(xhr) {
alert("Success");
}).fail(function(xhr) {
alert(xhr.hits.hits);
})
I have enabled Cross in elasticsearch.yml file with http.cors.enabled: true. Need some help pls
Those parameters are being added because you have told jQuery to expect a JSONP response. Consequently it is making a JSONP request (with <script> tags instead of XMLHttpRequest) and telling the server what callback function name to use.
As a side-effect this forces the request to be GET and prevents headers (such as content-type) being modified.
Don't tell jQuery to use JSONP unless the API requires that you do (JSONP is a dirty hack that has been superceeded by CORS so you should only have to use it with legacy APIs now).

Is it possible to add header ini ajax post cross domain?

i try to add header for authorization in ajax post to external domain. The code looks like this
$.ajax({
url: "externalUrl",
headers : {
"Authorization": token
},
type: "POST",
data: (data),
crossDomain : true,
dataType: "json",
success: function(result){
//run something here
}
});
i've set the CORS setting in my server too
res.Header().Set("Access-Control-Allow-Origin", "*")
res.Header().Set("Access-Control-Allow-Method", "*")
res.Header().Set("Access-Control-Allow-Headers", "*")
but when client try to post ,the method change into OPTIONS
Is it possible to add header ini ajax post cross domain?
problem solved by adding handler for options and add allow header in that handler as suggestion from madalin ivascu. it's possible!

POST gets converted to GET, when sending request via local apache

I am trying to send a post request with the following code. But the request goes as GET request, instead of POST. How to fix this.
$.ajax({
url: 'https://www.exampleurl.com',
method: 'POST',
headers: {"Access-Control-Allow-Origin": true},
data: {url:'bla',call:"trans"}
dataType: 'jsonp',
success: function(data){
console.log('succes: '+data);
}
});
This is the error I am getting
XMLHttpRequest cannot load https://example.com. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401.
When removed the header Access-Control-Allow-Origin, I am getting a 404 error
I don't think, you can use a POST method with jsonp request. jsonp callbacks only for with GET method. Have a look at link .
You don't have to pass parameters in url attribute when you want to send POST request you should use data attribute instead, take a look at jQuery.ajax() :
$.ajax({
url: 'https://www.exampleurl.com',
method: 'POST',
data: {q:1, q2:2},
headers: {"Access-Control-Allow-Origin": true},
dataType: 'jsonp',
success: function(data){
console.log('succes: '+data);
}
});
Hope this helps.

Request JSONP with text/plain MIME Type

I'm trying to use JSONP to request a feed on another domain. I know that the content type should be JSON or JavaScript, but it is text/plain and I don't have control over the server so I can't change the header. How can I get an AJAX call to work?
Here is what I have so far -
function asdf() {
$.ajax({
url: "http://example.com/path/to/sharepoint/_vti_bin/listdata.svc/TestCalendar/$count",
jsonp: "callback",
dataType: "jsonp",
contentType: "text/plain",
// work with the response
success: function( response ) {
console.log( response ); // server response
}
});
}
If I just try a regular request, obviously I just get a CORS error.
XMLHttpRequest cannot load http://example.com/path/to/sharepoint/_vti_bin/listdata.svc/TestCalendar/$count. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access. The response had HTTP status code 401.
Try to execute directly your URL in a browser to be sure that all is working fine
After that, try with this JQuery configuration:
$.ajax({
url : "YOUR_URL",
dataType : 'jsonp',
crossDomain: true,
type : 'POST',
timeout : 30000, // in milli seconds
cache : false
success:function(response) {
console.log(response);
}
});

ajax response error(XML Parsing Error: no element found Location: moz-nullprincipal)

i am unable to get the response from ajax. please guide me how to resolve this error, i am getting successful data return from the server i have checked it in fiddle web debugger and still ajax is showing error.
XML Parsing Error: no element found Location: moz-nullprincipal:{6b0a1ac2-50ab-4053-9f71-8ae49202288d} Line Number 1, Column 1:
$j.ajax({
type:"POST",
url:'http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit',
data: 'Celsius=12',
crossDomain:true,
async: false,
success:function(response)
{
alert("Success Full Done"+response.string);
},
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
}
});
I've this problem with request:
$.ajax({
type: "POST",
url: ajaxUrl,
dataType : "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function (data) {
...
}
});
Accept header in request is:
Accept application/json, text/javascript, */*; q=0.01
Response status is 200, but browser detect error and no success callback called
Fixed by remove dataType : "json":
$.ajax({
type: "POST",
url: ajaxUrl,
contentType: "application/json",
...
The only difference that accept header in request changed to:
Accept */*
But now success callback is called.
Add the "beforeSend" function into your AJAX call to override the acceptable response mime type.
Refer to the jQuery.ajax() documentation:
http://api.jquery.com/jquery.ajax/
As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
And:
Data Types
Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.
I had the same problem when I made GET XMLHttpRequest call.
var req = new XMLHttpRequest();
req.open('GET', '/exampleServlet', false);
req.send(null);
It was fixed by setting ContentType on the HttpServletResponse.
response.setContentType("text/plain");
This error may be caused due to two reason. One is when getting no response from java backend and other is when their is no #ResponseBody in java Controller method.
I added ContentType to ResponseEntity and problem solved. Try to add a valid ContentType to your controller response:
ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).build();
I just ran into the same problem with a simple request:
$.ajax({
type: "POST",
url: something,
data: JSON.stringify(data),
contentType: "application/json"
});
In my case, this was a fire-and-forget scenario - I don't care about the response. To solve it, it was a case of changing the server-side code to correctly return a 204: No content status code, instead of returning 200: OK.

Categories

Resources