How to pass the jquery hidden value to php - php

in my code i am creating a drop down box and storing the changed value of the drop down in hidden variable.
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<select id="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<input type="hidden" id="inputfield">
<div></div>
<script type="text/javascript">
$(document).ready(function() {
$("#sweets").change(function() {
var var_name = $(this).val();
$('input[id=inputfield]').val(theValue);
}
});
});
});
</script>
</body>
</html>
<?php
if(isset($_POST['form']))
echo $_POST['inputfield'];
?>
once the combo box is changed the php should get the hidden field value and i ve to perform db transaction. again i need to load another drop down box based on the selected value.. Can you guide me

You can bypass all the horse trading with the hidden field and send it to php directly via ajax.
$(document).ready(function() {
$("#sweets").change(function() {
$.post('myphpfile.php', {sweet : $(this).val() });
});
});
myphpfile.php will receive the value as a post with the name of 'sweet'

Unless I'm misunderstanding, shouldn't
$('input[id=inputfield]').val(theValue);
be
$('input[id=inputfield]').val(var_name);
?

You can wrap the select and hidden elements in form element adding a post method and action attribute. Give the hidden field a name as in name="hidden field"
this way you can access it in the post variable.
<form action="currentpage.php" method="post">
<select id="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<input type="hidden" id="inputfield" name="hiddenfield"/>
<input type="submit" value="Submit" name="submit"/>
</form>
When the change event executes to update the hidden field and you submit in php you can do
if(isset($_POST["submit"]))
{
$val = $_POST["hiddenfield"] ;
}

Related

Pass value to PHP after HTML Select Change

My html form has a Select option. a Mysql query runs after i Change data from option and Submit the data . What i want is, After selecting the data from select it will reload and pass the value to php code.
Here is the html
<form action='a.php?'>
<SELECT name="client_id" ID="mySelect">
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<input type="submit" name="chooseclient" value="Select">
</form>
Here is the php that runs after submit
if(isset($_POST['chooseclient'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['client_id']);
MYSQL query here
}
I have tried this.form.submit() , but that doesnt send data. I understand that i need to Ajax . Is there any way to onChange reload the form and pass data to php ?
To achieve what you are expecting you will have to do a little javascript. From what I understand you don't need to send ajax request as you asked for your form to reload when it gets submitted. But I'll give you both approaches.
No AJAX
First we will add a id to your form. Here in my example it will be "my-form". And an onchange event to your select that will call myFunction();.
We must also tell to your form to post the data for your current PHP script to work or it will send it as a get
<form id="my-form" action='a.php?' method="post">
<SELECT onchange="myFunction()" name="client_id" ID="mySelect">
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<input type="submit" name="chooseclient" value="Select">
</form>
Now in a javascript file or between a script tag add your function :
<script>
function myFunction(){
document.getElementById("my-form").submit();
}
</script>
Now your form should submit itself when you change the value of your select. BUT you will have another problem.
if(isset($_POST['chooseclient'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['client_id']);
//MYSQL query here
}
When you submit a form via javascript, your submit button will not be sent with the rest of the data. so if(isset($_POST['chooseclient'])) will never be true. To tackle this you have a few options, I'll give you two :
You could change your PHP to check on client_id instead (If you do this you can remove your submit button completely) :
if(isset($_POST['client_id'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['client_id']);
//MYSQL query here
}
Or change your submit button to a hidden field :
<form id="my-form" action='a.php'>
<SELECT onchange="myFunction()" name="client_id" ID="mySelect">
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<input type="hidden" name="chooseclient" value="Select">
</form>
Ajax
Just like in the first method we will add a id to your form and an onchange event to your select you should also remove your submit button or change it for an hidden field, in this example I will remove it :
<form id="my-form" action='a.php'>
<SELECT onchange="myFunction()" name="client_id" ID="mySelect">
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
</form>
And the script wich will be quite different to the first one :
<script>
function myFunction(){
var form = document.getElementById("my-form");
var action = form.getAttribute("action");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", action);
xhr.send(data);
}
</script>
Again you will have to fix your PHP not to condition on chooseclient (Unless you made it an hidden field) :
if(isset($_POST['client_id'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['client_id']);
//MYSQL query here
}
If you choose the ajax method you may want to do something with the response, there are plenty of threads on stackoverflow about this, here is one : How to get the response of XMLHttpRequest?
If you want to send the selected value automatically by Ajax to a.php when the field value is changed, you can use the following code :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<form action='a.php?'>
<SELECT name="client_id" ID="mySelect">
<option value="A1>'">A1</option>
<option value="A2">A2</option>
<option value="A3">A3</option>
</SELECT>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#mySelect").change(function(){
var value =$("#mySelect").val();
alert(value);
$.ajax({
url: 'a.php',
type: "POST",
data: ({chooseclient: value}),
success: function(){
location.reload();
}
});
});
});
</script>
</body>
If you do not want the page to be reloaded after sending information and saving to the database, ‍ comment it location.reload();
a.php :
<?php
if(isset($_POST['chooseclient'])){
$clientid = mysqli_real_escape_string($mysqli, $_POST['chooseclient']);
#MYSQL query here
# do something
}

