Converting PHP XPathNodeList to javascript array? - javascript

I have a small PHP script I have written that gets reviews from a website. However, I am trying to display them in Javascript but cannot get the values through to the JS.
in PHP I have the variable $reviewTitles populated using:
$reviewTitles = $xpath->query("//*[#class='" . $reviewStr . "']");
and I can access each value in PHP by using
$title = $reviewTitles->item($x)->nodeValue;
Where $x is the index of the title to display.
My question is how can I convert whatever object the php variable $reviewTitles holds into javascript, So I am able to access each title via a JavaScript array.
I have tried:
<script language="JavaScript" type="text/javascript">
var titles = '<?php echo json_encode($reviewTitles); ?>';
var titles_data = JSON.parse(titles );
window.alert(titles_data[0]);
</script>
But get nothing - What am I doing wrong?
Thanks for taking the time to read this.

Related

Use data-attribute in javascript to alter elements width

I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:
Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (i.e. graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):
<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>
The value of the data-attribute with the name "somedat" I want to use in js, like so:
var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;
What I did?
I checked whether the format of the value is right. I therefore set a 'static' variable var somevartest = '20%'; and used it in the code above. It worked and the graph changed accordingly.
I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (i.e. 'x%').
What is it that Im not getting? How can I solve my problem?
The proper way to pass data from PHP to JavaScript is using a JSON string.
PHP:
<?php
$arr = get_from_database_as_array(...);
// at end of page before your scripts:
echo "<script>";
echo "var data = " . json_encode($arr, true) . ";";
echo "</script>";
HTML:
<script>
console.log(data);
document.getElementById("elem1").style.width = data["elem1"] + "px";
document.getElementById("elem2").style.width = data["elem2"] + "px";
// and so on.
</script>

How do I convert a php date_diff value to a javascript integer?

I'm trying to use the difference between two dates to help me draw lines on an HTML canvas. I generate one date in PHP and extract the other which is stored in an SQL database
When I keep everything in PHP the echo'd output is exactly what I expect. However, when I json_encode the output, which I expect to be an integer, to use to draw the shape I want on the canvas, a completely different number is presented from javascript.
I'm pretty sure it has to do with the json encoding ... but I haven't been able to find any reference about how to do this properly.
Here's the PHP I use to grab, format, and create a date difference output:
$sdt = new DateTime($row['sdate']);
$today = new DateTime('now');
$sdiff = date_diff($sdt, $today);
$sdelta = $sdiff->format("%a");
If I keep all of this in PHP and either echo the variable or echo the json_encode variable I get the expected answer, which is 34.
echo $sdelta;
results in 34
echo json_encode($sdelta);
results in "34";
echo json_decode($sdelta);
results in 34;
However when I assign this value to a javascript variable and test the result of the assignment:
var diffdt = <?php echo json_encode($sdelta); ?>;
alert(diffdt);
The alert popup shows 199.
If anybody could help me with this issue, I'd be eternally grateful.
Extra information...
Column type for sdate is DATE
query I'm executing is to get the data is:
$stmt = $link->prepare("SELECT * FROM register WHERE id = ? ");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$num = $result->num_rows;
$row = $result->fetch_assoc();
var_dump($row['sdate']);
Number of rows is 1.
vardump result is: string(10) "2019-09-27"
Must use "Number(your_number)" method I used here,see bottom line:
<script type="text/javascript">
// To set two dates to two variables
var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
console.log(Number(Difference_In_Days));
</script>
Ended up resolving this issue by moving php code outside some of the javascript I had written. Problem was from a for loop I had implemented that updated javascript values from the php loop. This was adding up the result. None of my code actually changed, it was just rearranged.
Didn't think this was an issue since the for loop was doing it's job for what it was designed.
Thanks everyone for your help. It allowed me to eliminate most of the other potential issues.
airider74 When you say that PHP shows the correct data but JS does not, what are you using to display the values-- i.e. console/terminal/browser etc. ? Are they both using UTF8? Something you might try is encoding the output from the PHP via urlencode() and then decode it in JS via decodeURI() .
PHP:
echo urlencode(dIffdt);
JS:
var diffdt = "37"; alert( decodeURI(diffdt) );
Or try base64 encoding.
PHP:
echo base64_encode(diffdt);
JS:
var diffdt = "37"; alert( btoa(diffdt) );
I am thinking possibly your data is ASCII coming out of the server, but JS uses UTF8 by default (as do most modern browsers in a more general sense).

Putting two MySQL rows into an PHP array

