Thanks everyone solved by using JSON.parse(xhttp.responseText);
hello i trying to fill up datatable from a php file the data is generator from database then use echo json
and handle the response from javascript here is the php file
<?php
global $wpdb;
$db_list = $wpdb->get_results("SELECT dbtest.FName, dbtest.SName FROM dbtest");
echo json_encode($db_list);
exit;
?>
and here is how i trying to handle the data in javascript
<script>
const xhttp = new XMLHttpRequest()
xhttp.open("GET", "datatabletest.php")
xhttp.send()
http.onload = function() {
var response = xhttp.responseText;
console.log(response);
//from here problem start
$('#example').DataTable({
"data": response,
"columns": [
{ "data": "FName" },
{ "data": "SName" }
]
});
}
</script>
but it alert error DataTables warning: table id=example - Requested unknown parameter 'FName' for row 0, column 0.
it looks like the data from response is null but in console it showing as
[{"FName":"test","SName":"test2"}]
so i have tried to copy this line from console and add it into a var like
var jsdata = [{"FName":"test","SName":"test2"}];
//then use
$('#example').DataTable({
"data": jsdata,
"columns": [
{ "data": "FName" },
{ "data": "SName" }
]
});
}
and that worked so why it not working from the response what is missing to make it work like that
Related
I have issue using POST Function, I want to transform Transfer Order to Item Receipt, But when I tried to execute the script, it failed with error "org.mozilla.javascript.EcmaError: SyntaxError: Empty JSON string (INVOCATION_WRAPPER$sys#24".
Anyone can help me about my issue ?
Here is my Suitescript Code :
function postData (receiptItem) {
doValidation([receiptItem.recordtype], ['recordtype'], 'POST');
if (receiptItem.recordtype == 'transferorder') {
var recordId = [];
var recStr = [];
var objRecord = record.transform({
fromType: record.Type.TRANSFER_ORDER,
fromId: 131, // transfer Order internalid
toType: record.Type.ITEM_RECEIPT,
defaultValues: {
customform: '433'}
});
var itemReceiptId = objRecord.save({
enableSourcing: false,
ignoreMandatoryField: false
});
recordId.push(itemReceiptId)
log.debug({
"title": "[success] recordId: ",
"details": recordId
});
var recLoad = record.load({
type: receiptItem.recordtype,
id: recordId.getValue('internalid')
});
recStr.push({
use_form: recLoad.getText('customform'),
tran_id: recLoad.getValue('tranid'),
tran_date: recLoad.getValue('trandate'),
tran_from: recLoad.getValue('transferlocation'),
tran_to: recLoad.getValue('location'),
tran_ord_id: recLoad.getvalue('createdfrom'),
tran_memo: recLoad.getValue('memo')
});
log.debug({
"title": "recStr",
"details": recStr
});
return recStr;
}
}
return {
post: postData
};
});
It's a syntax error, very likely some misplaced bracket.
Make sure you are posting valid JSON and that the content type is set on your request
You must send data as JSON. if empty or no data then send {} at least in POST as ContentType is Application/JSON. ECMA Standard. The error message clearly states that "Empty JSON string".
Then try this in Postman tool.
I want to create an object by sending a json to my webserver and parsing the information.
My javascript looks like this:
import { HTTP } from '#ionic-native/http/ngx';
....
constructor(private http: HTTP){}
...
// combining and sending the information below
createMediaObject(): Observable<any> {
var url = `${ApiServerUrl}/add_mo`;
url = encodeURI(url);
var convertedData = {
type: "Feature",
geometry: {
type: "Point",
coordinates: [Number(this.mediaObjectForm.value.lng).toString(), Number(this.mediaObjectForm.value.lat).toString()]
},
properties: {
icon: this.mediaObjectForm.value.icon.toString(),
tags: this.mediaObjectForm.value.tags.toString(),
topic: this.mediaObjectForm.value.topic.toString(),
title: this.mediaObjectForm.value.name.toString(),
description: this.mediaObjectForm.value.description.toString(),
rotation: this.rotation.toString(),
media: this.mediaObjectForm.value.contents.toString()
}
};
return from(this.http.post(url, convertedData, {})).pipe(map(res => res.data));
}
Now I want to parse the informatik in php using the solution from this post get POSTed JSON Array in php:
$params = json_decode(file_get_contents("php://input"), true);
echo json_encode(array("status" => empty($params)));
try {
// get posted data
echo $params["type"];
if (isset($params["properties"]["topic"])) {
$object->topic = $params["properties"]["topic"];
echo $object->topic;
}
However:
echo json_encode(array("status" => empty($params)));
Output: {"status" : "true"} -> that means that something went wrong and params is empty
same with
echo $object->topic;
Output: null
Is there a problem in the frontend or backend?
Do I need to change something inside of my configs?
<script>
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
alert("state data"+data);
});
</script>
I have the value in data and want to show in javascript given below.
The fields data is given want to push my state data there.
<script>
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
</script>
Both are written in diffrent script
datasets is an array with an object on index 0. So to define or redeclare the data property in there the syntax is
salesChartData.datasets[0].data = data;
Use it in your callback function:
function(data) {
salesChartData.datasets[0].data = data;
});
Not sure if I understand correctly, is this what you need?
var salesChartData = {
datasets: [
{
data : {}
}
]
};
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
salesChartData.datasets[0].data = data;
});
Just set the data after receiving it
if you need to show the ajax result in a variable salesChartData, you can try this
salesChartData.datasets[0].data[0] = "new data"
salesChartData is a JSON object with key datasets contains an array of JSON objects.
So if salesChartData is declared globally, then you can replace in the success of the ajax
Here below, it done using web storage. This is used to access from different file.
// File 1
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
localStorage.setItem("salesChart", JSON.stringify(salesChartData));
//-----------------------------------------------------------------------
// File 2
var salesChartData = JSON.parse(localStorage.getItem("salesChart"));
// ajax call
$.getJSON('chartState', {
stateCode: $(this).val(),
ajax: 'true'
},
function (data) {
alert("state data" + data);
salesChartData.datasets[0].data[0] = data // "new data"
});
Hope this will work.
Thank You
I have done with my self
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
var chr=data;
var a=chr[0];var b=chr[1];var c=chr[2];var d=chr[3];
var e=chr[4];var f=chr[5];var g=chr[6];
After that I have sended one by one data
var salesChartData = {
datasets: [
{
data : [g,f,e,d,c,b,a]
}
]
};
As you mention that both parts of the script are in different tags you can solve the problem with a global, this is not recommended. The better solution would be to refactor the structure and not have multiple script tags. But if you have no control over this then you should do something like this:
<script>
// No var used to make it global
chart_state_data = false;
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
// the data is set to this variable on callback
chart_state_data = data
});
</script>
And:
<script>
// chart_state_data contains data retrieved from ajax call or false
var salesChartData = {
datasets: [{
data: chart_state_data
}]
};
</script>
I am trying to create a table using DataTable but having a hard time getting DataTable to load with JSON object.
function getData() {
var request = new XMLHttpRequest();
var json = "link-to-my-json-object";
// Get JSON file
request.onload = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var JSONObject = JSON.parse(request.responseText);
createTable(JSONObject);
} else if(request.status == 400) { console.log("Error", request.status);}
};
request.open("GET", json, true);
request.send();
}
Requesting the JSON file via a XMLHttpRequest() request.
short sample of the JSON object:
{
"meta": {
"version": 1,
"type": "test"
},
"reports": [
{
"report-metadata": {
"timestamp": 1528235303.721987,
"from-ip": "0.0.0.0"
},
//and so on...
Currently only trying to show the meta part in a DataTable table:
function createTable(jsonData){
$(document).ready(function(){
$('#table').dataTable({
data: jsonData,
columns: [
{ data: 'meta.type' },
{ data: 'meta.version' }
]
});
});
}
index.html part:
<table id="table" class="display" style="width:100%"></table>
Only getting a No data available in table when running, and I am obviously missing something.
The "data" attribute for initializing your Data Table is expecting a list (Each element representing a row). Modify your ajax response, so each row is an element in the jsonData list. I also added quotes around all the JSON options.
var jsonData = [
{ "meta": { "version": 1, "type": "test" } }
];
$('#table').DataTable({
"data": jsonData,
"columns": [
{ "data": "meta.type" },
{ "data": "meta.version" }
]
});
https://datatables.net/reference/option/data
Since you want to load your data via ajax, you should look at the ajax options built in to the DataTables API. https://datatables.net/manual/ajax
I am using the DataTable plugin.
I am loading the DataTable. Then I am attempting to reload the table, while preserving the existing content, with additional information acquired from another json file. However, there is no reload occurring.
var resourcetable = $('#table').DataTable({
"ajax": {
"url": "QueryDataService.asmx/GetData1",
"dataSrc": ""
},
"columns": [
{ "data": "Column1" },
{ "data": "Column2" },
{ "data": "Column3" } ]
});
resourcetable.ajax.url("QueryDataService.asmx/GetData2").reload();
The error I see is: Uncaught TypeError: resourceusagetable.ajax.url(...).reload is not a function
Appreciate your help.
Thank you.
reload() is callable from ajax, not url(). load() is callable from url(), so i would try resourcetable.ajax.url("QueryDataService.asmx/GetData2").load();