I want, if I select a value in selectbox 1, that selectbox2 is loaded with values that are dependet on selectbox1.
Here´s how I tried:
<head>
<script src="jquery/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#selectbox1").change(function(){
var value = $(this).children('option.selected').val();
$("#selectbox2").load("php/loadteams.php", {value: value} );
});
});
</script>
</head>
<body>
<?php
include 'php/db.php';
$res = mysql_query("select * from liga", $connection);
echo '<select id="selectbox1">';
while($val = mysql_fetch_array($res)) {
echo '<option value="'.$val['id'] .'">' . $val['name'] . '</option>';
}
echo '</select>';
mysql_close($connection);
?>
<select id="selectbox2"> </select>
Like you see, I tried with jquery. The file loadteams.php looks like that:
<?php
include 'php/db.php';
$ligaid = mysql_real_escape_string($_POST['value']);
$result = mysql_query("select * from mannschaft where liga = '" . $ligaid . "'", $connection);
while($te = mysql_fetch_array($result)){
echo '<option> ' . $te . '</option>';
}
?>
I don´t know where my mistake is - can you help me?
You should try using the :selected selector, instead of .selected which would match a class with the name selected.
Also, I believe the .load() method posts data through HTTP GET, so I believe you would have to use $_GET["value"] instead of $_POST['value'].
Correction:
As you are providing the data as an object, it IS posted through HTTP POST, so strike my above statement. From the jQuery documentation:
The POST method is used if data is provided as an object; otherwise, GET is assumed.
Related
I have looked at this site for three days. I admit I am new to using javascript. But I have used the many different solutions offered and none have worked. Please help.
I am trying to do something that should be simple: save a user choice of country from a dropdown box on an html5 page to a hidden post variable (using javascript onchange.) That is used in a post array on the same form for a php operation that sends the input to a mysql database. This is my code:
The hidden post variable doesn't update. From there I can't test the code logic. But my onchange code came from this site and is suppose to work.
References:
<script type="text/javascript" src="../../js/jquery-2.1.4.min_prod.js"> </script>
<script type="text/javascript" src="../../js/respond.min.js"> </script>
<script type="text/javascript" src="../../js/bootstrap.min.js"> </script>
form information:
<form name="form1" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" />
</form>
form element
$query="SELECT * from country ";
$query=$query."ORDER BY country asc";
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select id="country" onchange="send_name(this)">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
?>
<input type="hidden" id="c_php_value" name="c_php_value" value="">
Javascript
function send_name(selectObjectI) {
var value = selectObjectI.value;
$.ajax({
type: "POST",
url: "http://localhost/php/protected/form_addnews.php",
data:{c_php_value: value}
});
Post Submit Code
$country_id1 = trim($_POST['c_php_value']);
Thanks to a coder on utube, speaking german I might add, I discovered I don't need javascript, ajax or anything complicated to accomplish what I am trying to do.
I simply needed to do the following:
(1) Add a name="" to the dynamically created SELECT flag(name="country_id2").
(2) user chooses input with drop down box created.
(3) gather the $_POST after the form submit is set.
($country_id = $_POST['country_id2'])
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select name="country_id2" id="country_id2">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
I'm making a quiz website, for that questions and answers will be fetched from database and using PHP and MySQL.
I've stored the options in one single column using JSON.(Stored as string array) Question is displaying correctly but options couldn't; I've written them in similar manner.
quiz.php
echo '
<div id="ques_block">
<br>
<p id="ques"></p>
';
for($i=0; $i<$_SESSION["opt_size"]; $i++)
echo '<p class="opt" id="opt'.$i.'"></p>';
echo '
<div id="nav-for"><img src="next.png" alt="Next =>"></div>
</div>
';
next.php will be called using AJAX when NEXT is clicked.
next.php
$sql = "SELECT QUESTION, ANSWER, OPTIONS FROM user_quiz WHERE CUST_NO=$cust_no AND QUES_NO=$new_ques_no;";
$res = mysqli_query($conn, $sql) or die("bad Query: $sql");
if(mysqli_num_rows($res)==0)
echo "END";
else
{
$row = mysqli_fetch_assoc($res);
$ques = $row["QUESTION"];
$opts = $row["OPTIONS"];
$opt = json_decode($opts);
$resRows = sizeof($opt);
echo '
<script type="text/javascript">
document.getElementById("ques").innerHTML="'.$ques.'";
</script>
';
for($i=0; $i<$resRows; $i++)
echo '<script type="text/javascript">
document.getElementById("opt'.$i.'").innerHTML = "'.$opt[$i].'";
</script>
';
}
Edited:
#ADyson I'll try your method, Thanks,
BTW This is AJAX code as requested:
$(document).ready(function(){
$("#nav-for").click(function(){
$.post("nextQues.php",
{custNo: $("#custNo").val(), quesNo: $("#quesNo").val()},
function(data){
$("#ques").html(data);
}
);
});
});
I am trying to test the following code for inserting the value from PHP code to my javascript variable x
tested the PHP code, and it's giving the correct output but the alert box in the javascript shows this -
date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000"; $query = mysql_query($myquery); if ( ! $myquery ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } //echo json_encode($data); echo ''; mysql_close($server); ?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing </title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<?php
$username='user';
$password='pass';
$host='xx.xx.xx.xx';
$database='abc';
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = 'select code a,sum(fee) b from xyz where date > date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000';
$query = mysql_query($myquery);
if ( ! $myquery ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
//echo json_encode($data);
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
mysql_close($server);
?>
<script type="text/javascript">
function test(){
var x = document.getElementById("myPhpValue").value;
alert(x);
}
test();
</script>
</body>
</html>
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
Then:
var x = document.getElementById("myPhpValue").value;
you need to insert id="myPhpValue", because you used the "getElementById";
Add ID attribute in the html line
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
replace the above line by
echo '<input type="hidden" name="myPhpValue" id ="myPhpValue" value="'. json_encode($data) . '">';
You are inserting a value into html, not javascript code.
Do it like that:
<script type="text/javascript">
function test(){
var x = <?php echo json_encode($data); ?>;
alert(x);
}
test();
</script>
Server configuration problems
If You are getting php code on client-side (view-source to confirm), then the PHP engine is not working on the server.
You should check that php is properly installed on the server and is set as a handler for php files in your web server.
This depends on your web server and operating system.
Code problems
Problem #1: your output (echo) is creating an HTML element, not javascript. Hence you should escape the content for HTML - use htmlspecialchars instead of json_encode
Problem #2: you access the element with javascript document.getElementById but your actual element does not have an ID. Hence need to add the id attribute to your html input element.
Solution:
Stage 1: php outputs html - use htmlspecialchars and add id attribute
echo '<input type="hidden" name="myPhpValue" id="myPhpValue" value="'. htmlspecialchars($data) . '">';
Stage 2: javascript accesses html element (this is taken as-is from your code).
var x = document.getElementById("myPhpValue").value;
Side-note
You're using a deprecated mysql extension and should switch to PDO or mysqli instead.
There are numerous discussions both on SO and external resources on the matter.
Just a few:
Choosing an API - PHP manual
What is the difference between MySQL, MySQLi and PDO?
mysqli or PDO - what are the pros and cons?
I'm using x-editable http://vitalets.github.io/x-editable/index.html a jquery inplace editor. Currently I have a working code like below:
<?php
$num_rows = 1;
// store the record of the "tblstudent" table into $row
while ($row = mysqli_fetch_array($result)) {
echo "<script type=\"text/javascript\">
$.fn.editable.defaults.mode = \"popup\";
$('#username$num_rows').editable();
</script> "; //assign num to element
// Print out the contents of the entry
echo '<tr>';
echo '<td><a href="#" id="username' . $num_rows . '" data-type="text" data-pk="' . $row['id'] . '" data-url="post.php" data-title="Edit website">';
echo htmlspecialchars($row['website'], ENT_QUOTES, 'UTF-8');
echo '</a></td>';
echo '</tr>';
$num_rows++;
}
?>
Which result in the following:
but as you can see I use $num_rows in assigning element ID and getting the ID with javascript. I prefer not to use loop to assign uniq ID to element or include the javascript in php tag. Is there any elegant solution than this?
Thanks in advance.
Keep the id as username or infact add class='username' instead of id.
<script type="text/javascript">
$.fn.editable.defaults.mode = "popup";
$('.username').click(function(){
$(this).editable();
})
</script>
Hi I am trying to create a set of drop down boxes that will use an array of data from the values that you pick and then runs through a loop to post them to the screen at the moment the data that i want to use will just be local but i want to edit this later so that it will loop through the data from my database and post that to the screen. i have looked at other questions on this subject and just wondering how i would change it for my code i have looked at this link questions on stack overflow that I have looked at i have just got a couple questions that im wondering if anybody has seen this before or if they have seen any examples i have also looked at for loops and i understand the concept
my questions to you are:
1) how would I post the values from my drop down boxes into a php array
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
3)Would I need to use a second language like javascript or can it be done just in php
My drop down box code is
<div id="Content">
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="%">any...</option>
</select>
<br /><br />
Choose a principle:<br />
<select id="principle">
<option value="%">any...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<!-- end of the Options -->
below is the select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM subject";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['subject_id'] . '">' . $row['description'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM section WHERE subject_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['section_id'] . '">' . $row['description'] . '</option>';
}
return $type;
}
public function ShowPrinciple()
{
$sql = "SELECT * FROM principle WHERE section_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$principle = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$principle .= '<option value="' . $row['principle_id'] . '">' . $row['description'] . '</option>';
}
return $principle;
}
}
$opt = new SelectList();
?>
1) how would I post the values from my drop down boxes into a php array
In the form tag add method="POST". Reference in PHP with $_POST array. Make sure to validate and escape the data before writing to your DB.
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
If you don't have millions of categories, you are better off sending them all as a JSON array and using Javascript. Something like:
<script>
var categories = <?php echo json_encode($opt->ShowCategory()); ?>;
</script>
json_encode may require some options to be set, depening on your character set. More info here: http://php.net/manual/en/function.json-encode.php
Making a new request each time someone changes a dropdown box will drive them crazy, I know I hate that. If you have used jQuery before, this is very easy. This isn't that difficult without it.
3)Would I need to use a second language like javascript or can it be done just in php
For the sake of your users, use Javascript.
code for showCategory()
...
$categories = new array();
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$categories[$row['subject_id']] = $row['description'];
}
$validCategories = $this->getValidCategories() // get the valid categories
foreach($categories as $index=>$cat){
// only choose the categories that are valid
if(array_search($cat,$validCategories) !== FALSE)
$category.= '<option value="'.$index.'">'.$cat.'</option>';
}
return $category;