This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
i have a couple of variables that i want to save or not save to a database depending on whether or not i have set them as hidden/visible in a javascript function, i have searched for a while but cant find anything. Thanks!
That's absolutely impossible since PHP runs on the server while JavaScript and CSS are client-side.
The only thing you can do is checking if the element is visible using JavaScript and sending that data to your PHP script, e.g. via a hidden <input> field.
You can also have this alternative. NOTE that the page has to refresh before this take effect (i.e. before PHP has knowledge of what was going on)
//Your JavaScript
function setHidden()
{
document.getElementById('elementForVar1').visibility = 'hidden';
//use this to indicate field/variable is hidden. PHP will use this later
document.getElementById('elementForVar1HiddenField').value = 1;
}
declare hidden fields in your form to store the states of the variables
<form name="xxx">
<input type="hidden" id="elementForVar1HiddenField" name="elementForVar1HiddenField" value="0" />
</form>
Your javascript simply set the value of the hidden field to 1 indicating var1 is hidden
<?php
if($_POST['elementForVar1HiddenField'] == 1)
//variable was hidden
?>
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I was trying to unset a php session variable inside a jQuery if block. Whenever someone unchecks a checkbox it should unset a specific session variable. Here is my code below
PHP
session_start();
$_SESSION['myName'] = "John";
HTML
<form action="" method="post">
<input type="checkbox" id="myCheckbox"> Check to set session
</form>
jQuery :
$('form').change(function(){
if($('#myCheckbox').is(':checked')){
// Some statements here
}else{
<?php unset($_SESSION['myName']); ?>
}
});
But the code is not working here. It is not unsetting the php session variable. Please provide me a solution. Thanks.
Note : I can do it by using AJAX by loading the php code from another page. But I want it to be done by using jQuery only.
Or is there any solution in jQuery that I can unset session variable without using PHP code?
It will not work this way.
All PHP codes are executed before Javascript function .
To achieve this :
You have to do AJAX or form submission.
You just cant do it by only jQuery.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 2 years ago.
So I have a page where I'm requesting users to enter a key via an <input> tag. I would like to store this information in $_SESSION['sessionKey'] when the user clicks a button. Since I'm trying to keep the key moderately secure, I want to avoid passing this information via GET or POST.
Most of what I've found online shows this done by using GET/POST and I'm having difficulty finding information on a method that would not use this approach. I did find this question, which suggests to put JavaScript in a file that has an extension of .php, and from there, use the PHP tags to obtain the $_SESSION variables. I followed this approach like so...
javascript.php
<?php
require ("common/startandvalidate.php");
?>
$(document).ready(function() {
$("#submitButton").click(function(){
<?php $_SESSION['sessionKey']?> = $("#sessionKeyInput").value;
});
});
mainPage.php
<head>
<script src="javascript.php"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<input id="sessionKeyInput" placeholder="Session Key" />
<input id="submitButton" value="Submit" type="button" />
When I look at the page through Inspector (in Chrome) I see the error message:
Undefined index: sessionKey
the require("common/startandvalidate.php"); contains session_start(), so the session is being initiated...
I think it's not working because $_SESSION['sessionKey'] has never been declared before, so even though I want to assign a value to it, it's trying to see the variable contents, which is undefined. How could I go about assigning this value to the $_SESSION variable?
Sorry if this is a simple question, any resources are appreciated!
$_SESSION is a PHP array, you cannot set it on the client side via Javascript. The value has to be sent to the server to be stored in the array.
The question you pointed to shows how you can retrieve the data from $_SESSION, but it won't work for storing data.
The error you see in the console "Undefined index: sessionKey" simply means that the Javascript array named $_SESSION has no key named "sessionKey".
Javascript runs on the client and doesn't have access to the server, and therefore the session. If you want to put a user-entered value in the session, you need to pass it to the server. The most secure way to do that is an SSL-protected HTTP POST.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to get the selected option value of a drop down box in PHP code
Drop Down :
<SELECT NAME='action' class="action" id="action" onchange="a();">
<OPTION VALUE="IN"> IN </OPTION>
<OPTION VALUE="OUT"> OUT </OPTION>
</SELECT>
Script to get drop-down text:
<script type="text/javascript">
function a(){
var e = document.getElementById("action");
var strUser = e.options[e.selectedIndex].text;
document.write(strUser);
}
</script>
//got the script from Get selected value in dropdown list using JavaScript?
Here i need to print the value strUser in php. or else on changing the drop down values should print in same page not in new page.
PHP is server-side script run before javascript (client side) code. you can try
Ajax for sending this value to server and generate your desire output.
see detail Ajax
If you want to pass the data selected in the Dropbox to a PHP script, you must use forms or a submit() call from JavaScript over a dynamically generated form.
But if you don't want the page to be reloaded, then you must rely to AJAX technique.
Take a look here and here. There are tons of examples in the net.
< html>
< head>
< script>
//document.getElementById('yourSelectBoxId').options[document.getElementById('yourSelectBoxId').selectedIndex].value//or
function onchg(){
alert(document.getElementById('yourSelectBoxId').value);
}
< /script>
< /head>
< select id="yourSelectBoxId" onchange="onchg();">
< option value=1> a< /option>
< option value=2> b< /option>
< option value=3> c< /option>
< /select>
< body>
< /body>
< /html>
use innerHTML instead of document.write
If you want to pass it to the PHP script (and later save it as a global or in a database) you could use cookies, or submit it as part of a form (what I'd suggest).
So you have
<form action="form_receiver.php" method="get">
Which basically means, submit all the (named) fields in this form to the form_receiver page. The "get" could be replaced by "post" and they are just two methods for sending data ("get" data is encoded in the URL so it can be saved, useful for simple things, and "post" is "sent hidden by the browser" so is better for things like large ammounts of data or confidential stuff).
Now for the data in each field to be sent, you need to give it a name, as you have provided. So for that input field, you would only need to enclose it in a form.
On form_reciever.php, you would be able to access the variables by name using $_GET['name'] or $_POST['name'] depending on which method you used. You could then save it somewhere else to use later.
Cookies should be for preserving data about the user (such as a session id), and I would not recommend using them to pass data between pages. However, if for some reason you require this, you could set cookie data with javascript and get it using $_COOKIE['cookie_name'] in php. If you're setting a cookie in php use setcookie("name", "value") (more details here http://php.net/manual/en/function.setcookie.php).
There are many ways to set cookies in javascript. I would recommend using a library like jQuery and you could set and get cookies in a similar way: $.cookie("name", "new_value") or $.cookie("name") to get the value.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I'm kinda new to working with JS and PHP and stumbled upon a little problem. Im trying to pass the ID of a textbox I clicked through to PHP and then query a database with that ID. I tried the following code to check if the variable gets passed on, but nothing is alerted:
<script type="text/javascript">
function Like(ID)
{
<?php
$id = ID;
print "alert('$id');";
?>
}
</script>
<input type="text" id="1" onclick="Like(this.id)" >
What I'm trying to accomplish:
I've got a database of videos with a unique ID. I have 2 buttons next to each video for either liking or disliking. The 2 buttons will have an id based on the ID of the video. For example video number 2 has 2 buttons: like(id=L2) and dislike(id=D2). When the user clicks either one of those buttons, I want to update the videos table's "likes" column without the page reloading. Would that be possible?
You aren't going to be able to do this the way you have written it. PHP runs once on page load. So, when you click the input, your function will already be evaluated by php as this:
<script type="text/javascript">
function Like(ID)
{
alert('ID');
}
</script>
The ID is a bareword to php, so it treats it like a constant if defined, or a string (and may generate a warning). Assuming you don't have a contant ID, then it prints the alert line with the string "ID" in the $id variable.
By the time your javascript is called, all you will ever get is alert('ID').
To query a database, you have to pass the data back to the server. This will either load a new page, or if you want it to happen without a page load, you need to make the call to the server asynchronously (in the background), and modify the page based on the result. This is called AJAX. You will need to understand how server-code (php) and client-code (php) work, and then you will better be able to understand how AJAX brings those together to do what you want.
Since you asked this in a comment:
Well, I've got a database of videos with a unique ID. I have 2 buttons next to each video for either liking or disliking. The 2 buttons will have an id based on the ID of the video. For example video number 2 has 2 buttons: like(id=L2) and dislike(id=D2). When the user clicks either one of those buttons, I want to update the videos table's "likes" column without the page reloading. Would that be possible?
I'll tell you a way to achieve it, and it doesn't even require Javascript! :) (at least at first).
It's an old fashioned HTML form element. Since you'll be posting data you should use action post. The code can look like this:
<form method="post" action="/requests/like-video/" class="like-video">
<div>
<input type="hidden" name="video_id" value="<?php echo $video->id ?>">
<input type="submit" value="Like">
</div>
</form>
<form method="post" action="/requests/dislike-video/" class="dislike-video">
<div>
<input type="hidden" name="video_id" value="<?php echo $video->id ?>">
<input type="submit" value="Dislike">
</div>
</form>
Once you have that in place (and working) it's just a matter of hijaxing those forms. A super easy way of doing that is to use jQuery's Form plugin and simply run:
$('form.like-video').ajaxForm(OPTIONS_GO_HERE);
$('form.dislike-video').ajaxForm(OPTIONS_GO_HERE);
Doing it this way ensures users without JS also get a fully functional site.
It's called progressive enhancement.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do I use PHP variables as values for the <script> tag when rendering jQuery code in my CakePHP view?
In CakePHP, the value passed as a parameter in the url can be obtained by the controller attribute
<?php $userid= $this->params['pass'][0];?>
I want to use $userid inside the jQuery code.
$("#displayPanel #saveForm").live("click", function(){
document.location = 'http://localhost/cake_1_2/forms/homepage';
});//Click on SaveForm
Suppose if the userid is 12, I need the document.location to be 'http://localhost/cake_1_2/forms/homepage/12'.
How to use the php variable in jQuery?
For readability, how about:
<?php $userid= $this->params['pass'][0];?>
var userId = '<?=$userid?>';
$("#displayPanel #saveForm").live("click", function(){
document.location = 'http://localhost/cake_1_2/forms/homepage/' + userId;
});
You'll need to output the variable into the JavaScript source:
$("#displayPanel #saveForm").live("click", function(){
document.location = 'http://localhost/cake_1_2/forms/homepage/<?=$userid?>';
});//Click on SaveForm
Note the <?=$userid?>. If shorthand is turned off on your server, use <?php echo $userid; ?>.
Apart from the approaches suggested above, you could also:
Use the built in CakePHP Javascript helper to tie the PHP and JS parts better together (better code separation and no code language mix-up). Have a look here: http://book.cakephp.org/view/207/Javascript
Create a hidden input field in the HTML with you passed value that the jQuery can read from. Might seem somewhat over-complex, but can be handy in cases where the jQuery should be able to modify the values also or be used in submit forms etc.
Make the CakePHP controllers responsible for reading and using the user id instead of the JS. Depends on your specific use case, but instead of passing the parameter to the new page, simply fetch the value as the first thing from the controller that you call (impossible if the user id isn't always the same or can't be predicted passively).