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.
Related
Is it possible in PHP to find and replace a PHP variable with a user defined value from a drop down box on a different PHP page.
Example:
PHP Page 1
$test = '1234';
PHP Page 2
Drop Down Values: (Find and replace $test variable with Drop Down selection)
1
2
3
4
Im have not found much information about this.
The purpose is to pass hexadecimal colours based on user choice.
PHP Variables are server-side variables. You can not change server side variables from client side directly.
Common approaches are: (Although both do same in background)
Using GET to send your data
Using AJAX to dynamically send, fetch and change DOM (Maybe preferred in our case)
On selecting the item on the Drop Down menu, you need to call a method which sends a data to your PHP page and you can change variables.
Your PHP page should handle a GET request change the variable to $test
$test = $_GET["sent_variable"]
While on AJAX, you need to something like:
$.ajax({
url: "your-php-page.php",
type: "POST",
data: { sent_variable: selectedVar}
}).done(function() {
//Something here after doing
});
Read more about AJAX here.
Note: You have to trigger AJAX on selecting drop-down menu. Read about that here.
Assuming the dropdown box is part of a form, you can use the 'post' method.
e.g.
<!--HTML-->
<form method="post" action="myScript.PHP">
<select name="myOption">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" value="GO">
</form>
//myScript.php file
<?PHP
$test = $_POST['myOption'];
echo $test;
?>
I actually have a page on my own site that uses similar functionality for passing hex colours if you want to have a look at the HTML source code http://www.wxls.co.uk/formatmyvba.html
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
?>
I want to send the properties of HTML elements as data via POST, for example whether an element is visible or not?
You cannot do it with PHP and HTML alone, since the HTML form would only post a form input's name. You would need to add some JavaScript, which at the time the form is submitted, would iterate over all its inputs and modify their values to include the attribute values as well.
Example:
yourform.onbeforesubmit = function() {
// Loop over form elements and append -visible or -hidden to its value based on CSS style
// jQuery selectors like .is(":visisble") would help a lot here.
// This is just a basic example though - it would require an explicit visibility CSS rule on each
// input element...
for (var i=0; i<yourform.elements.length; i++) {
yourform.elements[i].value = += "-" + yourform.elements[i].style.visibility;
}
}
Another method would be rather than to modify the values of the inputs themselves, keep a hidden input for each visible user input and set the attributes as the value to the hidden input rather than the visible input.
You can not do this with PHP. You will need to use Javascript to determine this information and then either send an Ajax Request or add this information to an existing form.
To elaborate a bit more: PHP is executed Server Side and then sent to the Client (Browser). The Server is not aware of the state of the HTML Elements in the Browser.
As far as i can tell you have a form that is submitted anyway? So add a piece of javascript which is called before the form is submitted (onsubmit property of the form) and have it read out the status of the elements (visible, hidden, ...) and set this information to some hidden form fields.
Make sure the javascript that is called before the form is submitted is returning true, otherwise the action gets cancelled.
In ajax.
Try Prototype Framework, it is really easy to use!
http://prototypejs.org/api/ajax/request
If you want to do that I suppose you will have to create some hidden fields and javascript that would fill them in with information depending on your elements attributes. As far as I know there is no other way.
You have to define your data definition standard first: what do you want to store, and under what name.
then, imho you have to serialize the result and send it through POST, for finally unserializing it once at the server.
Use JSON serialization for an effective way of proceeding.
Include Hidden inputs using PHP like the following:
<input type="hidden" id="hidden1" name="hidden1" value="<?php if(condition) echo "default"; else echo "default";?>">
This default value can be set by PHP during page load, for transferring extra hidden data from one page load to another. But can also be modified by javascript after page load:
<script type="text/javascript">
document.getElementById("hidden1").value="true";
</script>
Note: PHP can change the value of any hidden or non-hidden element only during the next page load. It doesn't have any control over the HTML it sends to the browser. This is why you need Javascript(Client side scripting).
I have created a news area where i have display 3 thumbs of news at a time the source is from mysql database.
i have used the query like this:
$eu = 0;
$limit = 3;
$query2=mysql_query("SELECT * FROM news ORDER BY ID DESC LIMIT $eu,$limit");
now i have also create two buttons with like this
i want to use this buttons for display the next 3 thumbs onclick and prev 3 thumbs. but not able to change the value inside the query i.e $eu.
how can i change the $eu value inside the mysql query with javascript or any other suggestion and also i dont want to do this with reload of page with passing query parameters. i want it without reloading of page
You'll need to do an ajax call, pass in the value for $eu (eg, 3, 6, 9 etc) that you need, and pass back the contents of the news feed, to replace the existing lot.
There are many ways you can do this and which is easiest depends on the frameworks you are using. Google is your friend here, there are plenty of tutorials etc.
You can't change a php variable from Javascript simply because the server side script is already run, and javascript is a client side script.
What I suggest would be, use javascript to send an ajax request to a PHP scriptthat accepts $eu as a parameter.
In that PHP, do the query with the $eu, and print out the search results.
In your javascript, catch this result upon success ajax request and process/replace certain elements in your HTML with the result.
You cannot change the value of any PHP script directly from Javascript because PHP is parsed prior to the page being sent to the browser (i.e. server-side) and Javascript is parsed and execute by the browser (i.e. client-side).
There are 2 main ways this sort of thing is accomplished. If you really want to affect the PHP variable value then you'll have to reload the page (for example using an HTML form). Since you said you don't want to do that, then as others have suggested, you'll want to look at AJAX.
In a nutshell you'll use Javascript to send a request to a PHP page which will run the query you have above (and you can pass along a new value to plug into $eu in the form of POST or GET data) and return the results which you will then use to update the display on your page.
Try this
//PHP
$count=3;
$query= 'select * from news order by id desc ' ;
$limit_str=" limit 0,$count";
if(isset($_POST['page']))
{
$lim=$_POST['page'];
$offset=$lim[0]*$count;
$lim_str=" limit $offset, $count";
$query.=$lim_str;
}
//Form
<form method='post' >
< input type='submit' name='page[]' value='1' />
< input type='submit' name='page[]' value='2' />
< input type='submit' name='page[]' value='3' />
</form>
<?php
// Display logic
?>
I have an HTML form which contains a drop down, a tinyMCE textarea, and a save button.
The dropdown is used to select a file to edit.
I load up the required file into the tinyMCE editor by making an ajax call when the jquery change() event is triggered from the dropdown. That works fine.
The problem I'm having is saving the file off. I am trying to do it by posting the form off to another php page which will write to the file and then send us back to the main page.
This is the php code within my writeFile.php page:
<?php
session_start();
if (!isset($_SESSION['id'])) {
header ('Location: index.php?error=0');
}
else {
if (isset($_POST['save'])) {
$text = $_POST['mceContent'];
$index = $_POST['files']; // << PROBLEM LINE!
$array = array('homeText.txt', 'anotherText.txt');
$fileName = $array[$index];
$path = '../txt/'.$fileName;
$length = strlen($text);
echo "INDEX: $index"; // TO TEST THE INDEX VARIABLE.
$fh = fopen($text,'w',true);
fwrite($fh,$text,$length) or die('Could not write');
fclose($fh);
header ('Location: admin.php');
}
}
?>
The $index variable is meant to be the selected index in the dropdown, however it is posted by my form as the selected string value in the dropdown.
I can think of three solutions (ordered from least likely to work to most likely)
There is some way to get the index from that php post?
I can make a change in the HTML form/select tag to tell it to post the index and not the value string
I change it to a jquery event, with the on-click, and pass in the index to a post manually with xhr.
If someone could help me with implementing one of these method that would be great.
If you have your own, better solution I would be happy to hear that as well.
Also note that I can't build the path from the value string, because my dropdown uses descriptive strings, not actual file names.
Thanks in advance, bear in mind I'm new to php and especially jquery.
I am not sure why you can't use the value attribute - the descriptive string would be the text portion of the option element, the filename to save could be the value:
<option value="path/to/file_to_save.php">Descriptive file name</option>
Doing it that way, the user sees the descriptive text, the server gets a useful bit of information it needs when the form posts.
If that is not an option, you could add an onSubmit event to the form in which you pass the selectedIndex property to a hidden form field, then return true and let the form submit normally.
Form snippet
<form onsubmit="return beforeSubmit()">
<input type="hidden" name="file_index" value="" id="file_index_fld" />
<select id="file_name_dropdown">
<option>...</option>
Javascript snippet
var beforeSubmit = function () {
$('#file_index_fld').val($('#file_name_dropdown').attr("selectedIndex"));
return true;
}
... now in PHP's $_POST variable, you'll see $_POST['file_index'] contains the selectedIndex of the select element.
The long and short of it is that the selectedIndex property is a DOM item and not part of the POST data. No matter what, you are either going to have to intervene with javascript to add the data to POST, or modify your option elements to pass the desired data. I would always lean toward the former route as it is less complex.
Another option I can think of: Before posting, catch the new index in the change-event and write it to a hidden input-field of your form. After that, you can serialize and post it with jQuery.