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

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).

Related

Getting parse error while fetching text file content in JQuery

I am trying to fetch data from text file which resides on server. I have access of that location and able to see content when I put URL in browser tab.
I am trying to make AJAX call and get file content, but I am getting Error: Uncaught SyntaxError: Unexpected identifier
Code
function logResults(json){
console.log(json);
}
$.ajax({
url: u,
dataType: "jsonp",
jsonpCallback: "logResults"
});
on console,
I tried below code too, but same result,
$.ajax({
type: 'GET',
url: u,
crossDomain: true,
dataType: 'jsonp',
async: false,
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function(succ) {
console.log("Success: ", succ)
},
error: function(err) {
console.log("Error: ", err)
}
});
This code is always going into error block.
You said:
dataType: "jsonp",
But the URL is responding with:
Deployment automatically finished…
Which is not JSONP, it is plain text.
You get the error when it tries to execute the plain text as JSONP.
Don't put wrong information in the dataType field.
async: false,
That's deprecated. Don't use it. It's also pointless since you are using callbacks.
It's also incompatible with JSONP so it is ignored (until you remove the incorrect dataType).
crossDomain: true,
This has no effect unless you are making a:
non-JSONP request
to the same origin
which gets redirected to a different origin
… which is very rare.
headers: {
"Access-Control-Allow-Origin": "*"
},
Access-Control-Allow-Origin is a response header. It doesn't belong the request. Trying to add it to the request will cause extra problems as it will make the request preflighted.
(At least, that would be the case if you hadn't said dataType: 'jsonp' because adding request headers is incompatible with JSONP).
All you need on the client
The only code you need on the client is:
function logResults(result){
console.log(result);
}
$.ajax({
url: u,
success: logResults
});
The server you are requesting the data from will need to use CORS to grant you permission to access it if it is a cross-origin request.
It is because you have added dataType as jsonp, so that it will try to parse the response to JSON and if the response is not a JSON it will throw error.

HTTP POST Request with XML data

I am looking to make HTTP POST Request with XML payload.
I have looked at this documentation:
http://api.jquery.com/jquery.post/
Here the parameter data is I believe I should be interested in.
However, it is not entirely very clear to me how do I specify the format of this data parameter. In most of my earlier experience this parameter is application/x-www-form-urlencoded
However, my request has an XML payload.
Any pointers ?
$.post is a shorthand function that covers some common usecases but has some unchangeable defaults. Use the $.ajax method instead. It allows you to set the content type for the request.
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: String
When sending data to the server, use this content type. Default is
"application/x-www-form-urlencoded; charset=UTF-8", which is fine for
most cases. If you explicitly pass in a content-type to $.ajax(), then
it is always sent to the server (even if no data is sent). The W3C
XMLHttpRequest specification dictates that the charset is always
UTF-8; specifying another charset will not force the browser to change
the encoding.
You can post XML data as
$.ajax({
url: ajaxurl,
data: "<test><node1></node1></test>",
type: 'POST',
contentType: "text/xml",
dataType: "text",
success : parse,
error : function (xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
} });

Uncaught SyntaxError: Unexpected token : ajax call

So I'm trying to query the below json feed, however I keep getting the error in the topic.
I've searched around this site for possible answers however none that I've come across have worked so far. Commented out datatype and jsonp, jsonpCallback isnt it either, either is data, I've made sure that it validats via http://jsonformatter.curiousconcept.com/ and it does. I really dont know.
$.ajax({
type: 'GET',
url: 'http://raidbots.com/json/playerdata/us/mannoroth/usiris',
cache:true,
dataType: 'jsonp',
data: {
format: 'json',
},
success: ranks,
jsonpCallback:'callbackName',
error: function(data) { console.log(data); },
jsonp: false,
});
function callbackName(data){
console.log("jsonpCallback");
}
var ranks = function(data) {
console.log(data);
}
Thank you
-Art
The error is in your JSONp data because it's just JSON and not JSONp. JSONp requires the document to be valid JavaScript containing a function call.
If they don't support jsonp you need to use a proxy script (e.g. a php script on your server that retrieves the document) or ask them to send CORS headers so you can use a normal non-JSONp AJAX call to retrieve the data directly.

Jquery Ajax cross Domain returns success as status in error function

I am doing a cross domain get using jquery ajax but i get success as status in the error function.
I am expecting data to be returned from the get service is :
document.write("<div class=\"display_archive\"><div class=\"campaign\">07\/18\/2013 - <a href=\"http:\/\/us6.campaign-archive2.com\/?u=c7b9b2f23eb4f63fgfgf5ac4f&id=99e1f5f249\" title=\" Newsletter #3\" target=\"_blank\">Newsletter #3<\/a><\/div>");
but what i get is in error function
Object { readyState=4, status=200, statusText="success"}
My code
getResource : function ( containerSelector,serviceURL ) {
$.ajax ({
type : "GET",
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
url : serviceURL,
headers : {
"Accept" : "application/json",
"Content-Type" : "application/json"
},
success : function successData(resourceObj) {
console.log("success ");
console.log(resourceObj);
},
error : function errorData(resourceObj) {
console.log("error ");
console.log(resourceObj);
},
})
},
Am i missing something here ? help please
Use JSONP for Cross-domain requests
because Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:
function getData(data) {
}
And then your server wraps JSON data in a function call, like this:
getData({"the": "data"});
And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.
Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.
Refrence 1
Refrence 2
jQuery AJAX cross domain
Try adding:
crossDomain: true,
I can't see any error here other than that.

JSONP request returning error: "Uncaught SyntaxError: Unexpected token :"

So I'm trying to make a request to the Stack Exchange API with the following jQuery code:
$.ajax({
type: 'POST',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); }
});
But when I open the file on my machine, in either FireFox or Chrome, and make the request, I get this error:
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
Uh Oh!
I don't have a clue what's going on. I know the Stack Exchange API Gzips its responses, would this cause any trouble?
You have to set an unconventional parameter to get the SO API to work. Rather than the conventional callback, you need to pass a jsonp parameter.
Furthermore, you can't do POST with JSONP.
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); },
jsonp: 'jsonp'
});
It is not possible to do cross-domain AJAX using the conventional XMLHTTPRequest. This is for security reasons (it's call the same-origin policy).
There is a workaround. script tags are not subject to this restriction. This means that you can insert a script tag into the document that calls a URL. If you define a globally-accessible function in your script and tell the remote server what that function is called, the server can pass code that wraps the data to be sent in a call to that function.
The difficulty you had here is with the StackOverflow API. Conventionally, you would use the callback argument in your request, to tell the server what your function is called. However, StackOverflow's API asks you to use the jsonp parameter instead.
Try this URL: http://api.stackoverflow.com/1.1/stats?jsonp=callme
"callme" is the name of your callback function - in your GLOBAL NAMESPACE (window object).
By the way, if you are running Firefox and have the JSONView add-on installed you can test the above URL (and yours for comparison) directly.
Result from calling the URL:
callme({
"statistics": [
...
]
})

Categories

Resources