Store a session variable in html/javascript - javascript

I'm trying to grab a session variable in my javascript, but have some problems getting it right..
I didn't get that to work, so instead i tried to store it in a hidden variable in HTML first, but i dont know how to store a session variable there..
Can anyone guide me to the right path?
The code (HTML file): ($_SESSION["price1"] is equal to "20.00")
<input type="hidden" id="price" value="$_SESSION["price"]"/>
The code in javascript:
var sessionValue = document.getElementById("price").value;
What to do?

you missed PHP tags <?php and echo, change to:
<input type="hidden" id="price" value="<?php echo $_SESSION["price"]; ?>"/>

What everyone bellow mentioned is perfectly true, inside HTML you can just wrap stuff in <?php echo $_SESSION['price']; ?> and it will work (notice the <?php tags)
However, the right way to do this -- considering you want to pass a PHP variable (in your case a session variable) to javascript is to directly insert it into a javascript variable instead of accessing the DOM. This way, you also have it instantly and don't have to wait for the DOM to be loaded
<script>
var price = '<?php echo $_SESSION["price"]; ?>';
alert('The price is: ' + price);
</script>

This line:
<input type="hidden" id="price" value="$_SESSION["price"]"/>
Should be:
<input type="hidden" id="price" value="<?php echo $_SESSION["price"];?>"/>
You are missing the php tags

change,
<input type="hidden" id="price" value="$_SESSION["price"]"/>
To,
<input type="hidden" id="price" value='<?php echo $_SESSION["price"]; ?>'/>

Grab your session variable in JavaScript using this:
var my_session_price = "<?php echo $_SESSION["price"]; ?>";

Related

Indirect Population of Textarea in HTML Form Using PHP

I am working on an "Update User Data" form, which should reflect the initially entered information stored in the database into the textarea, and can be changed if the user wishes to. While I'm doing so, I have a concern - is directly writing value = <?php //some code ?> the safest bet?
I was trying to invoke a function to place my PHP code in that instead, but apparently it's just displaying the function's name.
Here's my code snippet:
<div>Date of Birth: </div>
<input id="dob" type="date" onFocus="emptyElement('status')" value="reflect_data('dob');">
where the function reflect_data is defined as -
function reflect_data(elem) {
//query and some code to access the data and store into $member
if (elem == "dob") {
echo $member['DOB'];
exit();
}
NOTE : A newbie to PHP, any advice would be welcome. Thanks. :)
You use php code in a JS function. That won't work that way and is impractical. Simple:
<input id="dob" type="date" onFocus="emptyElement('status')" value="<?php echo htmlspecialchars($member['DOB']); ?>">
is the best solution.

detecting input in dynamically generated input

My code dynamically generates a series of input fields. Each row of fields belongs to one database record and I use php's dynamic array notation ('[]') to capture the values.
Then at the input field i want to show the price input value that have been multiplied by total number of item that the data is generated from database.
I used javascript that placed inside foreach looping to detect the input and multiply it, but it only works for the first field, at the second field the multiplied value shown on the first field too.
this is the code structure :
<?php foreach ($barang->result_array() as $row): ?>
<tr>
<td><?php echo $row['nmbr']; ?> </td>
<td><?php echo $row['jumlah']?> </td>
<td><input id="pnwrn" type="text" name="pnwrn[]" value="" />
<input type="hidden" name="id_barang[]" value="<?php echo $row['id_barang']?>" />
<input type="hidden" name="jumlah[]" value="<?php echo $row['jumlah']?>" /> </td>
<td><div id="output"><script type="text/javascript">
var harga = <?php echo $row['jumlah']; ?>;
$('input').bind('input propertychange', function () {
$('#output').html($(this).val()*harga);
});
</script>
</div></td>
</tr>
<?php endforeach; ?>
I tried to make the output show the multiply value in each row but have no result yet..can someone tell me where i make my mistake?
thanks ~
There are several issues that others have pointed out in the comments.
The reason why every value on the page is changing is because you are using an id for the output div instead of a class and your jQuery change handler is saying: "get everything with an id of output and put this new html in it." Aside from that, it's not valid to use an id more than once on a page. So, change both the output and pnwrn to classes.
To make it simple to get the corresponding 'harga' value later, you can just store it as data on the input.
<?php foreach ($barang->result_array() as $row): ?>
<tr>
<td><?php echo $row['nmbr']; ?> </td>
<td><?php echo $row['jumlah']?> </td>
<td><input class="pnwrn" type="text" name="pnwrn[]" value="" data-harga="<?php echo $row['jumlah']?>" />
<input type="hidden" name="id_barang[]" value="<?php echo $row['id_barang']?>" />
<input type="hidden" name="jumlah[]" value="<?php echo $row['jumlah']?>" /> </td>
<td><div class="output"></div></td>
</tr>
<?php endforeach; ?>
The second issue is that you are writing a separate handler in every single table row. This is not only inefficient, it's hard to read the output and completely unnecessary. You just want your script once on the page so don't include it in your loop. To get to the corresponding values for your calculation, you can just retrieve the data value stored on the input. Then, you can use DOM traversal to find the corresponding output div. In this case, go up to the nearest ancestor row, then find its descendent element with the output class. Also, unless you are using a really old version of jQuery, use the on method instead of the deprecated bind.
<script type="text/javascript">
$('input').on('change', function () {
var harga = parseInt($(this).data('harga'));
$('this').parents('tr').find('.output').html($(this).val()*harga);
});
</script>

