How to print $_GET[] value - javascript

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.)

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 to pass numeric values from PhP to Javascript without posting data?

I need some data from SQL to Javascript, so I called them in PhP and I'm trying to pass these values to Javascript, but the code below causes a NaN failure... if I set a PhP command for the Javascript variable, I can't use it as a numeric value...
<?php
$val=12;
?>
<script>
var val="<?php echo $val; ?>";
</script>
I got a solution but I'm sure, this is not the best way to do this:
<?php
$val=12;
?>
<input type="number" id="val" name="val" value="<?php echo $val; ?>" hidden>
<script>
var val=getElementById('val').value;
</script>
One way of doing it is removing the quotes:
<script>
var val = <?php echo $val; ?>;
</script>
But there may be edge cases in which php yields unexpected results, so in my opinion it's a good practice to keep the quotes and to update the value.
If you are sure that the value will always be an integer and/or that you need an integer in your code you can do:
var numericValue = parseInt(val, 10);
Or if you are using lodash:
var numericValue = _.parseInt(val);
Remember to pass 10 as the second parameter which will specify the radix in the first case, as there may be edge cases in which numbers are interpreted with a base different than 10 (like hexadecimal or binary).
Otherwise if the value can be a float I suggest to do:
var numericValue = parseFloat(val);
And if you want to limit the digits after the decimal point you can do:
var numericValue = Number(parseFloat(val).toFixed(4));
.toFixed() returns a string so if you still need a number it's better to convert it back to a number with the Number() function.
Passing the value through an input may work but it doesn't look like a good practice, anyway to get the element you will need to add document before getElementById:
var val = document.getElementById('val').value;
Thank you all! It's easier, then I thought! I thought, quotes are always needed, as JavaScript identify "<?php" tag as string.

Inserting a multiline PHP string into a Javascript variable

My question
My question is about correctly parsing HTML from php into a variable inside of a javascript object (which in this case is ace-editor's value variable)
My problem
I have got a textarea for HTML and CSS, the HTML gets retrieved from the database and needs to be inserted into a field of croppie, i am currently using PHP's json_encode functionality to put it inside of the variable, but it seems to still escape from the value.
My code
<?php
$css = ($modify) ? trim($template->style()) : "";
$html = ($modify) ? trim( $template->html() ) : "";
$html = json_encode($html);
$css = json_encode($css);
?>
YUI().use(
'aui-ace-editor',
function(Y) {
var editorhtml = new Y.AceEditor({
boundingBox: '#editor-html',
height: '400',
mode: 'html',
value: '<?php echo substr( $html, 1, -1 ); ?>',
width: '100%',
showPrintMargin: false
}).render();
var editorcss = new Y.AceEditor({
boundingBox: '#editor-css',
height: '400',
mode: 'css',
value: '<?php echo substr( $css, 1, -1 ); ?>',
width: '100%',
showPrintMargin: false
}).render();
}
);
What happens
When i use this, and open up a specific template which can be managed, i will not be able to see the textarea's (because the ace editor could not be loaded), i get random errors relating to line 666 which is the exact line the HTML gets stored in. I did sanitize the outputs in json_encode correctly.. right?
in this screenshot, you can see the HTML/css which gets inserted. But the problem occurs on line 666 which the HTML is located at. Click here if the screenshot isn't readable for you
So my question is..
Why exactly does it not parse the HTML into the object correctly? Am i not sanitizing it correctly or am i missing something?
You are breaking the output of json_encode by changing double quotes it creates to single quotes.
It's better to call json_encode directly when adding value to the script tag:
value: <?php echo json_encode($html); ?>,
Your issue is because your $html string contains single quotes, try escaping them or using double quotes

Correct method on passing PHP variables that contains date and time to javascript

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.

how to use jquery selectors in a for loop?

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>

Categories