Within my HTML view file I have a link that looks like this:
url: 'http://localhost:3000/readings?limit=100&nodeID=0001'
This is part of an Ajax call that gets readings from my local database for nodeID = 0001.
In the corresponding .js controller file I have the following function:
.controller('ReadingsViewCtrl', function ($scope, $routeParams)
{
$scope.model = {
message: $routeParams.id}
});
I can now address the ID as {{model.message}} within my HTML view file.
What I want to do is somehow embed the {{model.message}} into the URL above so that I can get readings for arbitrary nodes, i.e. have something like url: 'http://localhost:3000/readings?limit=100&nodeID={{model.message}}'
This way I can get readings for an arbitrary nodeID passed in as a parameter instead of just node 0001. How can I do this?
EDIT: As asked here is the rest of the function that contains the URL property, it is part of an Ajax call that gets data from my database.
$.ajax({
url: 'http://localhost:3000/readings?limit=100&nodeID=0001',
dataType: 'json',
type: 'get',
cache: true,
success: function(data){
var jsonobject = [];
$(data).each(function(index, value){
var list = [];
var m = moment(value.time, 'YYYY-MM-DDTHH:mm:ss.SSSZZ');
var ts = moment(value.time).valueOf();
console.log(ts);
list[0] = ts;
list[1] = value.litres;
jsonobject.push(list);
})
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'Water consumption in Litres/sec'
},
series : [{
name : 'Litres per flush',
data : jsonobject,
tooltip: {
valueDecimals: 2
}
}]
});
console.log(jsonobject);
}
});
Related
I am using the Rasa X HTTP API to parse a yaml file and convert to a JSON object. I want to take this JSON object and then send it to my datatable to populate the rows. The problem is when I populate the datatable when calling the function in my datatable javascript, the JSON returns like this:
The API according to the docs here turns the payload into JSON format: https://rasa.com/docs/rasa-x/pages/http-api#operation/getDomain
Here is my code for the HTTP API:
export function getDomain(token) { //used to get auth token which is recreated each instance
var data = ""
//console.log(token);
var header_data = { Authorization: "Bearer " + token }
//console.log(header_data);
var sendData = {} //data to send. Check Rasa x API doc
$.ajax({
url: 'http://localhost:5002/api/domain',
type: 'GET',
async: false,
headers: header_data,
success: function (resp) {
//put name of json value you want to read after 'resp.'
//console.log(data);
var jsonDomain = yaml.parse(resp);
data = jsonDomain.entities;
console.log(typeof (data));
return data;
},
error: function (error) {
console.log('Error ${error}');
}
});
return data;
}
This function above parses the yaml file to get the data
export function getAuth() { //used to get auth token which is recreated each instance
var data = "";
var sendData = { "username": "me", "password":"huiwehfuiwfa" } //password changes each instance, there is a way to create a constant one too
$.ajax({
url: 'http://localhost:5002/api/auth',
//projects/default/intents',
type: 'POST',
async: false, //depracted but needs to be included to have it work
headers: {
"Access-Control-Allow-Origin": "*"
},
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendData),
success: function (resp) {
data = resp.access_token; //put name of json value you want to read after 'resp.'
return data;
},
error: function (error) {
console.log('Error ${error}');
}
});
return data;
}
This function gives authorization to use the API, gets the datatype as JSON, and stringifys it.
The console log for this shows as an object:
(3) ["plant", "water", "temperature"]
0: "plant"
1: "water"
2: "time"
length: 3
I then call this function to be able to use the data from the API in my datatables javascript:
import { getAuth, getDomain } from "./yaml.js";
export function populateTable() {
var token = getAuth();
var table_data = getDomain(token); // this gets the JSON data
var ieColumns = [{
title: "Name",
type: "text"
}];
var E = $('#Forestry').DataTable({
"sPaginationType": "full_numbers",
data: table_data,
columns: ieColumns,
dom: 'frtBip', // Needs button container
select: 'single',
responsive: true,
altEditor: true, // Enable altEditor
buttons: [
{
text: 'Add',
name: 'add' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Edit',
name: 'edit' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Delete',
name: 'delete' // do not change name
}
], style: "width:100%"
});
When I try to parse the JSON data using the parse function, I get an error from datatables complaining it is not in valid format.
I have also wrapped the function call getting the data from the API in brackets like this
var table_data = [getDomain(token)]; // this gets the JSON data
This returns one row with the first element in the JSON object which is plant but not the others.
The object type this returns is an array(3).
I want it to return each element in a separate row.
I have a an extjs 4.2 combobox that I'm using to display some data. Now I'm trying that based on a condition the combo would display a default value. I managed to return the needed data based on that condition, however I'm failing to set the necessary value in the combobox. How am I supposed to set that specific value?
combo:
var locationStore = Ext.create('Ext.data.Store', {
model: 'model_LOCATION',
proxy: {
type: 'ajax',
url: 'Record?DB=GEO&Table=LOCATION',
reader: {
type: 'xml',
record:'record'
}
},
autoLoad:true
});
var C_LOCATION= Ext.create('Ext.form.ComboBox', {
name : 'C_LOCATION',
id : '${DB}.${Table}.C_LOCATION',
store : locationStore,
queryMode : 'local',
displayField : 'display',
valueField : 'value',
});
AJAX call:
var data;
var code = 111;
data = "CODE ='" + code + "'";
var text;
$.ajax({
type: "POST",
url: "Record?DB=GEO&Table=LOCATION",
dataType: 'xml',
data: {
"Where": data
},
success: function(xml) {
text = xml;
Ext.getCmp('${DB}.GEO.LOCATION').setValue(text);
}
});
Give the combo box a reference in the config section (reference: 'comboBox'). Then call comboBox.setValue(defaultValueGoesHere) in your function where you are getting the specific value. You may need to hunt down the comboBox reference depending where you are.
I guess you will have to parse your XML response. Similar as in your code definition for the locationStore, where you specify the record in the xml response.
Why do you make the second ajax call?
Could you not filter the locationStore based on the CODE value, instead?
I have the following code on index page the script contains part of the code that will call the data from test page
<div class="leftbox" id="proddisplay">
</div>
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
From test.php i am getting json array that looks like this
[1,2,"text","text2"]
I want to display the json array data in a tabular form and display it inside the div. the view of table should be something like this (it will have some css of its own)
static text: 1
static text: 2
static text: text
static text: text2
static text will be given by me and remains the same throughout however the values of array would change. can anyone tell how i can do so
individually i can display the data from json, but here i also need to put json data in a table and then put that table within a div
First of all you need to encode the array in php before sending to frontend, use json_encode() and then decode it in the success function using JSON.parse() . After just run a loop throught the array.
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
var returneddata = JSON.parse(returndata);
var htmlData= '';
for(var i=0; i<returneddata.length; i++){
htmlData+= 'static text: '+returneddata[i]+' <br>';
}
$('#proddisplay').html(htmlData);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
I wrote two functions,assume that one of them get us list of all notifications and one of them get new notification, i wrote a script which call first method and get list of all notifications in Json format, and write another script which call second method every 8 second, and get us new notifications in Json format too. i show these notifacations in a KendoUI Datasource. so i have two datasource for just one KendoUI Datasource component, i want to add two data source in one datasource, is there any way to do this?
EDIT: This is my code
<script id="template" type="text/x-kendo-template">
<tr>
<td>#= ID #</td>
<td>#= TITLE #</td>
<td>#= DESC #</td>
</tr>
</script>
My first script which get us list of all notification :
var datas = function () {
var objects = [];
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetNoti",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
for (var i = 0; i < response.d.length; i++) {
objects.push({ 'ID': response.d[i].ID, 'TITLE': response.d[i].TITLE, 'DESC': response.d[i].DESC });
}
},
});
return objects;
};
var dataSource = new kendo.data.DataSource({
data: datas(),
change: function () {
$("#movies tbody").html(kendo.render(template, this.view()));
}
});
dataSource.read();
and this is my seccond script which call method that give us new notifications every 8 sec:
$("#go").click(function () {
setInterval(
function () { test2();}, 8000);
});
var p = function () {
var objects = [];
$.ajax({
type: "POST",
url: "./WebForm1.aspx/GetUnCheckNotification",
data: {},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
for (var i = 0; i < response.d.length; i++) {
objects.push({ 'ID': response.d[i].ID, 'TITLE': response.d[i].TITLE, 'DESC': response.d[i].DESC });
}
},
});
return objects;
};
function test2() {
var dataSource2 = new kendo.data.DataSource({
data: p(),
change: function () {
$("#movies tbody").html(kendo.render(template, this.view()));
}
});
dataSource2.read();
}
Now i want some thing like this :
dataSource = dataSource + dataSource2
dataSource.read();
Is there anyway?
JSON format cab be a nested structure. Define a view model and then use it.
public class Report
{
public int Id {set; get;}
public string Title {set; get;}
public string Desc {set; get;}
}
public class MyReportViewModel
{
public List<Report> NewNotifications {set;get;}
public List<Report> AllNotifications {set;get;}
}
Then serialize this new MyReportViewModel { ... } using Json.NET library (server side).
On the client side, you can use the returned JSON format as usual.
Never tried anything like this. But when I was looking for your answer, I found this link at Telerik Forums.
Two Data Sources, One Grid
This might help.! :)
Using Struts2.
In my Action I have a List<Person> persons;
In javascript, I have this function:
function mytestfunction() {
var url = "MyAction_mytestfunction.action";
var params = {};
var arr = [];
var p1 = { "firstname" : "John", "lastname" : "Doe"};
var p2 = { "firstname" : "Rob", "lastname" : "Smith"};
arr.push(p1); arr.push(p2);
params["persons"] = arr;
$.post(url, params, function(data) {
console.log("done");
});
}
Problem is, the post() never reaches the action. There are no errors in the logs, nothing.
This all changes if instead of posting objects I post primitives. So when I have a List<Integer> nums in the Action and params["nums"] = [1,2,3]; in javascript, everything is posted fine.
So, is there a way to post JSON objects to a Struts2 action via javascript/jquery?
I should mention that I'm using the struts-jquery plugin, not dojo.
I don't know anything about struts, but this is how I POST objects with json:
$.ajax({
type: "POST",
data: JSON.stringify(SOME_JAVASCRIPT_OBJECT),
contentType: "application/json; charset=utf-8"
// etc: etc
});
you can try as following example:
$.ajax({
type: "Post",
url: "action_name", //you can pass through querystring like actionname?paramname=value
data : {
//here comes your param or array
},
dataType:"json",
contentType: "application/json; charset=utf-8",
});
If you want to pass through querystring type must be GET