send select value as a param to url with out submit button using ajax

<html>
<head>
</head>
<body>
<form action="area.php" method="get">
<select name="xyz">
<option value="1">option1</option>
<option value="2">option2</option>
</select>
</body>
</html>
I want to send data of value of option as a param to form action with out submit button.
I have seen ajax and jquery but submit button is required every time.
I'll use jQuery syntax for its brevity. You can easily do this in native Javascript also.
Here's an abbreviated version of your form:
<form action="area.php" method="get" id="myform">
<select id="myselect">
<!-- ... options ... -->
</select>
</form>
Have this Javascript run when the page is done loading (note the first line). It's important that the .change() be bound after the form has been rendered.
$(document).ready(function() {
$("#myselect").change(function() {
$("#myform").trigger("submit");
});
});
This will fire the default submit action on the form whenever the select element is changed.
You can use ajax for that as follows:
$(".selectElement").on('change',function(){
$.ajax({
url: "area.php",
method: "POST"
});
});
You can get some documentation on this http://api.jquery.com/jquery.ajax
HTML:
<form>
<select name="xyz" id="mySelect">
<option value="1">option1</option>
<option value="2">option2</option>
</select>
</form>
jQuery:
$(function(){
$("#mySelect").on("change", function(){
var getValue = $(this).val();
$.ajax({
url:'area.php',
type:'get',
data:{ selectValue:getValue },
// get this value #area.php using $_GET['selectValue'];
success:function(response){
// whatever you echoed in area.php, comes in response
}
});
});
});
<select name="xyz" onchange="this.form.submit()">
<option value="1">option1</option>
<option value="2">option2</option>
</select>
You can try using this :
<html>
<head>
<script type="text/javascript">
function call_ajax (str) {
alert(str);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("abc").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "a.php?value="+str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="a.php" method="get">
<select name="xyz" id="abc" onchange="return call_ajax(this.value)">
<option value="1">option1</option>
<option value="2">option2</option>
</select>
</body>
</html>

Setting input values with the values returning from PHP

I have a form and I want to set the values of the input fields on change of a form select. On change of the select ajax jquery runs and calls a PHP file with get method. But I don't know how to return the values from PHP (array or echo or any other way) and how to set them to the input values.
Using jQuery, this could be desired solution:
<form name="frm">
<input type="text" name="age" id="txtAge" />
<input type="text" name="country" id="txtCountry" />
<select name="name" id="selName">
<option value="Ceyhun Ganioglu">Ceyhun Ganioglu</option>
<option value="ABC">ABC</option>
<option value="CED">CED</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('select#selName').change(function(){
var name = $(this).val(); // selected option's value
$.getJSON("<URL_TO_PHP_SCRIPT>", { name: name }, function(data){
// on success, put returned value in textbox
// return data is in JSON (note, I am using `.getJSON` now)
$("#txtAge").val(data.age);
$("#txtCountry").val(data.country);
});
});
});
</script>
Your PHP Code could be:
<?php
echo json_encode(array('age' => 21, 'country' => 'US')); // you need to return on the basis of name, :)
?>
Read Ajax doc for jQuery $.getJSON here: http://api.jquery.com/jquery.getjson/
Other Ajax functions in jQuery: http://api.jquery.com/jquery.ajax/

