Populate input with database data on select change - php

I'm an absolute beginner in the HTML/Php/JavaScript world. I'm trying to make this page:
dropdown list with titles of documents
when something is selected, populate input fields below with data from PostgreSQL to allow for update
submit button to update database with corrected values from user.
1 and 3 are ok (already tried this with an insert-only form).
My code looks like this (simplified, without dbconn):
echo "<select name='listedoc' size=1>";
while ($ligne = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo '<option value="'.$ligne['id_doc'].'">'.$ligne['doc_titre']. '</option>';
}
echo "</select>";
The input fields (simplified, there are 4 fields actually):
<p><form name="saisiedoc" method="post" action="docupdins.php"></p>
<table border=0>
<tr><td>Texte</td>
<?php
echo '<td> <textarea name="content" cols="100" rows="30"></textarea> </td>';
?>
</tr><tr>
<td colspan=2>
<input type=submit value="Valider la saisie" name="maj"> </td>
</tr>
</table>
</form>'
Then JQuery script :
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
});
});
</script>
The php to select fields (docsel.php):
<?php
include('../scripts/pgconnect.php');
$iddoc = $_POST['id'];
$sql="SELECT * FROM document where id_doc = $iddoc";
$result = pg_query($db, $sql);
if (!$result) {
echo "ERREUR<br>\n";
exit;}
$row = pg_fetch_row($result);
$doctyp = $row[1];
$doctitre = $row[2];
$docauteur = $row[3];
$doccontent =$row[4];
pg_free_result($result);
pg_close($db);
}
?>
Whatever I do, I can't get back values. I tried value="'.$doctitre'" in the input,
echo $doctitre, to no avail . Is my code logic correct ? Thank you for your help

you are close. the script docsel.php needs to return the data to the html-page.
you have it already setup to receive the data in the callback function
$.post("docsel.php", {id:id},function(data) {
$('textarea[name="content"]').text(data.content);
});
in order to have something in data.content, the php script sends json data:
$result = [];
$result['content'] = $doccontent;
echo json_encode($result);
maybe you need to read the docs on $.post and json_encode... good luck.

There are a couple of things you need to change here.
Firstly, and most importantly your docsel.php script has a gaping security hole. You should never ever ever place unsanitised input e.g. directly from a user, straight into a SQL query because it allows for SQL injection. Essentially, SQL injection allows a malicious user to end the programmers query and submit their own. To get round this you must sanitise any user input - so in this case pass the user input through the function pg_escape_literal() before putting it into your query.
Secondly, your docsel.php script must put out some kind of output for the AJAX request. You can do this by using echo and I would recommend you encode it into JSON. Code example:
$return_vals = array("doctype" => $doctyp, "doctitle" => $doctitre, "docauthor" => $docauteur, "doccontent" => $doccontent);
echo json_encode(array("document" => $return_vals));
Lastly, in your jQuery script, you aren't actually doing anything with the data that is returned from your AJAX post request. Inside the callback function, you need to then add the returned fields to your select dropdown. Code example:
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
//FILL THE DROPDOWN HERE
$(data).each(function(elem) {
$("#dropdown-id").append("<option value='" + elem.doctitle + "'>" + elem.doctitle + "</option>");
});
}, "json");
});
</script>
A mute and pedantic point, but when making requests for content then you should be using GET instead of POST.

Related

Passing the link's text as a value to the next page

I am trying to pass the link's text as a value to the next page so I can use it to search the database for the item and retrieve the information related to the value .I have tried using the POST method but regardless the information is not passed. This is the code I tried .
<form action="DetailedMenu.php" method = "POST" action = "<?php $_PHP_SELF ?>">
<?php
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
echo str_repeat(' ', 4); ?>
<a href="DetailedMenu.php" ><?php echo $array[$i]["Food_Name"];?></a>
<?php echo " " .str_repeat('. ', 25). "€".$array[$i]["Food_Price"]."<br>"; ?>
<input type="hidden" name="name" value="<?php echo $array[$i]["Food_Name"];?>">
<?php
}
}
?>
</form>
You don't need the form.
The easiest way to do what you're trying to do....
In addition to including the text in the content of the link, include it as a query string parameter.
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
I would actually recommend something more like this. I obviously don't know the names of your fields, so I've just taken a guess...
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
You'll be able to access "FoodID" as a parameter within your PHP, just as you would if it had been submitted from a form.
You may be looking for AJAX. AJAX lets you send the form data to a back end PHP file (that can then insert data into a DB, and/or get data from the DB) without refreshing the page.
In fact, when you are using AJAX you don't even need to use a <form> structure -- simple DIVs work just fine. Then you don't need to use event.preventDefault() to suppress the built-in form refresh.
Just build a structure inside a DIV (input fields, labels, etc) and when the user is ready to submit, they can click an ordinary button:
<button id="btnSubmit">Submit</button>
jQuery:
$('#btnSubmit').click(function(){
var fn = $('#firstname').val();
var ln = $('#lastname').val();
$.ajax({
type: 'post',
url: 'ajax_receiver.php',
data: 'fn=' +fn+ '&ln=' +ln,
success: function(d){
if (d.length) alert(d);
}
});
});
ajax_receiver.php:
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
//Do your stuff
Check out this post and especially its examples. Copy them onto your own system and see how they work. It's pretty simple.

