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.
Related
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).
I've had a look around and can't seem to find a working solution, so here's the requirements.
I'm building a system that takes data from a master page and loads it into a modal style window for quick data processing. I have a javascript function passing 4 status parameters, and whilst 3 of them will always be integers, one of them can be integer or string.
The function works if all 4 parameters are integer, but fails when a string is passed.
function passJob(jobid,equipid,status,location) {
var a = document.getElementById('jobnumber');
var b = document.getElementById('equipid');
var c = document.getElementById('status');
var d = document.getElementById('location');
a.value = jobid;
b.value = equipid;
c.value = status;
d.value = location;
}
PHP
<a href='#' onclick='passJob($sr,$eid,$ss,$sl);'>Modify Job</a>
$sr, $ss and $sl will always be numeric, $eid will either be integer, or a string starting with M and then having a number after it.
I've tried adding quotes to the variables, around the variables, inside the function etc and no luck :(
You need to pass as string if you do not know what they are - also make sure you do not nest the same type of quote:
onclick='passJob($sr,"$eid",$ss,$sl);'
Just wrap it in quotes. This treats it like a string at all times to avoid any potential JavaScript parsing errors.
Modify Job
That is because you do not properly encode the variables in a Javascript notation. Try:
echo "<a href='#' onclick='passJob(".json_encode($sr).",".json_encode($eid).",".json_encode($ss).",".json_encode($sl).");'>Modify Job</a>";
Do like below
Modify Job
I have the following PHP code. It creates multiple variables using $a; for example: $numtoken1.
$sql ="SELECT token, dispositivo FROM dispositivos WHERE idcliente=1";
mysql_select_db('localiza');
$retval = mysql_query( $sql, $conn );
$num_rows = mysql_num_rows($retval);
while($row = mysql_fetch_array($retval, MYSQL_BOTH))
{
$numtoken['$a']=$row['token'];
$numdispositivo['$a']=$row['dispositivo'];
$a=$a++;
}
Using JavaScript, I want to call all the PHP variables using that code, but it only get the last $a number.
My question is: In a JavaScript loop, how can I dynamically insert the value for $a? Because in the above PHP, I have multiple values for $a.
var accessToken = "<?= $numtoken['$a']; ?>"a;
var deviceID = "<?= $numdispositivo['$a']; ?>";
I suggest JSON:
var accesstoken = JSON.parse("<?= json_encode($numtoken); ?>");
var deviceID = JSON.parse("<?= json_encode($numdispositivo); ?>");
So the first thing I noticed when looking at this is that you are wrapping $a in single quotes (') instead of double quotes (") this means that instead of evaluating $a the key in the array will be the string "$a", so you'll be overwriting the value in each iteration of the while loop. See - http://php.net/manual/en/language.types.string.php#language.types.string.parsing for more info.
That being said the actual answer to your question varies, but the simplest method might be to use the json_encode function to convert your arrays into json objects.
var accessTokenArr = <?php print json_encode($numtoken); ?>
var deviceIdArr = <?php print json_encode($numdispositivo); ?>
Then you can iterate over the values in those arrays and do whatever you want to with the values. Fair warning - you may need to tweak that code a little as I haven't tested it to make sure it plays nicely.
I'm trying to pass an array of data from php to java script for "onclick" event.
I do it by converting the array data into JSON string in order to parse it back in the js function and work on it.
The problem is that JSON string contains double quotes , so it arises an error as the double quotes break the html string (Uncaught SyntaxError: Unexpected token ILLEGAL ). I did see several questions similar to this, but didn't find a solution to what I need, or maybe I didn't understood the correct solution. So I bring it up here with my specific case.
<?php
..some php code here..
$aData = array("You","Me",76,array(3,6));
$sJSONstr = json_encode($aData);
?>
<input type="button" name="formSubmit" value="Delete" onclick="analyze('<?php echo $sJSONstr; ?>')">
<?php
..some php code here..
?>
and the js function is as follows:
function analyze(i_sInputDataJSONStr)
{
var aInputData = JSON.parse(i_sInputDataJSONStr);
.. So something with the input data array..
}
Use single quotes for the onclick attributes instead of double quotes. Single quotes is equally valid as double quotes.
One more thing, since you already have your data in JSON format, there is no need to put it as a string in the analyze function call, since your JSON data is a valid JavaScript array (that's what JSON stands for: JavaScript Object Notation).
Therefore, you don't have to parse the input string in your analyze function declaration.
Consider the following example, this is perfectly valid code.
<?php
$arr = ["Hello", "World"];
$json = json_encode($arr); // $json = '["Hello","World"]'
?>
<div id="myDiv" onclick='doSomething(<?php echo $json; ?>)'>Click me</div>
<script type="text/javascript">
function doSomething(data){
for (var i = 0; i < data.length; i++) {
alert(data[i]);
}
}
</script>
create a javascript string and pass it:
<script type="text/javascript">
var myjson = '<?php echo $sJSONstr; ?>';
</script>
and then:
onclick="analyze(myjson)"
<input type="button" name="formSubmit" value="Delete" onclick='analyze(<?php echo $sJSONstr?>)'>
Replace the double quotes with single quotes in onclick='';
Worked like a charm for me.
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>