Have a form like:
<form name="myform" action="All.php" method="get">
<input type='text' id='tx' name='tx' value=''>
<td height="8" align="right" valign="middle">All Cities | Newyork | Police</td></form>
<script type="text/javascript">
function submitform(val)
{
$("#tx").val(val);
document.myform.submit();
}
</script>
And in All.php:
<form method="get" action="index1.php" id="frm1">
<select id="category" onchange="showSelected1();" style="width:150px">
<option></option>
<option value="1" <?php if($_GET["categoryText"] == "Marriages") echo "selected"; ?> >Marriages</option>
<option value="2" <?php if($_GET["categoryText"] == "Birthdays") echo "selected"; ?> >Birthdays</option></select>
<input type="hidden" id="categoryText" name="categoryText" value='<?= $_GET['categoryText']; ?>'/>
<select id="city" onchange="showSelected();" style="width:150px">
<option><?= $_GET['tx']; ?></option>
<option></option>
<option value="1" <?php if($_GET["cityText"] == "Newyork") echo "selected"; ?> >Newyork</option>
<option value="2" <?php if($_GET["cityText"] == "Police") echo "selected"; ?> >Police</option></select>
<input type="hidden" id="cityText" name="cityText" value='<?= $_GET['cityText']; ?>'/>
<input type="button" value="Submit" onclick="formSubmit()"/></form>
<script language="JavaScript" type="text/javascript">
<!--
function showSelected()
{
var selObj = document.getElementById('city');
var cityTextObj = document.getElementById('cityText');
var selIndex = selObj.selectedIndex;
cityTextObj.value = selObj.options[selIndex].text;
}
//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--
function showSelected1()
{
var selObj = document.getElementById('category');
var categoryTextObj = document.getElementById('categoryText');
var selIndex = selObj.selectedIndex;
categoryTextObj.value = selObj.options[selIndex].text;
}
//-->
</script>
Means, from first page contents filling into a form itself in All.php. If somebody clicks submit button without changing the selection city, in All.php, its not showing and not taking the city value to index1.php. Why is that?
you can try
document.getElementById("myform").submit();
You have write wrong variable name into your below code
<script type="text/javascript">
function submitform(val)
{
$("#hx").val(val);
document.myform.submit();
}
</script>
your have used hx insted of tx, so your code may be like this
<script type="text/javascript">
function submitform(val)
{
$("#tx").val(val);
document.myform.submit();
}
</script>
change this and try your code again.
I have seen many other problems into your code , learn how to use single quote (') and double quote("). You have written this
value='<?= $_GET['categoryText']; ?>' which is wrong.
correct way is value='<?php $_GET["categoryText"]; ?>'
Update you code according to this and run it again and come back here if there any problem.
Related
I have a php form I'll call it "php1" that uses ajax to populate the input text boxes from a mySQL db. to do so it uses a secondary page I'll call "php2". On php2 there is a submit "button" being used to submit any changes to the mySQL db. Every aspect works beautifully, except the submit, unless I test php2 by itself, then it submits to the db.What am I doing wrong?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function myBlur(str){
if (str == "") {
document.getElementById("demo").innerHTML = "You Must Enter a Device Name! <br>";
$("#demo").css("background-color","red");
$("#Name").css("background-color","red");
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("form1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","php2.php?q="+str,true);
xmlhttp.send();
}
}
</script>
This is to call the second page.
<fieldset><legend>Input</legend>
<div width="100%" id="form1">
<div id="demo"><br></div><br>
<form method="post" action="php1.php">
Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="<?php echo $Name ?>" onChange="myBlur(this.value)">
MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="<?php echo $MAC ?>">
Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="<?php echo $Own ?>">
Type: <select name="Type" id="Type" required="required" readonly="true" value="<?php echo $Type ?>">
<option value=""></option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Server">Server</option>
<option value="Monitor">Monitor</option>
<option value="Printer">Printer</option>
<option value="Phone">Phone</option>
</select>
<br>
</div>
</fieldset>
</form>
That is the form code from php1
$sql = "SELECT * FROM $table WHERE Name = '$q'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$N=$row["Name"];
$MA=$row["MAC"];
$Ow=$row["Own"];
$Ty=$row["Type"];
echo "<tr>";
echo "<form method='post' action='php1.php' id='UpAss'>",UpAss,"
<br><br>
Device Name: <input type='text' id='Name' name='Name' value=".$N." onBlur='myBlur(this.value)'>
MAC Address: <input type='text' id='MAC' name='MAC' readonly='True' autocomplete='off' value=". $MA.">
Owner or Location: <input type='text' id='Own' name='Own' value=". $Ow.">
Type: <select id='Type'>
<option value='".$Ty."'>". $Ty."</option>
<option value='Desktop'>Desktop</option>
<option value='Laptop'>Laptop</option>
<option value='Server'>Server</option>
<option value='Monitor'>Monitor</option>
<option value='Printer'>Printer</option>
<option value='Phone'>Phone</option>
<option value='iPhone'>iPhone</option>
</select>
echo "<input type='submit' id='Usubmit' value='Update Asset' form='UpAss' onClick='myUpdate()'></input></form>";
}
function myUpdate()
{
// Create connection
$connU = new MySQLi($db_host, $db_user, $db_pass, $db_name, $db_port);
// Check connection
if ($connU->connect_error) {
die("Connection failed: " . $connU->connect_error);
}
$Name = ($_POST["Name"]);
$MAC = ($_POST["MAC"]);
$Own = ($_POST["Own"]);
$Model = ($_POST["Model"]);
$OS = ($_POST["OS"]);
$Type = ($_POST["Type"]);
$sqlU = "REPLACE INTO SET $table SET MAC='$MAC', Own='$Own', Type='$Type' WHERE Name=$Name;";
if ($connU->query($sqlU) === TRUE) {
echo "PPC-".$Name." Has Been Updated!";
} else {
echo "Error: " . $sqlU . "<br>" . $connU->error;
}
$connU->close();
}
if(isset($_POST['Usubmit']))
{
myUpdate();
}
?>
And that is the code to load the form from php2 in to php1. I am sure it is something simple that I am missing and would appreciate any help. all this code works great, but the submit.
*(I left the DB information out of this code on purpose.)
1.) For Posting(Insert, update and delete via ajax)
This will get you started on how to post via ajax jquery. you can see comments on the code
You can also see that form parameter is set to id="add_content" which is refrenced in the jquery ajax call
<form method="post" id="add_content">
you can also see in the body of the html div that shows image loader when button is click and when result from backend is displayed hence
see sample on that
post.html
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$('#add_content').on('submit', function(e){
e.preventDefault();
alert('ok');
// display a loading image and message
$('#loader').fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Please Wait.. submiting form..</span>');
$.ajax({
type:'POST',
url:'post.php',
data:$(this).serialize(),
crossDomain: true,
cache:false,
success:function(msg){
// hide loader to display result
$('#loader').hide();
$('#showposts').fadeIn('slow').prepend(msg);
}
});
});
});
</script>
</head>
<body>
<div id="loader"> </div>
<div id="showposts"> </div>
<form method="post" id="add_content">
Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="100" onChange="myBlur(this.value)">
MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="1001">
Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="nancy read only">
Type: <select name="Type" id="Type" required="required" readonly="true" value="nancy type">
<option value=""></option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Server">Server</option>
<option value="Monitor">Monitor</option>
<option value="Printer">Printer</option>
<option value="Phone">Phone</option>
</select>
<br>
</div>
</fieldset>
<input type="submit" name="add" id="add" value="Add" />
</form>
</body>
example of post.php
<?php
// use strip_tags to avoid html injection that can also leads to xss attck
// sample with assets number
$asset_number= strip_tags($_POST['Name']);
$MAC= $_POST['MAC'];
$Own= $_POST['Own'];
$Type= $_POST['Type'];
// you can check for emptiness eg.
if($asset_number ==''){
echo "asset number is empty";
exit();
}else{
echo "success. my assests no is: $asset_number";
}
?>
sample 2.
if you want fetch records only with or without sending parameters, you can try
Remember to pass jquery library (jquery.min.js) if you are calling it from another page
<script>
$(document).ready(function(){
// set variable payload for formality. though you can pass it to backend as a variable
var payload= 'Am Nancy Mooree';
var datasend = "payload="+ payload;
$('#loader1').fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Please Wait.. submiting form..</span>');
$.ajax({
type:'POST',
url:'showresult.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#loader1').hide();
$('#listposts').fadeIn('slow').prepend(msg);
}
});
});
</script>
<div id="loader1"></div>
<div id="listposts"></div>
showresult.php
<?php
// assuming you are sending a post or get variables to query database
$payload= strip_tags($_POST['payload']);
// query your database to display result to ajax.
echo $result ="Am from database where payload is: $payload";
?>
This is my view file code
<?php for($i=0; $i<4; $i++) { ?>
<div class="box22">
<div class="mcm">
<input type="text" placeholder="Myself" id="coworkers" name="coworkers[]" />
<span class="bar"></span>
</div>
<div class="select2">
<select id="category_<?php echo $i; ?>" name="category[]" class="chosen-select ref-sel1" multiple >
<?php
foreach($genre as $gen){
echo '<option value='.$gen->genre_id.'>'.$gen->genre_name.'</option>';
}
?>
</select>
</div>
</div>
<?php } ?>
my script : when i chose one or more from option, it does not comes into script. How to get multiple values under loop
$(document).ready(function()
{
$('form#shortfilm').submit(function(e)
{
e.preventDefault();
var form = $(this);
var foo = [];
$('#category :selected').each(function(i, selected){
foo[i] = $(selected).text();
});
});
});
change text to val()
$('option:selected').each(function(i, selected){
foo.push($(selected).val());
});
or:
var foo = [];
$('.box22').each(function(x,v){
var temp =[]
$(v).find('option:selected').each(function(i, selected){
temp.push($(selected).val());
});
foo.push(temp)
});
see demo for the second option here
Please run this sample code. This may help you
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<form id="shortfilm" name="data">
<?php $genre=array(1=>'AAAAAAAAAAAAAA',2=>'BBBBBBBBBBBBBBB',3=>'CCCCCCCCC',4=>'DDDDDDDDDDDDDD',5=>'EEEEEEEEEEEEEEE');
for($i=0; $i<4; $i++) { ?>
<div class="box22">
<div class="mcm">
<input type="text" placeholder="Myself" id="coworkers" name="coworkers<?php echo$i?>[]" />
<span class="bar"></span>
</div>
<div class="select2">
<select class="category" name="category<?php echo$i?>[]" class="chosen-select ref-sel1" multiple >
<?php
foreach($genre as $key => $gen){
echo '<option value='.$key.'>'.$gen.'</option>';
}
?>
</select>
</div>
</div>
<?php } ?>
<input type="submit" value="submit" />
</form>
<script>
$(document).ready(function()
{
$('form#shortfilm').submit(function(e)
{
e.preventDefault();
var form = $(this);
var foo = [];
$('.category :selected').each(function(i, selected){
foo[i] = $(selected).text();
});
console.log(foo);
});
});
</script>
</body>
</html>
Using the .val() function on a multi-select list will return an array of the selected values:
var selectedValues = $('#category').val();
And in your html <select id="category" multiple="multiple">
Also put the values of the $gen->genre_id in a variable and so like this
foreach($genre as $gen){
$genId = $gen->genre_id;
$genName = $gen->genre_name;
echo '<option value='.$genId.'>'.$genName.'</option>';
}
Also <select id="category" in a forloop will have many select elements with the same id,change that to category[$i] or use class
I have a select box outside my form, When the users selects an option, the right form is being shown. But I want to send the value of the selected option together with the form.
<select id="selection" onchange="showForm()">
<option value="iphone">iPhone</option>
<option value="Android">Android</option>
</select>
<form action="iphone.php" method="post" id="form1">
<input type="text name="username" required>
</form>
<form action="android.php" method="post" id="form2">
<input type="text name="username" required>
</form>
Please note: This is a simple example, I want to know how you can send the value of the selectbox outside the form.
Add to each form a hidden input element:
<input type="hidden" name="selection" class="hiddenselection" />
Use javascript to copy the value on change. In jquery something like this:
$('#selection').on('change',function(){
$('.hiddenselection').val($('#selection').val());
})
function showForm(value) {
$.ajax({
type: "POST",
success: function(value){
if(value =='iphone'){
$("#form2").hide();
}else{
$("#form1").hide();
}
}
});
}
Keep the selected value in hidden field form1 and form2
<select id="selection" onchange="showForm(this)">
<option value="iphone">iPhone</option>
<option value="Android">Android</option>
</select>
<form action="iphone.php" method="post" id="form1">
<input type="text" name="username" required />
<input type="hidden" name="selection" id="iphone_selection" />
</form>
<form action="android.php" method="post" id="form2">
<input type="text" name="username" required />
<input type="hidden" name="selection" id="android_selection" />
</form>
<script>
function showForm(THIS){
var thisVal = $(THIS).val();
if(thisVal == 'iphone'){
$('#form2').hide();
$('#form1').show();
$('#iphone_selection').val(thisVal);
//$("#form1").submit();
}
if(thisVal == 'Android'){
$('#form1').hide();
$('#form2').show();
$('#android_selection').val(thisVal);
//$("#form2").submit();
}
}
</script>
<style>
#form1{
display:none;
}
#form2{
display:none;
}
</style>
https://jsfiddle.net/9tms99p5/
Try to include this script on your code.
<script type="text/javascript">
window.onload = function(){
document.getElementById("selection").onchange();
};
function showForm(){
if(document.getElementById("selection").value == "iphone"){
document.getElementById("form1").style.display = "block";
document.getElementById("form2").style.display = "none";
}else if(document.getElementById("selection").value == "Android"){
document.getElementById("form1").style.display = "none";
document.getElementById("form2").style.display = "block";
}
}
</script>
I’m using below a simple Jquery code to call a PHP page and get the button information back in a div:
<head>
<script>
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
myPHPfile.php
<?php
if( $_REQUEST["selectedButtonValue"] )
{
$buttonPHP = $_REQUEST['selectedButtonValue'];
echo "Value button is ". $buttonPHP;
}
?>
How can I get the PHP information inside JavaScript, as follows:
alert(<?php echo('buttonPHP'); ?>);
Note: The following code shows the alert box message, but I can’t use it since I need the $buttonPHP value:
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data){ alert(data); });
I’ve tried $_SESSION in myPHPfile.php, and also all jQuery AJAX functions: load(), get(), post() and the ajax() method, none of them is giving the PHP value inside JavaScript.
I looked all over but I couldn’t find an answer.
You would be better with an $.ajax request. Don't echo the 'Value of button is' part, just echo the actual value. For example:
$.ajax({
url: "myPHPfile.php",
context: document.body
}).done(function(data) {
var buttonValue = data;
// Whatever you want to do with the data goes here.
});
See the jQuery docs http://api.jquery.com/jQuery.ajax/
Alternatively, if you are generating the page with PHP, just echo the PHP variable into the JavaScript
<script>
...
var buttonValue = "<?php echo $buttonPHP; ?>";
...
</script>
Encode it in JSON instead of trying to echo the data :
<?php
if( $_GET["selectedButtonValue"] )
{
$buttonPHP = $_GET['selectedButtonValue'];
header('Content-Type: application/json');
echo json_encode($buttonPHP);
}
?>
Then use jquery get json to grab the data
$.get('myPHPfile.php?selectedButtonValue='+buttonvalue, function(data){
console.log(data);
});
Try:
alert('<?php echo $buttonPHP; ?>');
As a temporary solution, you could quickly merge both into a dirty code like this:
index.php:
<?php
$buttonPHP = "10"; //Set up your default button variable
if( $_REQUEST["selectedButtonValue"] == 10 )
{
echo "Selected button value: 10"; //You can also print $_REQUEST["selectedButtonValue"] here directly, but what's the point if you can select it from DOM through jQuery?
exit;
} else if ($_REQUEST["selectedButtonValue"] == 20) {
echo "Selected button value: 20";
exit;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $buttonPHP ?>; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
index.php rendered in browser:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = 10; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
EDIT: Stored session
<?php
session_start();
if (isset($_REQUEST['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = $_REQUEST['selectedButtonValue'];
echo $_REQUEST['selectedButtonValue'];
exit;
} else if (!isset($_SESSION['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = 10;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?>;
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv"><?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?></div>
</body>
</html>
Also make sure you filter the $_REQUEST variable, because as of now, it will print anything. See http://en.wikipedia.org/wiki/Cross-site_scripting for details.
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>