Json feeding dataTable through ajax call - json

I have a simple testing script:
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
$('#dataTables-example').DataTable({
"processing": true,
"serverSide": true,
"ajax": "../server/studentsdata.php"
} );
} );
</script>
This is my json response:
{"draw":0,"recordsTotal":57,"recordsFiltered":57,"data":[["Tiger Nixon","320800","61"],["Garrett Winters","170750","63"],["Ashton Cox","86000","66"],["Cedric Kelly","433060","22"],["Airi Satou","162700","33"],["Brielle Williamson","372000","61"],["Herrod Chandler","137500","59"],["Rhona Davidson","327900","55"],["Colleen Hurst","205500","39"],["Sonya Frost","103600","23"],["Jena Gaines","90560","30"],["Quinn Flynn","342000","22"],["Charde Marshall","470600","36"],["Haley Kennedy","313500","43"],["Tatyana Fitzpatrick","385750","19"],["Michael Silva","198500","66"],["Paul Byrd","725000","64"],["Gloria Little","237500","59"],["Bradley Greer","132000","41"],["Dai Rios","217500","35"],["Jenette Caldwell","345000","30"],["Yuri Berry","675000","40"],["Caesar Vance","106450","21"],["Doris Wilder","85600","23"],["Angelica Ramos","1200000","47"],["Gavin Joyce","92575","42"],["Jennifer Chang","357650","28"],["Brenden Wagner","206850","28"],["Fiona Green","850000","48"],["Shou Itou","163000","20"],["Michelle House","95400","37"],["Suki Burks","114500","53"],["Prescott Bartlett","145000","27"],["Gavin Cortez","235500","22"],["Martena Mccray","324050","46"],["Unity Butler","85675","47"],["Howard Hatfield","164500","51"],["Hope Fuentes","109850","41"],["Vivian Harrell","452500","62"],["Timothy Mooney","136200","37"],["Jackson Bradshaw","645750","65"],["Olivia Liang","234500","64"],["Bruno Nash","163500","38"],["Sakura Yamamoto","139575","37"],["Thor Walton","98540","61"],["Finn Camacho","87500","47"],["Serge Baldwin","138575","64"],["Zenaida Frank","125250","63"],["Zorita Serrano","115000","56"],["Jennifer Acosta","75650","43"],["Cara Stevens","145600","46"],["Hermione Butler","356250","47"],["Lael Greer","103500","21"],["Jonas Alexander","86500","30"],["Shad Decker","183000","51"],["Michael Bruce","183000","29"],["Donna Snider","112000","27"]]}
But I keep receiving this error:
DataTables warning: table id=dataTables-example - Invalid JSON
response. For more information about this error, please see
http://datatables.net/tn/1
I tried to validate my json response on a few websites, and they all show it as valid. Why is Datatables rejecting it?
A update:
If I paste my json response directly on the php page, it works. Look like the json is right, but for some reason the script is not sending correctly. When I try to access the script directed (by accessing the .php page), I get the correct json.

Update!:
Maybe its because of extra properties you are passing into dataTable!
try to change php part to produce something like this :
{
"data":[
["name":"Tiger Nixon","value":"320800","age":"61"],
["name":"Garrett Winters","value":"170750","age":"63"]
.
.
.
]
}

Related

Postman: POST request of nested JSON via form-data not working (while via raw-data ok)

