I've the below combination of server-side and client-side json processing code. I'm able to load json data from remote url and from local .js file.
But, somehow I'm unable to figure out how to load data from the serverjson object in the below code snippet.
var json ;
<#list jsons as json>
serverjson = ${json};
console.log(serverjson);
$.getJSON(---have to load data from json object----).done(function (jsonData) {
var time = 0; var curc = 0; var prec = 0;
$.each(jsonData.current.timeSeries, function(i,item){
//console.log(jsonData.current.timeSeries[i].beginTimeSeconds+" : "+jsonData.current.timeSeries[i].endTimeSeconds+" : "+jsonData.current.timeSeries[i].inspectedCount);
time = jsonData.current.timeSeries[i].beginTimeSeconds;
curc = jsonData.current.timeSeries[i].inspectedCount;
//curdata.addRows([curc]);
curdata.push(curc)
//data.addRows([[jsonData.current.timeSeries[i].beginTimeSeconds,jsonData.current.timeSeries[i].endTimeSeconds,jsonData.current.timeSeries[i].inspectedCount]]);
});
</#list>
So, to conclude, I'm not passing remote url or .js file in the $.getJSON() function, I need to pass serverjson object.
Please help me how to solve this.
Thanks in advance.
Instead of:
$.getJSON(---have to load data from json object----).done(function (jsonData) {
// code
});
do:
var jsonData = JSON.parse(serverjson);
// code
Related
This a bit complicated situation I have myself in. I have a PHP file in which I am generating data from DB dynamically. More like when a page is scrolled then data is fetched. So I have two PHP files file1.php and file2.php. file1.php has an ajax that fetches data from file2.php and displays it on its page.
Ajax in file1.php:
$(document).ready(function(){
var limit = 4;
var start = 0;
var action = 'inactive';
function load_posts_data(limit,start)
{
$.ajax({
url : "fetch-message.php",
method : "POST",
data : {limit:limit,start:start},
cache : false,
success : function(data)
{
$('#message_body').append(data);
if(data=='')
action = 'active';
else
action = 'inactive';
}
});
}
if(action=='inactive'){
action = 'active';
load_posts_data(limit,start);
}
$(window).scroll(function(){
if($(window).scrollTop()+$(window).height()>$("#message_body").height()&& action=="inactive"){
action = 'active';
start = start + limit;
setTimeout(function(){
load_posts_data(limit,start);
},100);
}
});
});
Now, file2.php has codes which are extracting data from DB 4 at a time. The problem is that I need to use a variable in file2.php say (variable name, var) which is in file1.php and I have failed to find any solution online. Please help.
You can't directly access PHP variables from Javascript or vice versa ! period. but what you can do instead is while returning the response from the file2.php (where you echo or pass the response according to the ajax call) you can return an array with all the required variable values like this.
return array = [
'data' => $data,
'var1 => $var1,
.
.
'varN' => $varN,
];
and from javascript where you process the response you can simply parse the response, for further reading you can google about :`parsing json in javascript
So basically what I'm doing is auto filling a textbox using AJAX to grab information from a PHP script that calls a C function.
This is what I've found in theory: (Assuming receiving only one value)
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response) {
$('#v1').val(response);
});
}, 5000);
});
Now, if this works, which I believe it will. If I receive an array of values, then the input inside of function cannot be response, correct? So what would I have to change it to make it an array?
Just to be clear, my PHP script is using echo to output its information. I'd rather output in such a more "standard" manner as in V1 = 120, V2 = 120, etc. but PHP is new to me and that I am currently researching. Thank you.
EDIT:
Just to make it clearer
Would something like this work?
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
$('#v1').val(response[0]);
$('#v2').val(response[1]);
$('#v3').val(response[2]);
});
}, 5000);
});
Since you echo on PHP side, the response just can be a string.
But if that string if formed as a valid JSON, you will be able to use it like you wish.
So on PHP side, make sure the json format is valid:
$array = [120,340,800];
echo json_encode($array);
Then in JS... You received a string... You have to parse it to make it an array.
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
var responseArray = JSON.parse(response);
$('#v1').val(responseArray[0]);
$('#v2').val(responseArray[1]);
$('#v3').val(responseArray[2]);
});
}, 5000);
});
Per the OP update, you could try something like this to map each item of the array up to its corresponding text box you could do.
$.post(ajaxurl, NULL, function (response) {
for (var i = 0; i < response.length; i++) {
$("#v" + (i + 1)).val(response[i]);
}
});
This would map each index of the array returned from the JSON endpoint, to a corresponding text box.
If the JSON being returned from your endpoint is a valid JSON array, your response variable should already be an array!
Send your array as json:
echo json_encode(array($value1, $value2, $value3));
JS
$.post(ajaxurl, NULL, function (response) {
// selectors in same index order as response array
$('#v1, #v2, #v3').val(function(i){
return response[i];
});
},'json');
The easiest way (for me) to communicate between javascript and PHP is JSON.
So your PHP script have to generate an answer in this format.
PHP code
// At the top of your PHP script add this
// that will tell to your browser to read the response as JSON
header('Content-Type : application/json', true);
// Do your logic to generate a PHP array
echo json_encode($yourArray);
HTML code
<div class="someClass"></div>
Javascript code
var container = $('.someClass');
$.post(ajaxurl, NULL, function (response) {
console.log(response); // for debuging
for (let i = 0; i <= response.length; i++) {
let myItem = response[i];
container.append('<p>' + item + '</p>');
}
});
It's cleanest to generate dynamically the p elements because you don't know how many results your PHP file will return you.
I'm not sure of the javascript code, you maybe will received a json string that you have to transform to a Javascript Array
Before link you javascript to php script, try some call with postman (or others http client) to ensure that your 'webservice' is working as excepted
i have a file locally which has array of objects in my view i need it to be warped as a variable, on viewing the variable that array should be used
i tried this but i dont know its the right way could some one help me
var url = 'proj/array/arrayobject';
console.log(url);
var refreshId = setInterval(function(){
$('div.comment-container').comment({
//here i should call that url and display object one by one with equal intervals
})
}, 1000);
could some one help me
First of all I would suggest to keep that file as JSON file having .json extension. It would make the file purpose more clear.
Secondly, You can use jQuery Ajax's getJSON() method to get data of that file and assign it to your local or global variable like below:
var myGlobalVariable = null;
$.getJSON("proj/array/arrayobject.json", function( data ) {
myGlobalVariable = data;
});
Then, You can use your myGlobalVariable in your code. But, Make sure that you use it once you get data in it. For this you can use callbacks.
For your scenerio, Code will be like below:
var url = null;
function init() {
$.getJSON("proj/array/arrayobject.json", function(data) {
url = data;
MyFunc();
});
}
function MyFunc() {
setInterval(function() {
$('div.comment-container').comment({
// use url here
})
}, 1000);
}
$(function() {
init();
});
I got some code off a tutorial a couple of months ago that I am now changing and using in my site. I have already coded alot so do not want to go another route.
Basically I need to retrieve all posts from a database and display on screen dynamically without refreshing the page. now I have the XML that is generated from the PHP file - all is good. Where I am stuck is reading that XML o the ajax side. here is what I have so far:
function getAllPosts() {
alert('hi');
var count = 0;
var tlu = getUrlVars()["user"]; // tlu stands for time line user
var data = 'user='+tlu;
$.ajax({
url: 'getAllPosts.php',
type: 'POST',
data: data,
success: function(response){
var xml = response.responseXML;
var posts = xml.documentElement.getElementsByTagName("post_item");
for (var i = 0; i < posts.length; i++) {
var id = posts[i].getAttribute("id");
var account_name = posts[i].getAttribute("account_name");
var author = posts[i].getAttribute("author");
var type = posts[i].getAttribute("type");
var data = posts[i].getAttribute("data");
var postdate = posts[i].getAttribute("post_date");
categoryPost(id, account_name, author, type, data, postdate);
}
}
});
}
function categoryPost(id, account_name, author, type, data, pastdate){
if(type === 'write'){
alert("hello");
}
}
It is running the alert("hi"); test but not the rest of the code.
My console gives me this: Uncaught TypeError: Cannot read property 'documentElement' of undefined
How can I read the elements from the xml? Everywhere I look has that XMLHTTP stuff and I don't, so I am pretty confused...
Thanks in Advance
If you are expecting an XML response, try setting data type: 'xml'. In your $.ajax parameters. If you're still having issues. Log the response object by using console.log(response) to examine what is actually being returned or you can use Chrome's postman extension. Comes in handy ;-).
I use a dojo request.get to read a txt file in JSON format, but can't convert it to JSON object.
The "datagrid.txt" stored some data as:
[
{"col1":"val1", "col2":"val2", "col3":"val3"},
{"col1":"val1", "col2":"val2", "col3":"val3"},
{"col1":"val1", "col2":"val2", "col3":"val3"}
]
The requesting client code is as:
require(['dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore', 'dojo/dom', 'dojo/request', 'dojo/domReady!'],
function(lang, DataGrid, ItemFileWriteStore, dom, request){
request.get("datagrid.txt",{
// Parse data from JSON to a JavaScript object
handleAs: "json"
}
).then(
function(text){
var datalist = JSON.stringify(text);
for(var i = 0, l = 16; i < l; i++){
console.log( datalist[i] );
}
});
The console.log displays things in string(such as "[","{"), not what as I expected an array({"col1":"val1", "col2":"val2", "col3":"val3"}), which I could used to populate a dojo datagrid data store.
Dojo can handle the JSON format on its own. Official docs
I think your Problem lies in the way you're writing your datagrid.txt and the style you try to read the data later.
Here's my solution:
require(['dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore',
'dojo/dom', 'dojo/request', 'dojo/domReady!'],
function(lang, DataGrid, ItemFileWriteStore, dom, request){
request.get("datagrid.txt",{
// Parse data from JSON to a JavaScript object
handleAs: "json"
}
).then(
function(text){
var datalist = [];
dojo.forEach(text,function(thisText,i){
//add each single Object from the datagrid.txt to datagrid-array
datalist.push(thisText);
//alert the newly added item in datagrid
console.log(datalist);
});
});
I think this should fix your Problem.
Regards, Miriam