I am developing a narrowcasting system for my school and I am currently using a JavaScript to rotate between URL's for the iFrame on the main display page.
I want to be able to change these values through a backend with PHP. However I can't figure out how to put 2 rows (module_url and module_time) into a array and echo it to JS.
Browsing through stackoverflow I tried a variety of code and this one kinda works, except it will throw out URL's like: "var arrayObjects = ["https:\/\/domain.eu\/dir\/page.php","https:\/\/domain.eu\/dir\/page.php"]".
(I want the array to display: "var arrayObjects = ["https:\/\/domain.eu\/dir\/page.php", 20]". Where the URL stands for the new iFrame source and the 20 for the time the page will be displayed.)
So my main question is, how do I make 2 rows fit into 1 array and how do I make sure the array will display correct links aswell as the module time.
<?php
$mysqli = new mysqli('localhost', 'user', 'pw', 'db');
if ($stmt = $mysqli->prepare("SELECT module_url FROM db")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
ALL OTHER JS CODE
</script>
Edit: module_time is not added to the MySQLi query at the moment.
First your PHP array should be multi-deminsional like:
$result_array[] = array($name, <time here>);
Then since you already use json_encode and assigned it to JS array, it is indeed already an array in Javascript, that is you can already access the elements like:
arrayObjects[0][0]; <---- first element URL
arrayObjects[0][1]; <---- first element time
Printing JavaScript array to HTML will show it as text like:
http://www.google.com,20,http://www.google.com,30
By the way you can use JSON.stringify() to print the actual Javascript array instead of the text, sample:
var array = JSON.stringify(<?php echo $json_array; ?>);
document.write(array);
Will output:
[["http://www.google.com",20],["http://www.google.com",30]]

How can I use a javascript argument to select which string I need in a php array? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
First off, I'm fairly new to JS and PHP. But I have a PHP array that contains the titles of some events. I'm trying to make a Javascript script that creates elements and fills them with the strings in the php array.
Here's kind of what I'm wondering about. Is there a way to do something like this:
function createCard(x) {
var event_title = "<?php echo $event_title[x]; ?>";
}
Or if there's a better way to do this, I'm open to suggestions. Thanks!
EDIT:
I was able to fix my own issue by just converting the php array into a js a array and going from there
var event_title_arr = [<?php echo '"'.implode('","', $event_title ).'"' ?>];
you have to convert the PHP array to string or json and use in js.
ex, array to string,
function createCard(x) {
var event_title = "<?php echo implode(',', $event_title[x]); ?>";
var event_title_arr = event_title.split(',');
console.log(event_title _arr);
// play around using JS variable "event_title_arr "
}
OR
function createCard(x) {
var event_title = "<?php echo json_encode($event_title[x]); ?>";
var event_title_arr = JSON.parse(event_title);
console.log(event_title _arr);
// play around using JS variable "event_title_arr "
}

javascript append colon to variable

I have a javascript function in which am trying to send some data to another php script. I have to send an array of values to the php script. I am trying to append : to each value in the javascript function so that I can use implode to get the array values in my php script. This is the javascript function I have.
$("#update-form").submit(function(e) {
$passdata = "";
<?php
for ($i=1; $i <= $total_columns - 1 ; $i++) {
printf('$passdata+=$("#slider%d").val().:;' . PHP_EOL, $i);
}
?>
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="'+$passdata+'">');
$('form').data('submit', 'true').submit();
e.preventDefault();
return false;
}
})
I used printf('$passdata+=$("#slider%d").val().:;' . PHP_EOL, $i); However, I am not able to see the variable in php script. I also tried,
printf('$passdata+=$("#slider%d").val()+=:;' . PHP_EOL, $i);
How can I append : to the variable in my javascript function?
Look at what it generates in the client, is that valid JavaScript?
$passdata+=$("#slider1").val().:;
JavaScript does not do string concatenation that way.
$passdata+=$("#slider1").val() + ":";
If I were you, I would use an array and join()
$passdata.push($("#slider1").val());
and than make it a string
var myValue = $passdata.join(":");
Even better, do not use PHP to generate the JavaScript! Just add a class on the elements and use a single selector with map();
$(".myCommonClass").map( function(){ return this.value; }).get().join(":");
Or just post multiple form element names to the server and handle the multiple values on the server like forms always work.
Rather than hacking around this abomination, why not just do something like this:
Add a class to all of your sliders. Then:
$(".sliderClassNameHere").map(function(x) {return x.value;}).get().join(":");
Alternatively... just submit the sliders...?
Why not use json? In PHP you use json_encode(), put it in hidden input's value, and then in javascript you use function json_decode() on that value. That's what json is for.

Categories