I want to POST the following JSON-object via Postman:
{
"title": "test_title",
"date": "2021-12-31",
"attachments": [
{
"name": "test_attachment"
}
]
}
This works perfectly fine, when using Postman's raw input form for the request-body: I get a "201 Created"-response back.
However, when using the form-data to POST the data, I get the error "Invalid data. Expected a dictionary, but got str." (see also screenshot below) What am I doing wrong here? I tried all kind of other versions to enter the attachment-key:value pair but nothing worked so far
I managed to make it work! (note: I added some additional fields compared to the screenshot in question. See below for details:
You did nothing wrong.
If you want to make a request with json object, then you go with raw type (json) in postman.
If you want to upload file, then you use form-data
One more thing, status 201 means the request is succeed, your object has been created.
var express = require('express')
const multer = require('multer')
const upload = multer()
var app = express()
app.use(express.json());
app.post('/test',upload.none(), function (req, res, next) {
res.send(req.body)
})
app.listen(80, function () {
console.log('web server listening on port 80')
})
Above is a sample endpoint which works with both form-data and json , just do a post to http://localhost:80/test with both form data and raw json
you can see both will get parsed correclty
APIs are just abstraction , its like a function that takes in many attribute, how you parse it depends on the implementation ( how the api function is written) .
so answer is "Talk to the developer" on how the API is implemented and what it is supporting
I'm having issue in placing json into form format the way Daniel did in Postman. Need help in figuring out what is it required to place the cascaded json objects into form data format. Please see here that I'm trying to accomplish.
JSON Format (to be filled into Postman form-data section:
{
"primary_object": {
"child_object_1": [{"id": 12345678, "value": "abc"},{"id": 87654321, "value": "xyz"}],
"child_object_2": [
"first_val",
"second_val"
]
}
}

response with status 200: ok

I am trying to figure out how to plot data from a local '.JSON' file using angular2-highcharts example.
I followed the example in 'https://www.npmjs.com/package/angular2-highcharts' to first understand how to plot .JSON data and it worked. I took the data available for the example and created a local .JSON file (copied the content from 'https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK' in notepad and saved it with UTF-8 encoding as a .JSON file), and replaced the file path for the JSON request to this. When I do this though, I get an error - response with status 200.
constructor(jsonp : Jsonp) {
//jsonp.get('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK').subscribe(res => {
jsonp.get('./data.json').subscribe(res => {
this.options = {
title : { text : 'AAPL Stock Price' },
series : [{
name : 'AAPL',
data : res.json(),
tooltip: {
valueDecimals: 2
}
}]
};
});
}
options: Object;
};
Since I am not super familiar with json data/ Javascript or angular2 I am not sure if I am missing something very basic here. Any help is appreciated.
as far as I know, Response Status 200 specifies that request was successful. i.e. your request was successfully handled. perhaps you want to try checking response data.
check your callback for response data.
Using http instead of json helped. I made use of the suggestion in this answer https://stackoverflow.com/a/36305814/4567096.

Requesting embedded JSON data for D3

For reasons I won't bore you with, ALL elements of my webpage must be embedded into one file.
Between the HTML header tags, I have valid JSON data declared:
<script type="application/json" id="data">
"name": "flare", "children":[{"name": "thing1", ... }]
</script>
Previously this data was written to a JSON file which was referenced by my D3 bar chart scripts as follows:
d3.json("data/file.json", function(root) {
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
});
I have been able to pass the embedded JSON to an object after following this thread:
Best practice for embedding arbitrary JSON in the DOM?
How can I now successfully pass this object to the D3 bar chart?
Parsing the embedded JSON object was the hard part, so you've basically got this one figured out. Once you have the embedded JSON parsed and passed to an Object, you can just start using that Object.
Building off of your example, say you had this JSON data embedded in your page:
<script type="application/json" id="data">
{"name": "flare", "children":[{"name": "thing1", ... }]}
</script>
Then instead of using
d3.json("data/file.json", function(root) {
...
}
just extract the body of the function you were using, and load the JSON object at the top:
var root = JSON.parse(document.getElementById('data').innerHTML);
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
...
The method described in the question you've linked to will work. Just call the variable whatever you're using in your D3 code, e.g.
var root = JSON.parse(document.getElementById('data').innerHTML);

calling JSON webservice & using html

I've been using XML a lot lately but now I'm practicing with some JSON.
What I am trying to do is make a button and text box - so the user can type in a zip code and it will get the info for that zip code...
Using JSON from geonames.org
It's frustrating me trying to figure this out, I've found it easy when I was making my own files with XML but now I am trying to use an actual website and JSON.
Please show me how to do this! Would appreciate it! Thanks.
First of all HTML cannot process a json response from a server. You can send a get or post in json format to a server and get a json response back but you need something other than HTML to process that JSON message. Browsers can format and display XML but not JSON (they just display it as a string). The easiest way to do that in a browser is use JavaScript. For this I would recommend using the jquery library.
http://jquery.com
Here's an example of some jquery I used recently to process a returned JSON string.
$(document).ready(function() {
$(".img a").on("click", function(event) {
event.preventDefault();
var item;
if ((item= $(this).attr( 'href' ))=="saved") return false;
$(this).html("<div style='line-height:4em '>Saved</div>");
$(this).attr("href","saved");
var action ="add";
jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
var result=data.result;
if (result=="saved") {
self.html("<div>Saved</div>");
self.attr("href","saved");
}
}, "json")
.error(function() {
alert("error: unable to contact web service");
});
});
});
The returned JSON string from this request is { result: saved }. So as you can see you access the associated array as part of the data object. In my case data.result provided me with the value of result from the json string.
Note my example is for using an anchor tag to pass a value to send in the webservice call. In your case you will need to use a form.
If you're using jeoquery then just look at the html source of UI sample. It's showing the same autocomplete box that you might be trying to implement no custom code to write to parse returned JSON. Below code should work for you:
<input class="input-large" id="city" type="text"/>
$("#city").jeoCityAutoComplete();

JSON to usable array javascript

I'm trying to convert my JSON code to a usable array in javascript/jquery.
I have the following JSON code arriving via ajax:
[{"id":"9","firstname":"Greg","surname":"Bril","position":"0","busy":"0","disabled":"0"},{"id":"14","firstname":"Nai","surname":"Brooks","position":"1","busy":"0","disabled":"0"},{"id":"17","firstname":"Margaret","surname":"Grey","position":"1","busy":"0","disabled":"0"},{"id":"1","firstname":"Cameron","surname":"Grover","position":"0","busy":"0","disabled":"0"},{"id":"2","firstname":"Sarah","surname":"Grover","position":"0","busy":"0","disabled":"0"},{"id":"3","firstname":"Margaret","surname":"Hynes","position":"0","busy":"0","disabled":"0"},{"id":"4","firstname":"Stephen","surname":"Hynes","position":"0","busy":"0","disabled":"0"},{"id":"11","firstname":"Ben","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"15","firstname":"Elizabeth","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"10","firstname":"Grant","surname":"Mills","position":"0","busy":"0","disabled":"0"},{"id":"16","firstname":"John","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"13","firstname":"Lucinda","surname":"Ower","position":"1","busy":"0","disabled":"0"},{"id":"12","firstname":"Karina","surname":"Scott","position":"1","busy":"0","disabled":"0"}]
It is created and intepreted using:
$.getJSON( "tc_search1.php", {
leave: $("input#leave").val(),
end: $("input#end").val(),
override: $("#tc_override").is(":checked"),
tc_id: $("#tc_id").val()
}, function(data) {
//i cant get this part to work
});
I can't seem to manage to get the function on success to work. I tried the $.each method on jquery documentation website, but I can't get it right. Can anyone help?
The getJSON method will automatically parse the JSON string into a Javascript object.
The data parameter in your success callback function will be an array of objects. For example, the expression data[0].firstname will return "Greg".