working with php in javascript Working in an blade.php
<?php
$date = date("Y-m-d");
$time = date("H:i:s");
?>
<script>
function myFunction() {
var time = <?php echo json_encode($time) ?>;
var timefrom = <?php echo json_encode($post->timefrom) ?>;
var timeto = <?php echo json_encode($post->timeto) ?>;
var date_dif = timeto - date;
alert(date_dif);
</script>
Alert gives me back "NaN".
Source in the browser looks like that:
function myFunction() {
var time = "21:14:53";
var timefrom = "21:21:00";
var timeto = "23:00:00";
var date_dif = timeto - time;
alert(date_dif);
So data is getting passed but not saved?
Has anyone any idea how I can work with the data I pass from PHP to javascript?
You seem to be mixing back end code with front end.
Front end is static, just sitting there. You need to use ajax to communicate with your back end.
There are many free tutorials on ajax all over.
This
var time = "21:14:53";
var timefrom = "21:21:00";
var timeto = "23:00:00";
needs to be in fields so you cam work with it.
You're trying to subtract a string from a string, that's not going to work... for obvious reasons. Thus the NaN output in your alert.
Population of the data from PHP into your script tag is behaving properly.. you're just not working with that data in a way that makes any kind of sense afterward :)
Why would you even need to do this when you can calculate the difference in php
haha thanks u guys. Yes I though about calculating in php and then pass it to js. But was wondering how to do it like that.
Also later I want to compare the calucalted data in js to run functions based on it.
If you want to do more in JavaScript then you are going to need to invest in some training.
Can I suggest courses by Wes Bos?
moment.js is a good library for working with dates in JavaScript
My point was, if working with the data to save, you have to either post with a form or ajax.
Like here an edit in being done. if I change the amount from 40.00 to 50.00, yes it's changed on screen (front end),
But nothing is updated until I post the change with ajax in this case.
Front end is static data only sitting on screen in the browser.
Agreed, take some free or paid good JS training. There are some good tutorials out there that make learning fun and fairly easy.
thank u very much. Jear, need alot of training 😊 Just started this semester with everything.
Please sign in or create an account to participate in this conversation.