Use HTML variable inside JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)
Let's say there is some PHP file called as scheduler.php. It contains a script
<script>
window.setInterval(function(){
find_opt_schedule();
}, 60000);
</script>
... and some PHP code:
<form action="scheduler.php" method="post">
<select name="refresh" id="refresh">
<option value="30000">30000</option>
<option value="60000" selected>60000</option>
<option value="120000">120000</option>
</select>
</form>
How do I use the value selected by the user from refresh select list inside the script? In particular, I want to replace 60000 by the variable that must be selected by the user from the list. I tried this, but the refresh rate is very high instead of 60000 miliseconds.
window.setInterval(function(){
find_opt_schedule();
alert(<?php echo (int)$_POST['refresh']; ?>);
}, <?php echo (int)$_POST['refresh']; ?>);
Your values should be (30000, 60000, 120000), not (0, 1, 2). The POST field contains the value of the selected option, not the text.
Note: You should have been able to figure this out by checking the source of the resulting HTML document. The "1" ought to stick out like a sore thumb.
<select name="refresh" id="refresh">
<option value="30000">30000</option>
<option value="60000" selected>60000</option>
<option value="120000">120000</option>
</select>
window.setInterval(function(){
find_opt_schedule();
}, <?php echo (int)$_POST['refresh']; ?>);
And make sure you use:
<form action="yourscript.php" method="post" name="form" id="form">
And a submitbutton, or javascript:
<select name="refresh" id="refresh" onchange="form.submit()">
<input type="submit" value="Set refresh"/>
All together, with session storage:
<?php
session_start();
if( isset( $_POST['refresh']) ){
$_SESSION['refresh'] = (int) $_POST['refresh'];
}
?>
<script type="text/javascript">
window.setInterval(function(){
find_opt_schedule();
}, <?php echo isset($_SESSION['refresh'])?$_SESSION['refresh']:120000; ?>);
</script>
<form action="scheduler.php" method="post" name="form" id="form">
<select name="refresh" id="refresh" onchange="form.submit()">
<option value="30000">30000</option>
<option value="60000" selected="selected">60000</option>
<option value="120000">120000</option>
</select>
<input type="submit" value="Set refresh"/>
</form>
Use JQuery:
<html>
<body>
<select name="refresh" id="refresh">
<option value="30000">30000</option>
<option value="60000" selected>60000</option>
<option value="120000">120000</option>
</select>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function setInterval(refresh_rate)
{
window.setInterval(function(){
find_opt_schedule();
}, refresh_rate);
}
$(function(){
$('#refresh').change(function () {setInterval($(this).val());});
}
</script>
</body>
</html>
Erm... that's just plain HTML. All you need is to read it and adjust the timeout as needed:
<script>
(function() {
var start = new Date().getTime(),
selector = document.getElementById('refresh');
setInterval(function() {
// check if timer has run out
var now = new Date().getTime();
if( now-start > selector.value) {
find_opt_schedule();
start = now;
}
},1000);
})();
</script>

PHP/Javascript post js variable to php page

Though a novice in javascript, I need to take javascript variable (an array) reflecting what a user has done on client side and post it to a PHP server page on submit.
It was suggested that I include this as a value in a hidden field in a form to post to the php page. However, since the JS variable is dynamically created by the user, I can't write to the page for inclusion in the form unless I call a function that refreshes the page. To avoid a double page refresh, I'd prefer to have the submit function both grab the data and simultaneously post it to the php script. AJAX if I understand correctly, should not be needed because I'm okay reloading the page once on submit. I just don't want to reload twice.
The following uses the function suggested by Andrew to set the js variable and post. Th form posts as I get the other hidden variable in the form but I am not getting the variable set by js, possibly because there is a mistake with the naming of the variables.
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function postData(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
window.location = "posttoserver.php?data="+options[i].value;
}
function setTheValue(val) {
var options = document.getElementById(listBoxID).options;
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<form id="myForm" action="getdata.php" method="get">
<input type="hidden" name="data" />
<input type="hidden" name="mode" value="savedit">
<button onclick="setTheValue(options)">Submit Data</button>
</form>
</body>
</html>
On the other end I have in getdata.php:
<?php
$mode = $_REQUEST['mode'];
$option = $_REQUEST['data'];
echo $mode;
echo $option;
print_r ($option);;
?>
Finally solved it days later with document.getElementById('varname').value
For newbs like me, document.getElementById does not merely retrieve data as you might think and most documentation mentions. It also sets data.
The key is to write the statement backwards and also (as you must do to retrieve a value) put id== into the element you want to set.
If you write var test = document.getElementById('text'); and you have put id="text" in some field, it will retrieve the value of text. That's what the usual documentation mentions. However, if you write:
document.getElementById('varname').value = "dog"
it will insert "dog" into the element that contains id=varname.
While that may be obvious to the more experienced, it certainly confused me.
Following code works.
<html>
<head>
<script>
function Post(data)
{
document.getElementById('varname').value = data
}
</script>
</head>
<body>
<form action = "" method="get">
<input id="varname" type="hidden" name="d">
<button onclick="Post('dog')">Post to Server</button>
</form>
</body>
</html>
You can go ahead and create a form like you normally would with an empty hidden field:
<form id="myForm" action="posttoserver.php" method="get">
<input type="hidden" name="data" />
...
<input type="submit" value="Submit" />
</form>
And you can use a JavaScript function to set the value of the hidden field:
function setTheValue(val) {
var form = document.forms['myForm'];
hiddenField = oFormObject.elements["data"];
hiddenField.value = "val";
}
You can then call the function setTheValue(val) when your button is clicked or whatever.
I hope this helps!
jQuery actually makes this very simple. You have the right idea but using window.location is going to change your page. What you are looking to do is make a async request to another url while you remain on your current page.
http://api.jquery.com/jQuery.ajax/

Categories