update data in the div

I have a problem with updating the data I display from my db. Initially, when the page opens I display the date corresponding to the current date but then the user can change the date by entering it in a text box and when he clicks update all the data displayed should be deleted and the data corresponding to the new date should be displayed. Right now I have a javascript function which deleted all the data in the div when the button is clicked. The div holds the data I want to change. But I don't know how to add new data into the div. I tried to add php code to look up the database for the data in the javascript function but I don't know how to add it to the text box.
function changedate()
{
document.getElementById("label1").innerText=document.getElementById("datepicker").valu e;
document.getElementById("selecteddate").innerText=document.getElementById("datepicker" ).value;
document.getElementById("teammembers").innerHTML = "";//empties the div(teammembers)
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
}
}
?>
}
You can use a combination of jQuery and AJAX to do this. Much simpler than it sounds. To see that this is the right answer for you, just view this example.
In the below example, there are two .PHP files: test86a.php and test86b.php.
The first file, 86A, has a simple selection (dropdown) box and some jQuery code that watches for that selection box to change. To trigger the jQuery code, you could use the jQuery .blur() function to watch for the user to leave the date field, or you could use the jQueryUI API:
$('#date_start').datepicker({
onSelect: function(dateText, instance) {
// Split date_finish into 3 input fields
var arrSplit = dateText.split("-");
$('#date_start-y').val(arrSplit[0]);
$('#date_start-m').val(arrSplit[1]);
$('#date_start-d').val(arrSplit[2]);
// Populate date_start field (adds 14 days and plunks result in date_finish field)
var nextDayDate = $('#date_start').datepicker('getDate', '+14d');
nextDayDate.setDate(nextDayDate.getDate() + 14);
$('#date_finish').datepicker('setDate', nextDayDate);
splitDateStart($("#date_finish").val());
},
onClose: function() {
//$("#date_finish").datepicker("show");
}
});
At any rate, when the jQuery is triggered, an AJAX request is sent to the second file, 86B. This file automatically looks stuff up from the database, gets the answers, creates some formatted HTML content, and echo's it back to the first file. This is all happening through Javascript, initiated on the browser - just like you want.
These two files are an independent, fully working example. Just replace the MYSQL logins and content with your own fieldnames, etc and watch the magic happen.
TEST86A.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "test86b.php", // "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
TEST86B.PHP
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'abcd1234';
$pword = 'verySecret';
$dbname = 'abcd1234_mydb';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
$result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<ul style="list-style-type:disc;">
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</ul><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
Here is a more simple AJAX example and yet another example for you to check out.
In all examples, note how the user supplies the HTML content (whether by typing something or selecting a new date value or choosing a dropdown selection). The user-supplied data is:
1) GRABBED via jQuery: var sel_stud = $('#stSelect').val();
2) then SENT via AJAX to the second script. (The $.ajax({}) stuff)
The second script uses the values it receives to look up the answer, then ECHOES that answer back to the first script: echo $r;
The first script RECEIVES the answer in the AJAX success function, and then (still inside the success function) INJECTS the answer onto the page: $('#LaDIV').html(whatigot);
Please experiment with these simple examples -- the first (simpler) linked example doesn't require a database lookup, so it should run with no changes.
You want to output a literal JS statement with whatever you get back from php, basically:
document.getElementById("teammembers").innerHTML = // notice no erasing, we just
// overwrite it directly with the result
"<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
// so just show it!
echo $email_users; // think about this for a second though
// what are you trying to achieve?
}
}
?>"
This is a vast question, not very specific. Checkout more about AJAX requests - basically from javascript you will have a call to the server that retrieves your data.
This is a snippet from the javascript library jQuery :
$.ajax({
type: "POST",
url: "emails.php",
data: { user: "John" }
}).done(function( msg ) {
$('teammembers').html(msg);
});
hope this will give you a starting point

