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"
}
Related
I have API Call abd which will be returning Json like below
{
"status": true,
"message": "Data Sent",
"data": [
{
"id": 9,
"name": "North",
"colType": 7,
"userID": 0,
"isVisible": false
}
]
}
And below i have JavaScript Ajax Call but it is returning Empty datatable please do help
$('#myTable').DataTable({
destroy: true,
responsive: true,
"ajax": {
"url": url+'/api/CommonMasters/7/GetByUserID/'+#ViewBag.UID,
"type": "GET",
"datatype": "json",
},
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"columns": [
{ "data": "name", "autoWidth": true },
{
"render": function (data, type, full, meta) { return "<a id='Edit' class='btn btn-info' onclick='editRefUser(" + full.id + ")' ;>Edit</a>"; }
},
]
});
In the ajax section, you need to define your data source: "dataSrc": "data".
"ajax": {
"url": url+'/api/CommonMasters/7/GetByUserID/'+#ViewBag.UID,
"type": "GET",
"datatype": "json",
"dataSrc": "data"
},
Why is this needed? Your JSON data structure does not have a "name" item at the top level. Names are nested inside the top-level "data" object. This extra directive tells DataTables to look only at the JSON's "data" object as its starting point.
See here for the related documentation:
The ajax option basically inherits all of the options made available by jQuery.ajax, but we provide the extra option of dataSrc to provide the ability to alter what data DataTables will read from the JSON returned from the server...
Also, on an unrelated note, I don't think you need this: destroy: true - try removing it. It probably does not make sense to try to destroy the table object while you are initializing it.
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!
Am attempting to load and Ext Store with Ext 4.0.7.
It is returning an Object doesn't support this property or method error when i call the loadRawData method on the store in the success callback of the AJAX request.
Here is the data i am loading:
{
"data": [
{
"id": 1,
"source": "1445261",
"target": "1437043",
"sourceType": "user",
"redirectUrl": "http://www.google.co.uk",
"message": "this is a notification message",
"targetType": "user",
"messageType": "notification",
"sentDate": "1354758001",
"notificationType": "notification",
"parameters": "null",
"read": "false",
"readDate": 1354758001
},
{
"id": 2,
"source": "1445261",
"target": "1437043",
"sourceType": "user",
"redirectUrl": "http://www.google.co.uk",
"message": "this is a notification message",
"targetType": "user",
"messageType": "notification",
"sentDate": "1354758001",
"notificationType": "notification",
"parameters": "null",
"read": "false",
"readDate": 1354758001
},
{
"id": 3,
"source": "1445261",
"target": "1437043",
"sourceType": "user",
"redirectUrl": "http://www.google.co.uk",
"message": "this is a notification message",
"targetType": "user",
"messageType": "notification",
"sentDate": "1354758001",
"notificationType": "notification",
"parameters": "null",
"read": "false",
"readDate": 1354758001
}
]
}
This is the store code and ajax request:
var infoStagingStore = Ext.create('Ext.data.Store', {
model: 'SCB.RMWB.InfoBar.Model.Message',
storeId: 'Staging',
autoLoad: false,
pageSize: 10,
proxy: {
type: 'pagingmemory',
reader: {
type: 'json',
root: 'data'
}
},
listeners: {
load: function(){
console.log('loaded');
}
}
});
Ext.Ajax.request({
url: '/rmwb/resources/js/app/infoBar/data/data.json',
timeout: 60000,
method: 'GET',
scope: this,
params: '',
success: function(resp) {
console.log(resp.responseText);
var store = Ext.data.StoreManager.lookup('Staging');
store.loadRawData(resp.responseText, true);
},
failure: function(resp, opts) {
},
callback: function(options, success, resp) {
}
});
Can't quite see why this is returning an error?
As in my comment, you donĀ“t need a pagingmemory store. What you need is an ajax store because the pagingstore is for allowing pagination with data you have in memory but there is no reason to use it seeing your requirement.
So if you use an standard ajax proxy, you will be able to load it in the normal way (using the .load() method). Then, when you need to add more record from the server you what you have to do is just call the load method again but with the addRecords option.
For example (untested sample):
// load store with historical data
infoStagingStore.load();
// load more records to the store from a different resource
infoStagingStore.load({
url: '/rmwb/resources/js/app/infoBar/data/data.json',
addRecords: true
});
Seeing as you've assigned your store to a variable called infoStagingStore could you not just reference that directory in your ajax call?
Ext.Ajax.request({
url: '/rmwb/resources/js/app/infoBar/data/data.json',
timeout: 60000,
method: 'GET',
scope: this,
params: '',
success: function(resp) {
console.log(resp.responseText);
//var store = Ext.data.StoreManager.lookup('Staging');
infoStagingStore.loadRawData(resp.responseText, true);
},
...
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"
}
}
}
]
}