I have the following ajax call to get data from elasticsearch. My problem is that the response does not have the expected 'aggregations' field.
$.ajax({
url: 'http://elasticsearch.net:80/tenant/_search' ,
dataType: 'JSON',
type: 'GET',
data: {
"size": 0,
"aggs": {
"group_by_user_name": {
"terms": {
"field": "user_name"
}
}
}
},
success: function(response) {
console.log(response);
}
});
Object {took: 2, timed_out: false, _shards: Object, hits: Object}
_shards: Object
hits: Object
hits: Array[0]
length: 0
__proto__: Array[0]
max_score: 0
total: 3967
__proto__: Object
timed_out: false
took: 2
__proto__: Object
I've tried the request with curl and I see the 'aggregations' field. Any idea why I can't access this field in an ajax response?
See this stackoverflow post: Querying dynamic aggregation in elasticsearch with AJAX
Essentially, you need to use POST rather than GET.
What does your curl request look like?
You need to use POST instead of GET. When you are using GET , it disregards your body and provides the top hits alone.
Your CURL equal-ant of the query is as follows -
curl -XPOST http://elasticsearch.net:80/tenant/_search -d '{
"size": 0,
"aggs": {
"group_by_user_name": {
"terms": {
"field": "user_name"
}
}
}
}'
I tried POST earlier but I was getting a 400 error (Failed to derive xcontent from org.elasticsearch.common.bytes.ChannelBufferBytesReference). I played with it again and realized that what I was missing is converting the javascript object to JSON string:
$.ajax({
url: 'http://elasticsearch.net:80/tenant/_search' ,
dataType: 'JSON',
type: 'POST',
data: JSON.stringify({"size": 0,"aggs": {"group_by_user_name": {"terms": {"field": "user_name"}}}}),
success: function(response) {
console.log(response);
}
});
BTW, the curl request works with both GET and POST.
Thanks for your help!
Related
Im working on a chrome extension using manifest V3. A core functionality of the extension is to enable users to send data from a website to the REST API of my django application, where the user is already logged in. While testing locally everything was fine, however when I went to test in staging, I found that with HTTPS django requires a "referer" in the POST header for CSRF protection.
From what I found chrome extensions just don't attach that header. So I tried the declarativeNetRequest API using the following code. However this only works when I open the URL in a tab. When fetch is called to post to the same URL, the rule is not matched. Is this the correct way to force a referer header when using fetch in V3? Thanks!
manifest.json:
...
"permissions": [
...
"declarativeNetRequestWithHostAccess",
"declarativeNetRequestFeedback"
],
"declarative_net_request": {
"rule_resources": [{
"id": "ruleset_1",
"enabled": true,
"path": "rules.json"
}]
},
...
rules.json:
[
{
"id": 1,
"priority": 1,
"action": {
"type": "modifyHeaders",
"requestHeaders": [
{
"header": "Referer",
"operation": "set",
"value": "whatever"
}
]
},
"condition": {
"urlFilter": "https://api.myserver.com",
"resourceTypes": [
"main_frame"
]
}
}
]
background.js:
...
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(function (m) {
console.log('match:', m);
});
function post_data() {
fetch(link, {
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'X-CSRFToken': csrf_token.value
},
body: JSON.stringify(text)
})
.then(response => console.log(response))
.catch(error => console.log('Error:', error))
return true;
}
...
You need to replace main_frame with xmlhttprequest, which is a type both for XHR and fetch.
Also, limit this rule to requests made by your extension. It can be done by specifying the extension's id in domains. Since the id may change during development, we'll set the rule dynamically.
Remove declarative_net_request from manifest.json.
Add the following code in background.js:
chrome.runtime.onInstalled.addListener(async () => {
const rules = [{
id: 1,
action: {
type: 'modifyHeaders',
requestHeaders: [{
header: 'Referer',
operation: 'set',
value: 'whatever',
}],
},
condition: {
domains: [chrome.runtime.id],
urlFilter: '|https://api.myserver.com/',
resourceTypes: ['xmlhttprequest'],
},
}];
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: rules.map(r => r.id),
addRules: rules,
});
});
Using JS Datatables jQuery plugin, I'm attempting to post JSON data to the server and use the JSON in the response to ultimately populate the datatable. However I've experiencing some strange behavior.
Using this code:
table_config.ajax = {
"type": "POST",
"url": $(location).attr('pathname'),
"data": JSON.stringify({'member_id':2444}),
"dataType": "json",
"contentType": "application/json",
"dataSrc": "results.data"
};
I get a 400 HTTP response and the request payload looks like:
0=%7B&1=%22&2=m&3=e&4=m&5=b&6=e&7=r&8=_&9=i&10=d&11=%22&12=%3A&13=2&14=4&15=4&16=4&17=%7D
What's going on here?
You are stringifying something that is already a string in the data option.
Try:
table_config.ajax = {
"type": "POST",
"url": $(location).attr('pathname'),
"data": { member_id: 2444 },
"dataType": "json",
"contentType": "application/json",
"dataSrc": "results.data"
};
For datatable grids, It works when I tried this
ajax: {
url: ...,
data: function ( d ) {
return JSON.stringify({"name" : "foo"});
},
"contentType": "application/json"
}
I am having a problem fixing this error. May be someone can explain what is going on here:
I am getting JSON back from server:
d3.json(fullpath, function (json)
{
graphData = json;
if (graphData.nodes.length == 0)
{
$.jnotify("Sorry there is no data for graph. Please include social media type in search.");
}
drawGraph();
});
here is part of the json:
"nodes": [{
"id": 1,
"userID": 1,
"profile_image_url": "images/twitterimage_1.jpg",
"description": "user1 desc",
"name": "user 1",
"location": "Berlin",
"statuses_count": 5,
"followers_count": 1
}
,
{
"id": 2,
"userID": 2,
"profile_image_url": "images/twitterimage_2.png",
"description": "user2343434 desc",
"name": "user 2",
"location": "Berlin",
"statuses_count": 6,
"followers_count": 2
}
then on this line: 'if (graphData.nodes.length == 0)' I do have this error:
'Error: Unable to get value of the property 'nodes': object is null or undefined'
And this is only in IE, not a problem in Chrome or Firefox.
Please help!
thanks!
ok. the problem was in this line:
d3.json(fullpath, function (json)
Do you know that IE does json asynchronously be DEFAULT?
and Chrome/Firefox does this call synchronously?
So, the work around is to switch to .ajax call from jquery library:
$.ajax({
url: dataPath,
dataType: 'json',
async: false,
data: null,
success: function (response)
{
}
thanks!
I am trying to get a json file from my server. Until now, always I need a json file, it was got by ajax and a php file in server creates the json file.
Not I have a json file (X.json) with this structure:
{
"zona": [
{
"zona1": [
{
"lon": "a",
"lat": "b"
},
{
"lon": "aa",
"lat": "bb"
},
{
"lon": "aaa",
"lat": "bbb"
},
{
"lon": "aaaa",
"lat": "bbbb"
}
]
},
{
"zona2": [
{
"lon": "c",
"lat": "d"
},
{
"lon": "cc",
"lat": "dd"
},
{
"lon": "ccc",
"lat": "ddd"
},
{
"lon": "cccc",
"lat": "dddd"
},
{
"lon": "ccccc",
"lat": "ddddd"
}
]
}
]
}
And when I try the same way to get the file, I didn't get anything. I think maybe it is possible to add the file when I load the webpage like a javascript file. Or maybe with jsonp but I trid and also I got bad answer.
As json try, I used:
$.ajax({
url: 'localhost/open/listaPuntosZona.json',
type: 'GET',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpCallbackfunction",
error: function () {
alert("Error in Jsonp");
}
});
function jsonpCallbackfunction(responseData) {
alert(responseData);
}
Also I wrapped json file with: callback( jsonfile code)
And also, this other two tries:
$.ajax({
url: 'localhost/open/listaPuntosZona.json',
type: 'get',
error: function(data){ },
complete: function(data){
data=jQuery.parseJSON(data); //do something with data
alert(data.zona.zona1.length);
}
});
$.getJSON('localhost/open/listaPuntosZona.json',function(jsonData){
alert("hola");
alert(jsonData);
});
I am using lampp to test the webpage.
Do I have to change something? I used jsonp in past but don't know what I am doing wrong now.
First of all, try using $.getJSON() instead of plain $.ajax(). it will solve many problems right off the bat.
http://api.jquery.com/jQuery.getJSON/
Secondly, make sure your json file is formatted perfectly, without any loose characters and strange whitespaces.
Also try to chain an error handler to your ajax call. available in the getJSON documentation above.
var jqxhr = $.getJSON("example.json").error(function() { alert("error"); });
// this is according to documentation, i cannot currently test this to work, sorry about that.
I know this is old but in case someone else has this issue like I did, here is how I was able to fix it...
Add the following line to the .htaccess file...
Header set Access-Control-Allow-Origin "*"
I'm trying to make a call to WCF Data Services and display the results in a GridPanel.
The call works and returns the correct JSON except the GridPanel doesn't display any results.
I tried copying the returned json into a file also on the webserver and replacing the destination url for that. This worked correctly and displays the results.
So as far as I can tell the JSON, the code and the service are all correct but they don't work together properly.
The Ext JS
Ext.define('Customer', {
extend: 'Ext.data.Model',
fields: ['Id', 'CustomerName'],
proxy: {
headers: {
'Accept' : 'application/json'
},
type: 'rest',
url: 'Service.svc/Customers',
reader: {
type: 'json',
root: 'd'
}
}
});
The JSON back from the service
{
"d" : [
{
"__metadata": {
"uri": "http://localhost:52332/testservice.svc/Customers(1)",
"type": "PierbridgeShinePlatformTestModel.Customer"
},
"Id": 1,
"CustomerName": "fred",
"Invoices": {
"__deferred": {
"uri": "http://localhost:52332/testservice.svc/Customers(1)/Invoices"
}
}
},
{
"__metadata": {
"uri": "http://localhost:52332/testservice.svc/Customers(2)",
"type": "PierbridgeShinePlatformTestModel.Customer"
},
"Id": 2,
"CustomerName": "Mr Fred",
"Invoices": {
"__deferred": {
"uri": "http://localhost:52332/testservice.svc/Customers(2)/Invoices"
}
}
}
]
}