Load an html table from a mysql database when an onChange event is triggered from a select tag

So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});

Getting a record row in php using javascript

Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/

How to insert PHP values into Javascript?

Javascript:
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option><option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
PHP/HTML:
<script type = "text/javascript" src="js/addinput.js"></script>
<form name="form1" method="POST" action="services.php" onsubmit="return valid()">
<br><br><br><center>
<table class="form" border=1>
<tr>
<td class="head" colspan="2" >Select Vehicle:</td>
</tr>
<tr ></tr>
<tr>
<td colspan="2" class="info">
<div id="dynamicInput">
<br><select name = "vehicle[]" id = "vehicle1">
<option value = "">Vehicle 1</option>';
include_once "vehicledbconnect.php";
$queryveh = mysql_query("SELECT * FROM vehicletbl");
while($fetch_2 = mysql_fetch_array($queryveh)) {
$brand = $fetch_2['vehbrand'];
$name = $fetch_2['vehname'];
echo '<option value = "'.$brand.' '.$name.'">'.$brand.' '.$name.'</option>';
}
echo '</select>';
echo '<input type="button" value="Add another vehicle" onClick="addInput(\'dynamicInput\');"></div>';
Hi. Is it possible to insert PHP values in a javascript? I have a program here that if the customer click the submit button (echo '), a new drop-down form will appear. And I want the drop down form to contain all of the values of the query ($queryveh = mysql_query("SELECT * FROM vehicletbl");). In my default drop-down form, all values of the query are shown. Please help me guys. I am desperate for an answer. Javascript is my weakness. Thanks a lot.
edit:
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option>" + "<?php include 'vehicledbconnect.php'; $queryveh = mysql_query('SELECT * FROM vehicletbl'); while($fetch_2 = mysql_fetch_array($queryveh)) { $brand = $fetch_2['vehbrand']; $name = $fetch_2['vehname']; <option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option> }?>";
Can this be the solution? I've tried but it's not working, if this can be the solution, maybe there's only something wrong with my code here.
The only way to retrieve values from a server from javascript is to use AJAX.
Well you can do it without AJAX if you don't mind a page refresh, but I don't think that is what you want.
I would use a jQuery load function. This is the simplest example I can muster up for you.
You will need to download jQuery (http://docs.jquery.com/Downloading_jQuery) and include it in your html header:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
Then you can make a simple function to call; either as a onclick or onchange depending on your preference.
function reloadDropDown()
{
document.getElementById('dynamicInput').innerHTML = 'Loading ...';
var v_name = document.formname.elementname.value;
$('#dynamicInput').load("dropdownload.php", { vehicle_name : v_name });
}
Let me go through this. dropdownload.php would have your '$queryveh' made drop down code. Javascript basically plonks whatever happens in dropdownload.php on to a div with the id 'dynamicInput' When javascript loads dropdownload.php it sends via POST a variable by the name vehicle_name which you can use as $_POST['vehicle_name'] within dropdownload.php.
So, dropdownload.php may look something like this.
<?php
$queryveh = mysql_query("SELECT * FROM vehicletbl WHERE vehname = '{$_POST['vehicle_name']}'");
// collect the data and put it in to an Array I like to do this so I can check the array to make sure it has something in it if not return an error message but I will skip that for the purpose of this explanation.
while($ucRow = mysql_fetch_array($queryveh, MYSQL_ASSOC)) array_push($resultsArray, $ucRow);
?>
<select name = "vehicle[]" id = "vehicle1">
<?php
foreach ($resultsArray as $fetch_row){
?>
<option value = "<?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname'].'; ?>"><?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname']; ?></option>
<?php } ?>
</select>
?>
I'm not entirely certain on the end result you are after but that is a basic jQuery ajax call. If you can grasp that, you are half way to a truly dynamic web page / app with some further practice with this area. Hope that gives you a direction to go in :)
JavaScript gets evaluated on the client ..so like Html ..so it is to be used the same way.
-> yes, you just use php in your javascript as long as its defined to be evaluated by php first (usually within a .php file)
edit:
just to clarify, if you want to get values within javascript from the server by php.. you need to have a look at what danishgoel said: Ajax (Asynchronous JavaScript) ..see - since Rikudo Sennin disrespected the link, another http://en.wikipedia.org/wiki/XMLHttpRequest ..or even better have a look at a javascript framework that does most of the stuff for you (f.e. jQuery)

Categories