I'm trying to generate a HTML data table from the result of a SQL query execution. The resulting data is in JSON format. I'm using the plugin "Datatables" to achieve this. I'm following this example
I don't get an error but the data table is empty. I'm obviously doing something wrong or missing something.
Here's the code excerpt. Could I please get some guidance on to the right path please.
function jsDataPlot(chartProps) {
// Get the array from the element:
var graphPropsStore = chartProps;
// Loop through the array with the jQuery each function:
$.each(graphPropsStore, function (k, graphPropsStoreProperty) {
// The makeCall function returns a ajaxObject so the object gets put in var promise
var dbResAjx = getResultFromSql(k);
// Now fill the success function in this ajaxObject (could also use .error() or .done() )
dbResAjx.success(function (response) {
console.log(response);
// When success, call the function and use the values out of the array above
$('#divId').DataTable(response);
});
dbResAjx.error(function (response) {
console.log(response);
});
});
}
function getResultFromSql(paramId) {
// bla bla code
return $.ajax({
url: 'runMySqlQuery.php',
type: 'post',
data: {// some POST params}
});
}
JSON Result
[{"DATE":"2015-12-15","TYPE":"AAA","NAME":"asdasd"},{"DATE":"2015-12-15","TYPE":"BBB","NAME":"dsfsdfsdfsdf"},{"DATE":"2015-12-15","TYPE":"AAA","NAME":"reterter"},{"DATE":"2015-12-15","TYPE":"CCC","NAME":"ertertertert"}]
OK, in your JSON yu have this. DATE - TYPE - NAME
[
{"DATE":"2015-12-15","TYPE":"AAA","NAME":"asdasd"},
{"DATE":"2015-12-15","TYPE":"BBB","NAME":"dsfsdfsdfsdf"},
{"DATE":"2015-12-15","TYPE":"AAA","NAME":"reterter"},
{"DATE":"2015-12-15","TYPE":"CCC","NAME":"ertertertert"}
]
then in your JS should define your columns ....
$('#divId').DataTable({
columns : [
{data: "DATE"},
{data: "TYPE"},
{data: "NAME"}
],
data: response
});
example: https://jsfiddle.net/cmedina/7kfmyw6x/4/
Related
I am trying to show my JSON data in the table by using Data table. However, data table keep stuck in the processing like this and I don't know why.
https://jsfiddle.net/Lvmertbp/
JSON format
console.log(data)
Java controller code
#GetMapping(value="/projects")
public #ResponseBody List<Project> getProjects() {
return projectService.findAllProjects2();
}
I know this is the old question, but I have tried everything I can but it just don't work.
Try removing the success function, that seemed to work for me:
success:function(data){
console.log(data);
},
You should also check that your array is in the "data" object, if it's just a flat array you should pass an empty string to dataSrc. Working example: http://jsfiddle.net/5snrvL4m
Your server response is returning an array of result , not an object with data key array ,
So you data table will search in the result for a data array key , but not found , in your case you should specify the param dataSrc as empty , so it'll take it as ana array ,
Check here the doc
$(document).ready(function () {
$('#tableProject').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "/projects",
type: "GET",
contentType: "application/json",
dataSrc: '', // <------------------------ here set empty string
data: function () {
},
success:function(data){
console.log(data);
},
},
paging:true,
columns: [
{data: "projectNumber"},
{data: "name"},
{data: "status"},
{data: "customerName"},
{data: "startDate"},
]
});
});
I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?
current code :
$.mockjax({
url: "/Api/Cases/{caseId}",
proxy: "/mocks/cases nuevo.json",
dataType: 'json',
responseTime: [500, 800]
});
$.ajax({
type: 'GET',
url: '/Api/Cases/',
data: {caseId: taskId},
success: function(data){
//use the returned
console.log(data);
}
});
current error:
GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)
Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.
Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:
$.mockjax({
url: /\/Api\/Cases\/(\d+)/, // notice the regex here to allow for any ID
urlParams: ['caseID'], // This defines the first matching group as "caseID"
responseTime: [500, 800],
response: function(settings, mockDone) {
// hold onto the mock response object
var respObj = this;
// get the mock data file
$.ajax({
url: 'mocks/test-data.json',
success: function(data) {
respObj.status = 200;
// We can now use "caseID" off of the mock settings.urlParams object
respObj.responseText = data[settings.urlParams.caseID];
mockDone();
},
error: function() {
respObj.status = 500;
respObj.responseText = 'Error retrieving mock data';
mockDone();
}
});
}
});
There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId, // this will add the ID to the URL
// data: {caseId: taskId}, // this adds the data to the query string
success: function(data){
//use the returned
console.log(data);
}
});
Note that this presumes the mock data is something like:
{
"13": { "name": "Jordan", "level": 21, "id": 13 },
"27": { "name": "Random Guy", "level": 20, "id": 27 }
}
What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId,
success: function(data){
//note you have to parse the data as it is received as string
data = JSON.parse(data);
var result = $.grep(data, function(e){ return e.caseId == taskId; });
//since i'm expecting only one result, i pull out the result on the 0 index position
requestedData = result[0];
}
});
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API, And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];
**Note: **
A more suited solution would be a mixture between what i've done and #jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:
[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]
I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id
I want to get data from server and suggest with typeahead.
I get my data from list to an usl like /foo/q=QUERY and this query return json like ["salam","bye", "khodafez,].
How i can use from bootstrap typeahead to suggestion.
I try this code:
<script type="text/javascript">
$(document).ready(function() {
$("#vahid").typeahead({
// ???
});
});
</script>
According to the documentation, you just provide a function for source in the options:
$("#vahid").typeahead({
source: function(query, process) {
// `query` is the text in the field
// `process` is a function to call back with the array
$.ajax({
// Your URL
url: "/foo",
// Your argument with the query as its value
data: {q: query},
// Success callback -- since it expects the first
// parameter to be the data, and that's what the
// success callback is called with, you can just
// use `process` directly
success: process
});
}
});
The above assumes that the response correctly identifies the response as Content-Type: application/json. If it doesn't, add
dataType: "json"
...to your ajax options.
I'm using the asynchronous mechanism because you're querying a server. If you already had the data client-side, you could simply return it from the source function directly. But they (intelligently) don't require you to retrieve it synchronously from the server, as that would lead to a bad XU.
Accourding to docs https://github.com/tcrosen/twitter-bootstrap-typeahead
you can add ajax attr like :
$('#myElement').typeahead({
ajax: '/path/to/mySource'
});
or
var mySource = [
{ id: 1, name: 'Terry'}, { id: 2, name: 'Mark'}, { id: 3, name: 'Jacob'}
];
$('#myElement').typeahead({
source: mySource
});
for local data
I am trying to retrieve data from a URL of the form http://www.xyz.com/abc.json.
I have been trying to achieve this using the $.ajax method in the following manner.
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://www.xyz.com/abc.json.",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
However I am being unable to get this to run. I need to loop through the retrieved data and check for some specific conditions. This could have been achieved easily with the $.getJSon if the json data had a name to it, however the file is of the form:
[{
"name": "abc",
"ID": 46
}]
because of which I have to effectively convert and store it in a Javascript object variable before I can use it. Any suggestions on where I might be going wrong?
It looks like you will want to convert that data response to a json object by wrapping it with { } and then passing that to the json parser.
function (data) {
json = JSON.parse("{\"arr\":"+data+"}").arr;
}
Then to get your data, it would be
json[0].name //"abc"
So your question is how to convert a string to Json object?
If you are using Jquery you can do:
jQuery.parseJSON( jsonString );
So your return should be:
return jQuery.parseJSON( json );
You can read documentation here