Setting Date Picker With JavaScript And PHP

I'm trying to set a date picker with JS like any other <input> value.
This HTML line works, but I need to set the value with Java.
<input Id="BirthDate" name="BirthDate" type="date" required value="<?php echo $BirthDate ?>" >
However when I try to use the .value attribute the date picker stays blank.
<input Id="BirthDate" name="BirthDate" type="date" required >
Currently I am using this script to set the picker, This function runs as soon as the page loads the body.
function StartUp() {
document.getElementById("BirthDate").value = "<?php echo $BirthDate ?>";
}
</script>
What am I doing wrong?
And what else could I try to use?
I have it working no, something was being difficult with the syntax of the php.
changing:
document.getElementById("BirthDate").value = "<?php echo $BirthDate ?>";
To:
document.getElementById("BirthDate").value = "<?php echo($BirthDate); ?>";
Adding () parentheses around my variable and a ; semicolon after the command fixed my issue.

Keep value in input box when the page is refreshed

I want to keep the value from a input box even when the page is refreshed.
I know that i could do that using just an echo, but i'm connecting two different files.
I have one page with the form:
<form method="POST" action="mypage.php">
<input type="hidden" name="value" value="test">
<input type"submit">
</form>
And another one(mypage.php) that reads the form
<input type="text" name="value" value='<?php echo $_POST['value']; ?>' />
The code is working, bue lets imagine that someone refreshed the page and the value desappears.
I want to know how can I keep the value inside the textbox even when someone refreshes the page.
Thanks.
Create a session to preserve the value:
<?php
session_start();
if((isset($_SESSION["preserve"]))&&($_SESSION["preserve"] != "")){
$_SESSION["preserve"] = $_POST['value'];
}else{
$_SESSION["preserve"] = "";
}
?>
<input type="text" name="value" value='<?php echo $_SESSION["preserve"]; ?>' />
<?php
//when you don't need this session anymore do this:
//(that can also be called in another page of your project)
unset($_SESSION["preserve"]);
?>
Hope that's what you were looking for...

Hidden values in php echo

I have this query in php code:
$sql="SELECT vName,id FROM employee WHERE vName LIKE '%$my_data%' ORDER BY vName";
I have echoed the vName.
echo $row['vName']."\n";
The above values appear in a autocomplete textbox.
In the same aboce echo statement I want to pass 'id' as hiden value. is it possible? I wan to retrieve it in another page.How do I do this?
$sql="SELECT vName,id FROM employee WHERE vName LIKE '%$my_data%' ORDER BY vName";
$hid='<input type="hidden" name="xyz" id="abc" value="'.$row['id'].'" />';
echo($hid);
echo $row['vName']."\n";
I hope you get the idea.
Echo it out to a hidden input field,
<input type="hidden" name="hidden_id" id="my_hidden_id" value="<?php echo $row['id'];?>"/>
This way you can pass it with a form if you are submitting one or simply add an id to it and get the value to pass to the next page.
I would first make a variable of $row['id'] and when you're still in your form but outside the textbox do this:
<?php echo "<input type='hidden' name='id' value='".$yourvariable."'/>";?>
If it must be completely hidden i recommend using php-sessions.
I guess you want to do that if you want to retrieve the id in other page , you better do this :
<?php echo $row['vname'] ?>

Categories