I'm sending my mysql result to an associative array and then encoding with JSON
$showDisplayResult = $mysqlConn->query($getDisplayPage);
while($row=mysqli_fetch_assoc($showDisplayResult))
{
$rows[] = $row;
}
$showDisplays = json_encode($rows);
ANd in my main page I'm using javascript to grab this, parse it and append the correct variables into my URL. The functionality seems to work but it only shows undefined as the variables in the URL.
Here's the javascript:
<script type="text/javascript">
let obj = <?php echo $showDisplays; ?>;
//obj = JSON.parse(obj);
let params = new URL(document.location).searchParams;
params.set("pageID", obj.pageID);
params.set("display", obj.display_id);
let url = window.location.href.split('?')[0];
let nextURL = url + "?" + params.toString();
window.setTimeout(function () {
window.location.href = nextURL;
}, obj.duration * 1000);
console.log(obj);
</script>
So my URL is now showDisplay.php?display=undefined&pageID=undefined
How can I get this to parse the JSON correctly?
UPDATE:
If I echo $showDisplays, this is the JSON that prints:
[{"pageID":"104","page_type_id":"1","display_id":"3","slide_order":null,"duration":"56","active":"1","background_img":null,"panel_id":"96","panel_type_id":"1","page_id":"104","cont_id":"148","contID":"148","content":"\r\n\r\n\r\n<\/head>\r\n\r\nThis is full content<\/p>\r\n<\/body>\r\n<\/html>"},{"pageID":"116","page_type_id":"1","display_id":"3","slide_order":null,"duration":"54","active":"1","background_img":"images\/BG_spring.svg","panel_id":"113","panel_type_id":"1","page_id":"116","cont_id":"165","contID":"165","content":"\r\n\r\n\r\n<\/head>\r\n\r\nThis background should be green<\/p>\r\n<\/body>\r\n<\/html>"}]
So on page load i want the url to have display=3&pageID=104 then after 56 seconds (its duration) it should refresh and th URL should be display=3&pageID=116 for 54 seconds, and then keep the loop
If I read the code correctly, $showDisplays is an array of row objects, not a single row object. The JavaScript, however, tries to access properties of a row object as if they were on their containing array, obj.
If you want to access properties of the first row object in the array, you can do this with:
params.set("pageID", obj[0].pageID);
params.set("display", obj[0].display_id);
The next row object would be at the next index, obj[1]. So, in order to get all of the row objects in sequence, you would loop over them.
Related
So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply
i have code above which gets data from a database and then place in in json form to make it readable in java script.
the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],
"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();
Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];
Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];
in java script. Does Any one know how i can do this.
$query = mysqli_query($conn,"SELECT * FROM car_models");
// Loop the DB result
while(($result = mysqli_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){
// Create array for current user
$data[$result['Brand']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['Brand']][] = $result['Model'];
}
//json data
json_encode($data);
I found the solution. Simply added the json object in a variable and now am able to get the echo it to the console
`
//json data
var brandAvailable =
console.log(brandAvailable);
"`
I want to send multiple base64 strings via jquery's $post(). The number of strings are not always the same. How can I do this and fetch it in php?
Is it a good option to have all strings in an array and add them in $post()?
var items = [
"data:image/png;base64,i.....",
"data:image/png;base64,i....",
"data:image/png;base64,i...."
] //the number od these strings varies on each post
$.post("../send.php",
{
for(i=0;i<21;i++){
'item'+i: items[i]
}
},
)
php:
if($_POST['item1']){
$item1 = $_POST['item1'];
}
I would go with the following steps:
1) Create a form with the input fields that contain all these base64 strings. (the form and all its fields can all be hidden in html)
2) In my form all the input text fields can have the same name like in this case
<input type="text" name="text1[]">
2) When I need to add a new string, I shall add an input field in that form by using jQuery.append()
3) in my jquery post i will set the data to
$.post('../send.php',$('#myFormId').serialize(),function(){
// what i want to do with the response
})
4) in my php page I can easily loop over
foreach($_POST['item1'] as $item){
// do what you want with data
}
that's it!
Try this
JS :
$.post("../send.php",{items:items}); //send to server
PHP:
$_POST['items'] // catch in server
I would create a regular array of strings, and then iterate to the array of strings and add them as properties of an object using a for loop. Here's an example.
var items = []; // Empty array.
items.push(item1, item2, item3); // Add Base64 strings.
var postdata = {}; // An object for our postdata.
// Iterate through the array and add items as properties to the object.
for (var _i = 0, _j = items.length; _i < _j; _i++) {
postdata['item_'+_i] = items[_i]; }
// POST the object to the PHP file.
$.post("../send.php", postdata);
Then, in PHP, you get $_POST['item_1'] until $_POST['item_n'] from jQuery. :)
UPDATE
You can process the postdata in PHP like below.
<?php
foreach($_POST as $k => $v) {
// Do things for each item POSTED.
// This will end after the last POSTed item is reached.
// $k is the 'key', as in what's inside the square brackets of $_POST[]
// $v is the 'value', as in $_POST[key] = "THIS STUFF";
}
?>
Hope that was helpful!
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];
when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...