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>
Related
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.
I'm a bit confuse on passing PHP variables that contains date on an onclick attribute of a button, for example.. (for some reason, I put the button inside an echo)
<?php
$date = date("F-d-Y", "2015-07-24"); //to convert the string 2015-07-24 to date with an specific format
echo "<button onclick = 'goToThisJSMethod(".$date.")'> Pass </button>";
?>
on the javascript part wherein goToThisJSMethod written.
function goToThisJSMethod(dateRec){
alert (dateRec);
}
The syntax above results nothing and the alert box didn't appear
I tried changing the above code, I alter the parameter that will be passed on PHP, instead of using $date variable, I used the exact string of the date to be the parameter and change the javascript like this:
function goToThisJSMethod(dateRec){
var date = new Date(dateRec);
alert(date.getMonth()+1 " " + date.getDate() + " " + date.getFullYear());
}
Yes there's a result with this but then again, it returns a default date of 1/1/1970. What should I do regarding with this problem?
The biggest problem is the second argument to date() has to be a timestamp, so you need to use strtotime. You'll always get "January-01-1970" because you're passing it a string where it needs a timestamp.
You probably also need quotes around your string, as below. Check the rendered HTML in the browser to see.
<?php
$date = date("F-d-Y", strtotime("2015-07-24"));
echo "<button onclick=\"goToThisJSMethod('{$date}')\"> Pass </button>";
?>
I converted your html to use " and PHP to use variable interpolation.
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.
I want to pass $_GET value to window.open, but how?
My current code can't pass $_GET value:
function googlemap() {
ver id = <? php print ''.$_GET['buid'].''; ?>
window.open("Views/Admin/addresstomap.php?bid=+id", "myWindow",
"status = 0, height = 600, width = 800, resizable = 0 top=200, left=300,scrollbars=no,toolbar=no, location=no, directories=no, ")
}
You're not using the variable in the window.open call, you're just using a string with the name of the variable:
"Views/Admin/addresstomap.php?bid=+id"
JavaScript won't interpret id from that string. You need to separate it from the string itself:
"Views/Admin/addresstomap.php?bid=" + id
Additionally, you have a typo in the var keyword and you're missing a semi-colon. This:
ver id=<?php print''.$_GET['buid'].''; ?>
should be this:
var id=<?php print''.$_GET['buid'].''; ?>;
Indeed, you may even need quotes around it if the variable is supposed to be a string. (I don't know if it is, but you should be able to figure it out.) In that case the line would be:
var id="<?php print''.$_GET['buid'].''; ?>";
(Note: Given these errors, there may still be others that I haven't noticed. You'll want to do some debugging, check your PHP logs, check your JavaScript console, etc.)
i want to acheive this :
for (i = <?php echo $current_i ?> /*then I get augmented in javascript */;i<max;i++){
$('#anyid****')./* my actions goes here */
}
here i want to put the counter I of the javascript in the selector
how could i do that ???
Sorry i don't know PHP but i hope you wanted to do something like below
for (i = <?php echo $current_i ?> ;i<max;i++){
$('#div'+i)/*do the rest*/
}
the + is for concatenation, i hope it is same in PHP. Also you could cast i to string.
Just for OP's understanding
in line 2 $('#div'+i) i is a integer type and others $(#div) are of type string. For jquery needs a string selector to retrieve a matching dom node and for that i needs to also be casted/converted to a string variable so that it could concatenate/add/attach with the prefix string which is in this example #div. in c# you add 2 strings like this var result = "#div" + i.ToString(); and i did not know PHP equivalent for + in c#,hence a sorry at the start of post. Now do you understand?
for (i = <?php echo $current_i ?> /*then I get augmented in javascript */;i<max;i++){
$('#anyid' + i)./* my actions goes here */
}
you can just concatenate it to the string of your selector.
That's not very "jQuery-ish". Assuming the elements have IDs with a continuing part and are in order, you can give every element a common class and use slice [docs] and each [docs]:
$('.commonClass').slice(<?php echo $current_i ?>, max + 1).each(...
You could provide better solutions if you explain more about your problem. E.g. giving each element an increasing ID does not seem to be a deliberate solution.
P.S.: I wouldn't put the PHP variable there either, maybe assign the value to a JavaScript variable first.
it would be a lot cleaner if you split up the php and javascript like this.
js_var.php
<?php
$phpvars = array(
'max' => 12,
'fop' => 22
);
function phpvar($key = NULL){
global $phpvars;
return ($key)
? json_encode($phpvars[$key])
: json_encode($phpvars);
}
?>
usage
<?php include('phpvars.php');?>
<script type="text/javascript">
window.phpvars = <?=phpvar()?>;
var max = phpvars.max;
for (var i=0;i<max;i++){
console.log(i);
}
console.log(php);
</script>