Saving Javascript Array to PHP - php

Hello i am quite new to javascipt so please explain things clearly. I am currently running a php page which includes:
upp.php
<script>
document.getElementById("data").value = localStorage.getItem('itemsArray');
</script>
this items array contains objects which is saved like this:
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
$.post('upp.php',{ items: JSON.stringify(oldItems) }, function(response) {
window.location.href = "upp.php";
the result of the page appears like this:
[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]
is there anyway i can save this information into PHP and split the data so I can manipulate it one at a time like a loop or something. For example:
1st time:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
Next:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
etc.
Thanks.

upp.php:
<?php
$array = json_decode($_POST['items'], True);
foreach ($array as $key=>$line) {
# $key is a number like 1173627548
# and $Line is an array with methv, q1, q2, q3, q4, and comm
}
?>
That will show you the array it got from the JSON. Now you can work with the data.

Related

ChartJS Arrays Acting as One Item

I'm trying to import readings from mySQL database, and place them on a ChartJS.
$query = mysqli_query($conn, "SELECT * FROM readings
ORDER BY readings_id DESC LIMIT 2");
$distance = array();
$timestamp = array();
while($row = mysqli_fetch_array($query)) {
$distance[] = $row['river_height'];
$time[] = $row['time_stamp'];
}
This is the query I'm using and the method I'm doing to store readings in an array.
However, when I try to place these in a bar chart for example, the 2 readings will act as one.
I have the Javascript code as follows:
const time = <?php echo json_encode($time); ?>;
var canvasElement = document.getElementById("chart");
var config = {
type: 'bar',
data: {
labels: [time],
datasets: [{data:[10, 20]}],
}
}
I've tried quite a lot of things, but can't figure it out. I'm new to this, so it doesn't help. Any advice or help would be appreciated.
This is happening because your PHP is returning an array for the labels and then you put that array in another array. This tells chart.js that it has to be a multiline label as you can see.
To get the behaviour you want you need to remove the array brackets at the labels field like so:
const time = <?php echo json_encode($time); ?>;
var canvasElement = document.getElementById("chart");
var config = {
type: 'bar',
data: {
labels: time, // remove array brackets around time
datasets: [{data:[10, 20]}],
}
}
Assuming you want time_stamp as the X axis, and river_height as the Y axis, change to :
PHP :
while($row = mysqli_fetch_array($query)) {
$data[] = [
'x' => $row['time_stamp'],
'y' => $row['river_height']
];
}
JavaScript :
var config = {
type: 'bar',
data: {
datasets: [{
data: <?= json_encode($data) ?>
}]
}
};

Order Array by Relevant Search Results

I know that there has to be a library for this somewhere, but what I am trying to do is pass in an array of strings, and a search string and have it order the array by how relevant it is to the search string.
I have been having a hard time figuring out what to google to figure this out, anyone point me in the right direction?
preferably in php, or another server side language
I don't really know what you mean by 'revelant'..
But, if you want to find the best string based on a search string, you can use the Levenshtein algorithm. It calculate a "distance" between two strings.
More infos here : http://php.net/manual/fr/function.levenshtein.php
This is kinda tricky and I cannot really explain in English, so I'll just have to show you a working code. If you have an questions, you can ask.
<!DOCTYPE html>
<head>
<title>Search Array</title>
<script>
//so let's set an array of values we will be searching
function searchArray(dis) {
var bigContent = new Array('Jesus loves you','Angle','God in Heaven','Bala','Overcomer','Be born again','Adesuwa','Heaven is real','James','Apple','John the baptist');//this is the array that serves as your database
var searchi = dis.value, result = Array();
searchi = searchi.toLowerCase();
//order the array alphabetically
bigContent = bigContent.sort();
var content;
if(searchi !='') {
//Define the arrays for initial pre-storage
var keys = new Array(), contentArray = new Array();
//Loop through the content array to search for all occurence of string
for(var i=0;i<bigContent.length;i++) {
content = bigContent[i].toLowerCase();
if(content.indexOf(searchi) > -1) {//found the search in this value
//get the position of the search string in content
var pos = content.indexOf(searchi);
//make position the key for your content array
if(contentArray[pos]) {//check if this position has already been assigned to a content
//if yes, append this content.
contentArray[pos] += '[]'+bigContent[i];
} else {//else, set the content
contentArray[pos] = bigContent[i];
//only save the position the first time you find it, to avoid duplication
keys[keys.length] = pos;
}
}
}
//sort the key so it can order the values in ascending order(relevance)
keys = keys.sort();
//loop thru the key
for(var i=0;i<keys.length;i++) {
var key = keys[i];//remember the value of "var key" is the key for contentArray value
if(contentArray[key]) {//just to be sure it's ther
var thisContent = contentArray[key];
//check if the content has more than 1 value
if(thisContent.indexOf('[]') < 0) {//if it doesn't
result[result.length] = contentArray[key];
} else {//if it does
//convert content into array
var thisContentAr = thisContent.split('[]');
//Loop thru the array
for(var j=0;j<thisContentAr.length;j++) {
result[result.length] = thisContentAr[j];
}
}
}
}
}
document.getElementById('ov').innerHTML = '';
for(var i = 0; i<result.length;i++) {
document.getElementById('ov').innerHTML += '<div>'+result[i]+'</div>';
}
}
</script>
</head>
<body>
<div><input type="text" onkeyup="searchArray(this);" autofocus="autofocus" /></div>
<div id="ov"></div>
</body>
</html>

Storing valuesin a javascript array

Hello people here is my code
function send(Eqt_Param,Eqt_Param_value)
{
var Eqt_Paramv=Eqt_Param+'='+Eqt_Param_value;
alert(Eqt_Paramv);
}
every time Eqt_Param and Eqt_Param_value will be different ...iam sending values onclick so run this script for 5 times well i get 5 different values overall.but now i need to save each value in an array so that i can use the array element in the script function again,
plzz help me to fix this
var data = new Array();
function add(param, value){
var temp = {'param' : param, 'value' : value};
if (data.length >= 50)
data.shift();
data.push(temp);
}
Call the function after the processing like
add(Eqt_Param,Eqt_Param_value);
Create a global array variable, and simply assign the function to it.
var array = [];
function send(param, param_value) {
array[] = Eqt_Param + '=' + Eqt_Param_value;
}
or
var array = [];
array[] = send(param, param_value);
function send(param, param_value) {
return Eqt_Param + '=' + Eqt_Param_value;
}
The array will contain all the results anytime the function is run.
Hope this helps.
not sure if this is what u want... but u can try this out..
create a global array...
var globalArray=[];
use push() to push the values u want in the array
function send(Eqt_Param,Eqt_Param_value)
{
var Eqt_Paramv=Eqt_Param+'='+Eqt_Param_value;
alert(Eqt_Paramv);
globalArray.push(Eqt_Paramv); // i am pushing the result(Eqt_Paramv) here,
}

Php javascript conflict with passing javascript to php

I have a slight problem. I have several arrays in php with different team names. Each array contains teams of a certain league. When I click an add button I get the option to add a new entry to the calendar. I want the drop down to have only the teams for that league. onclick of the add button I call a javascript function that knows what division was clicked. However in order to give the javascript the information for which teams to display I have to pass it one of the php arrays. The problem I am having is telling php which array to pass to javascript depending on which league javascript is on. I don't want to specify the array myself because there is an option to add a league and this would mean having to code in more code each time a league is added. The point of the site is being dynamic.
here is some code.
for ($i = 0;$i<$sizeof($leaguesarray);$i++){
$htmlimploded[$i] = implode($html[$i]);
}
here I have used emplode to make all of my php arrays readable into javascript.
for (var h = 0; h<size; h++){ // goes through every league
if(h == leaguenum){ // finds the league for the clicked add button
// this is the line that I have trouble with I can't think of
//anyway of telling it which array to use since it is serverside code.
var myarray = ["<? echo $htmlimploded[]?>"];
}
}
Javascript code above.
Imploding works but why not json_encode($array)? It's a simpler, built in way to turn php arrays into javascript objects or arrays. If you have something like:
$league1 = array('team1', 'team2');
$league2 = array('team3, 'team4') ;
Then make a multidimensional associative array of these:
$all_teams = array('league1'=>$league1, 'league2'=>$league2);
encode it into a Javascript object and print it into your JS:
$encoded = json_encode($all_teams);
print 'var teamObject = '.$encoded.';';
If you were to console.log(teamObject) you'd see something like this:
{"league1": ["team1", "team2"], "league2": ["team3", "team4"]}
Looks complicated, but now you can pull out the array you desire very easily. The league 1 array is teamObject.league1 and the league2 array is teamObject.league2, and so on.
i think you missed something in the following code:
var myarray = ["<? echo $htmlimploded[]?>"];
By right, it should be:
var myarray = ["<?php echo $htmlimploded[]?>"];
Assuming that PHP knows the names of the leagues and the teams and that JavaScript knows the league name that is clicked, You can wrap the arrays of the team names inside an object with the league as the name of the property.
<?php
$arr = array("League1" => array("Team 1", "Team 2"),
"League2" => array("Team 3", "Team 4")
);
?>
var obj = {};
<?php foreach ($arr as $k => $v): ?>
obj.<?php echo $k; ?> = ["<?php echo implode('","', $v); ?>"];
<?php endforeach; ?>
Then when a user selects a league, you can loop through the array of the property (which is the league name) of the object.
clickedLeague = "League1";
for (var i = 0; i < obj[clickedLeague].length; i++)
{
console.log(obj[clickedLeague][i]); // Logs the team name to console
}

assigning value to array in javascript

in php you could do like this:
$key1 = 1;
$key2 = 1;
$array[$key1][$key2] = 'hi';
in javascript i tried with this:
key1 = 1;
key2 = 1;
var array = new Array();
array[key1][key2] = 'hi';
but it didnt work. how can i do the same thing in javascript?
Your problem is that you need to instantiate the inner array before assigning values in it
var key1 = 1;
var key2 = 1;
var array = [];
array[key1]=[];
array[key1][key2] = 'hi';
Or you could do it all in one:
var array=[['hi']]
Also, you should avoid assigning to specific indexes unless you're updating an existing element. The first example above will automaticly add an element
array[0]=undefined;
If you want to use specific keys, and not just indexes, you should use dictionaries or objects (dictionaries and objects are the same thing i javascript)
The key1 property of array is undefined at the time you are trying assign the property key2 to it. You need to actually indicate that array[key1] is an array before you start assigning values to it.
For example:
array[key1] = [];
array[key1][key2] = 'hi';
JavaScript is having a problem with the key1 and key2 dimensions of your array being undefined. To correct this problem, these are changes you could make:
var key1 = 1;
var key2 = 1;
// define "array" as an empty array:
var array = [];
// define "array[key1] as an empty array inside that array
// (your second dimension):
array[key1] = [];
array[key1][key2] = 'hi';
PHP does some magic -- you can simply supply 2 keys and PHP "knows what you mean" and will define the $key1 and $key2 dimensions without thinking about it. See: PHP: arrays: If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key.
JavaScript requires you to be more explicit about array creation.
You can find neat implementations. For example, here is a way, which is a function creating an array for the rows and then, creating an array for each column (could be anidated in the other way, but...)
var sDataArray=MultiDimensionalArray(7,2);
//alert(sDataArray[0][0]);
function MultiDimensionalArray(iRows,iCols)
{
var i;
var j;
var a = new Array(iRows);
for (i=0; i < iRows; i++)
{
a[i] = new Array(iCols);
for (j=0; j < iCols; j++)
{
a[i][j] = "";
}
}
return(a);
}
The thing is, you just can't work the arrays just like PHP ones. Must treat them the way they really are: an array of arrays (of arrays (of arrays (of arrays)...)).
Good luck.

Categories