Unable to send two strings together using PHP to JavaScript - javascript

I'm trying to pass database value javascript / ajax. If if send directly it works well,
The same I'm trying to do from database. And some how it doesn't work.
I'm sending value of the option to script like this,
<select name="users" onchange="showUser(this.value)">
and when I send value directly like this, It show the correct value in script.
<option value="Peter Grif">Peter Griffin</option>
Script Result is = Peter Grif
And if the same I fetch from database, like this.
while($row=$select->fetch_assoc())
{
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
In Dropdown box it is exactly working with full name like "Peter Grif"
But the script result is = "Peter" the second part of name after space never comes.
Full Program:
<html>
<head>
<script>
function showUser(str) {
window.alert(str);
}
</script>
</head>
<body>
<body>
<form>
<center> <select name="users" onchange="showUser(this.value)"> </center>
<option value="Peter Grif">Peter Griffin</option>
<option value="Lois Griff">Lois Griffin</option>
<?php
include("connection.php");
$select=$con->query("select name from users group by name");
while($row=$select->fetch_assoc())
{
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
?>
</select>
</form>
<br>
</body>
</html>

I modified your code in while loop and it works as you want. Its the quotation issue.
<html>
<head>
<script>
function showUser(str) {
window.alert(str);
}
</script>
</head>
<body>
<body>
<form>
<center> <select name="users" onchange="showUser(this.value)"> </center>
<option value="Peter Grif">Peter Griffin</option>
<option value="Lois Griff">Lois Griffin</option>
<?php
include("connection.php");
$select=$con->query("select name from users group by name");
while($row=$select->fetch_assoc())
{
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
?>
</select>
</form>
<br>
</body>
</html>

echo "<option value=".$row['name'].">".$row['name']."</option>";
The option value needs to be quoted. You are ending up with
<option value=Peter Grif>Peter Grif</option>
It needs to be quoted so it ends up like
<option value='Peter Grif'>Peter Grif</option>
So either
echo "<option value='".$row['name']."'>".$row['name']."</option>";
or perhaps
echo "<option value='{$row['name']}'>{$row['name']}</option>";
(you can reference arrays within double quotes by surrounding by curly brackets, I feel it makes it easier to read than concatenation, so you don't get quote confused when echoing HTML especially, but it's just my preference).
Doing view source on page can help with these things to make sure the generated HTML is valid.

Related

Changing the select value in php

I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output

I want to populate a second select form based on the first one selection. Both are retrieving their elements from an sql database

This is my first post here.
I'm less than beginner in HTML or Java script, I'm doing this only from a month or so.
So, this is my first project.
I need to populate two select forms with data retrieved from a SQL database.
First select is a "Car brand" second one is "Car model" which is based on the first one.
I have managed to populate the first select and to get the selected value in java script variable x.
How should I proceed do next to read the models from the selected brand?
Here is what I have done until now:
<?php
include("sql.php"); //connection to the database
$sql_select_marca = "select id, denumire from marca"; //sql statement to retrieve brands
$stmtMarca = sqlsrv_query( $conn, $sql_select_marca);
?>
<html>
<title> Adauga Oferta </title>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<form cars style="position: absolute">
<p> Marca:</p>
<select id=SelectBrand class="select" name="marcaSelectata"
form="cars" style="position: absolute" onchange="marca()">
<option value="">Select brand</Seleteaza> </option>
<?php
while( $row = sqlsrv_fetch_array( $stmtMarca)) {
echo '<option value=' . $row['id'] . '>' . $row['denumire'] . '</option>';
}
?>
</select>
<p style="margin-left: 290px"> Model:</p>
<select id="SelectModel" class="select" name="model" form="cars" style="position: absolute;margin-left: 360px" onchange="model()" >
<option value="">Select model</Seleteaza> </option>
</select>
</form>
<p id="Brand"> You've selected:</p>
<script>
function marca() {
var x = document.getElementById("SelectBrand").value;
document.getElementById("Marca").innerHTML = "Ai selectat: " + x;
}
</script>
</body>
</html>
The second select from database should be something like:
select * from model where idmarca = $x
*where x is the id read from the first select
You need to do it with ajax. on Car brand select change you need to make a ajax call to list the second select box values.
For Example refer this

PHP noob having problems posting drop-down values into MySQL database. My table formatting is off too. Can anyone shed some light on this?

Building a football prediction website. I am getting thee Home_team names and away team a names from fixtures table in DBMS, with corresponding drop down boxes for each fixture so that the user can predict the score. I cant get it to work. Grateful for any help!
//establish connection
<?php
$connection = mysql_connect('localhost', 'root', 'password');
mysql_select_db('mls');
$query = "SELECT * FROM fixtures WHERE Fixture_ID BETWEEN '1' and '10' ";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num>0){
echo"<table>";
echo "<th>Home Team</th>";
echo "<th>Home Score</th>";
echo "<th>Away Score</th>";
echo "<th>Away Team</th>";
for($count=0;$count<$num; $count++){
$row = mysql_fetch_array($result);
echo"<tr>
<td>".$row['Home_Team']."</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='H".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select >
</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='A".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td>".$row['Away_Team']."</td>
</tr>";
}
echo"</table>";
<input type="submit" title="Submit the form">
</form>
}
?>
<html>
<?php
//process3.php file
<?php
include_once('db.php');
$Home_Score = $_POST['Home_Score'];
$Away_Score = $_POST['Away_Score'];
if(mysql_query("INSERT INTO user_prediction VALUES('$Home_Score', '$Away_Score')")){
$result = "Successfully Inserted";
else
$result = "Insert failed";
?>
//myscript.js file
?>
$("#sub").click(function(){
$.post( $("#myForm).attr("action"), $("#myForm:input").serializeArray(),
function (info){$("#result").html(info);});
});
$("#myForm").submit(function(){
return false;
});
While there is plenty of things that could be causing problems, notice here:
<select name="Away_Score">
//count id for unique values in dropdown
<select id='A".$count."'>
$count will literally be represented here as the string "$count", due to this code not being contained in PHP tags. Try correcting instances of code similar to this to something like below:
<?php
echo '<select name="Away_Score">';
//count id for unique values in dropdown
echo '<select id="A' . $count . '">';
?>
I see some problems there..
you switch between PHP and HTML appearently without knowing what
is what or how you start PHP and end it.
Your table is messed
up. You open a table, but in mid you just forget about it. you dont
close your td-tags or your table.
your select is messed up. You
have 2 select tags, one of which has even unescaped php-code written
in it.
your JS click-event does not trigger, because you named
it wrong.
Apart from you using mysql_-functions, which are deprecated and will stop working in newer PHP vewrsions, the list goes on...
In short: This code is a complete mess. Erasing this and starting all over with a clear head would be the best option.
To digress a bit, I honestly think that for an app of that size you should be employing some open source PHP packages. Sorry I can't comment yet so had to leave as an answer

How can i use more than 2 form in php and post values?

i want to ask how can i use more than 2 or 3 form in php? i have 2 different form with different id like"formid, formid2" and javascript control "kontrol(), kontrol2()". with this when i change selection the value of the selection appears from different form. But if the forms have same id and control it just appear first form's selection. How can i add and use values more than 2 - 3 forms?
Thanks.
<?php
if(isset($_POST['islem1']))
echo "Value = " . $_POST['islem1'];
if(isset($_POST['islem2']))
echo "Value = " . $_POST['islem2'];
?>
<html>
<head>
<script>
function kontrol(){
document.getElementById("formid").submit();
};
function kontrol2(){
document.getElementById("formid2").submit();
};
</script>
</head>
<body>
<form action="two.php" method="post" id="formid">
<select name="islem1" onchange="kontrol()">
<option value="0">- - - - - -</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<form action="two.php" method="post" id="formid2">
<select name="islem2" onchange="kontrol2()">
<option value="0">- - - - - -</option>
<option value="10">10</option>
<option value="20">20</option>
</select>
</form>
</body>
</html>
i will use this like these picture. it works for first row. all combobox are in a form seperate. if i add an entry and second row is adding too according to loop. so all forms have same ids and controls, after the first row the other combobox doesn't post anything.
http://www.imageupload.co.uk/Bhu --- First Image
http://www.imageupload.co.uk/Bhx --- Second Image
i found a way :). if i use variable, i can append forms as much as i want, it's like that,
<?php
if(isset($_POST['islem1']))
echo "Value = " . $_POST['islem1'];
?>
<html>
<head>
<script>
function kontrol(i){
document.getElementById("formid"+i).submit();
};
</script>
</head>
<body>
<?php for($i=1; $i<=3; $i++){ ?>
<form action="two.php" method="post" id="formid<?php echo $i; ?>">
<select name="islem1" onchange="kontrol(<?php echo $i; ?>)">
<option value="0">- - - - - -</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<?php } ?>
</body>
</html>

Dynamic drop down list using html and php

I'm learning html and php, I have a mysql DB employees where there is a table called Employees_hired, which stores id, name, department and type of contract. I want to make a drop down list of employees who belong to a type of department and a specific contract type. In the code would be something like:
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()"> <!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()"> <!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<?php if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
The question I have is: how to get the selected values ​​from the first drop-down lists (type_hire and department) for use in the query and fill the drop down list of employees. I know how to fill a dropdown list by querying the DB (what I learned in an online course) but I do not know how to take the values ​​from the dropdown lists and use them in my practice. I read that I can use "document.getElementById (" id "). Value" to give that value to the variable in the query, but nowhere explained in detail how. I am new to web programming and my knowledge of Javascript are poor. Can anyone tell me the best way to do this?. It is possible only using html and php or I have to use javascript?
So you have the onchange in there and that's a start. The onchange is referencing a JavaScript function that you don't show. There are a couple quick ways to approach this:
Post the form to itself (as you have chosen) or
use ajax (possibly via jQuery for quickness).
(both of these examples don't address how you are accessing the database)
1)
Using your run function:
<script type="text/javascript">
function run(){
document.getElementById('form1').submit()
}
</script>
Additional PHP:
<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
$value_of_department_list = $_POST['department'];
$value_of_type_hire = $_POST['type_hire'];
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
while($row_list=mysql_fetch_assoc($list))
{
echo "<option value=\"{$row_list['name']}\">{$row_list['name']}</option>";
}
}
else
{
echo "<option>Please choose a department and a type of hire</option>";
}
?>
2)
<script type="text/javascript">
function run(){
$.post('get_employees.php',$('form1').serialize(),function(data){
var html = '';
$.each(data.employees,function(k,emp){
$('select[name="employees"]').append($('<option>', {
value: emp.name,
text: emp.name
}));
.html(html);
},"json");
}
</script>
And get_employees.php would contain something like:
<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
$value_of_department_list = $_POST['department'];
$value_of_type_hire = $_POST['type_hire'];
$return = array();
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
while($row_list=mysql_fetch_assoc($list))
{
$return[]['name'] = $row_list['name'];
}
echo json_encode($return);
}
?>
Note, these are just quickly written examples. A lot more could/should be done here.
Heres a modified jQuery version of your code. (With some cleanup)
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<? $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()">
<!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()">
<!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<? if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--[ I'M GOING TO INCLUDE THE SCRIPT PART DOWN BELOW ]-->
</body>
</html>
Now I cleaned up the tags, and added a hotlink to jQuery using googleapis free cdn. Next is the actual javascript. Btw. DO NOT USE THE MYSQL_* FUNCTIONS IN PHP. They are depreciated. Check out http://php.net/manual/en/mysqlinfo.library.choosing.php for more info on that. On to the scripting...
<script type="text/javascript">
$('#type_hire').change(function() {
var selected = $('#type_hire option:selected'); //This should be the selected object
$.get('DropdownRetrievalScript.php', { 'option': selected.val() }, function(data) {
//Now data is the results from the DropdownRetrievalScript.php
$('select[name="employees"]').html(data);
}
}
</script>
Now I just freehanded that. But I'll try and walk you though it. First we grab the "select" tag that we want to watch (the hashtag means find the element by ID). Then we grab the selected option within that. Next we run a AJAX call to preform a GET on the page "DropdownRetrievalScript.php" which you would create. What that script should do is take the GET variable "option" and run it through the database. Then have it echo out the "option" tags. Our javascript stuff then takes those results and plugs them directly into the select tag with the name attribute of employees.
Remember that AJAX is just like inputing that url into your browser. So the data variable is literally whatever code or text that url would display. It can be Text, HTML, JSON, XML, anything.

Categories

Resources