I have a form that takes 56 separate inputs and stores them across 6 tables in mySQL indexed by a unique ID generated when the form is generated. That said, I have an edit mode that passes the UID to the form via the GET method (ie. index.php?editUID=5552d631220810).
My question is, what is the best way to assign all the values to each of the 56 inputs? Currently I am using PHP to process a script line to assign each of the values which are set in the database like this:
<script type="text/javascript" language="javascript">
$(function() {
$("#salesPrice").val("7500000");
});
</script>
But this seems like a cumbersome / not very efficient way to assign my values to their respective fields. Is there a cleaner way to do this? Also, if this is helpful, the names of my mySQL fields are the same as my inputs (ie. salesPrice is the name of the column in my database and the name of the index of my input field if that is useful).
Thanks for any ideas.
You could loop through the column names and the variables and output them to both the HTML and the Javascript
<?php
//MYSQL query goes here
for($results as $data) {
?>
$("#<?php echo $data->name; ?>").val("<?php echo $data->value; ?>");
<?php
}
?>
Or simply just use it with HTML and no javascript
<?php
//MYSQL query goes here
for($results as $data) {
?>
<input type="text" name="<?php echo $data->name; ?>" value="<?php echo $data->value; ?>">
<?php
}
?>
Related
I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.
I am trying to get the values of div elements using Simple HTML Dom Parser. Its working fine for only hard coded values. Here is the hard coded stuff.
<table>
<tr><td class='none'><div class='drag' id='d1'>1</div></td></tr>
<tr><td class='none'><div class='drag' id='d2'>2</div></td></tr>
<tr><td class='none'><div class='drag' id='d3'>3</div></td></tr>
Apart from these constant values i need to get the other id values which are displayed based on the selection from the drop-down menu.
<form method="post" name="order" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select id='test' name='test'>
<option value="">Please Select</option>
<option value='test1'>Test1</option>
<option value='test2'>Test2</option>
</select>
</form>
After the selection they click the continue button which redirects them to the same page and here is my script that displays id's from database.
<?php
$i=4;
if ($_SERVER['REQUEST_METHOD']=="POST")
{
$query = mysql_query("select * from test_demo where test_requested='$_POST[test]'");
while($result=mysql_fetch_array($query))
{
echo "<tr><td class='none'><div class='drag' id='d$i'>". $result['oid'] ."</div></td></tr>";
$i++;
}
}
echo "</table>"
?>
Now i want to get the order id's 1,2,3 and remaining id's retrieved from the database. In order to get these values i am using a Values button on click goes to retrieve.php file.
In retrieve.php file i am using Simple html dom parser to get the values. Here is the code.
<?php
include_once('simple_html_dom.php');
//test.php contains my hard coded html and php code
$html = file_get_html('test.php');
$temp = '1';
//usig div name we are retrieving the values
foreach($html->find('div#d5') as $e)
$result[]= $e->innertext;
print_r($result);
?>
In the place of d5 if i could mention d1 or d2 or d3. I could able to get the values 1,2,3 respectively. But i am unable to get the order id values which are retrieved from the database. The div ids for these elements starts from d4 and so on. Where could be I am going wrong?
There are several issues.
First, PHP scripts aren't run if you access them as ordinary files. You need to change the URL to go through the server:
$html = file_get_html('http://localhost/path/to/test.php');
Second, you need to provide the value of the test parameter in the URL, so it should be:
$html = file_get_html('http://localhost/path/to/test.php?test=test1');
Third, in test.php you need to access the parameter using $_GET, not $_POST, when it's accessed this way:
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$test = mysql_real_escape_string($_GET['test']);
$query = mysql_query("select * from test_demo where test_requested='$test'");
...
}
So this is what I have - A javascript onclick event that will parse json from my MySQL database data and display it when someone clicks on a seat.
var jsonData = <?php echo json_encode($array); ?>;
function displayInfoForDiv(i){
document.getElementById('fname').innerHTML = jsonData[i].first_name;
document.getElementById('lname').innerHTML = jsonData[i].last_name;
}
Output
<?php while ($row = mysql_fetch_array($sql)){ ?>
<p><span id="fname"><?php echo $row['first_name']; ?></span></p>
<p><span id="lname"><?php echo $row['last_name']; ?></span></p>
<?php } ?>
The PHP is for my search box when you try to look up a name - I'm using this
$sql = mysql_query("select * from people where first_name like '%$term%' OR last_name LIKE '%$term2%'");
So the problem I'm having is when I conduct a search for Matt, more then one result will show up. Say:
Matt
Hasselbeck
Matt
Hew
But if I use the onclick event and click on joe's seat, it will display like this:
Joe
Frill
Matt
Hew
So the problem is that the search results will remain when I trigger the onClick event but the first one will change.
My question is, is there a way when I click on a seat to clear the search results and only display the one but when I conduct a search to display the similar names.
I'm using the PHP and JS to call the same data because, the JS only has a range of floor, while the php is grabbing everything from the database.
Hopefully this is clear and thank you for any input.
You Have Two Issues going on here.
You are using the same value for the id attribute multiple times.
Your result setup is logically flawed
Solution to Issue 1
Change id attribute to class attribute
When you use document.getElementById in javascript it returns the first element with that id.
Which means that if you have multiple ids with the same value only the first element will be selected. So your function should be changed to the following
function displayInfoForDiv(i){
document.getElementsByClassName('fname')[i].innerHTML = jsonData[i].first_name;
document.getElementsByClassName('lname')[i].innerHTML = jsonData[i].last_name;
}
Solution to Issue 2
Use template for results
Wrap all results in a div tag
By wrapping results into a div tag you will be able to clear results by clearing the html for that div tag.
<div id='Results'>
<?php while ($row = mysql_fetch_array($sql)){ ?>
<p><span class="fname"><?php echo $row['first_name']; ?></span></p>
<p><span class="lname"><?php echo $row['last_name']; ?></span></p>
<?php } ?>
</div>
<script>
function clearResults()
{
document.getElementById('Results').innerHTML='';
}
</script>
To use a template for results I would recommend underscore.js
So a template for your needs would look like the following:
<script id='result-template' type="text/x-jquery-tmpl">
<p><span class="fname">${first_name}</span></p>
<p><span class="lname">${last_name}</span></p>
</script>
And to utilize the template you would do the following:
The code below assumes you have included underscore.js
function LoadResults(jsonData)
{
_.templateSettings = {
interpolate: /\$\{(.+?)\}/g
};
var output='',
resultDiv=document.getElementById('Results');
template= _.template(
document.getElementById('result-template').innerHTML
);
clearResults();
for(x in jsonData)
{
resultDiv.innerHTML+=template(jsonData[x]);
}
}
I have a huge form and in part of the form I want to insert some value to database using js. I might not be clear about how to present the question but here my needs are:
suppose, I have two tables in database table1, table2. In a html form:
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1){ ?>
<option value"<?=$row['name']?>" name="option1"><?=$row['name']?></option>
<?php } ?>
</select>
<input type="file" name="file">
<input type="button" name="button" onclick="submit_form(true,'');">
Now, I want to pass the $row['name'] value to submit_form() function in javascript. The javascript code will check the value and return it to the form to submit it. My question is since the $row['name'] from table1 is inside the while loop, I cannot pass the value to javascript. If the form was small I could have done using submit button and check $_POST('submit') type. I want to insert the $row['name'] in this form to table2 as file name associated with the name.
As i understand you want to pass selected value from form to submit_form() function?
function submit_form(param1, param2){
var passedValue = document.getElementById('tab1').value;
// here is your old submit_form() function. passedValue contains
// your selected $row['name']
}
#Jhilke Dai, First of all your php code is little buggy, '=' sign must be in html not in php the correct code is
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1) { ?>
<option value="<? echo $row['name'] ?>" name="option1"><? echo $row['name'] ?></option>
<?php } ?>
</select>
<input type="file" name="file"> <input type="button" name="button" onclick="submit_form(true,'')">
You can use generic functions or even jQuery itenerations, to fetch form values
See the similar question answer : Get selected value/text from Select on change
function getDomValueByID( id ) {
return document.getElementById(id).value;
}
function submit_form( a, b ) {
var formValue = getDomValueByID( 'tab1' );
//OR
var jQueryFormValue = jQuery( "#tab1" ).val();
//Do what u want here.
}
In fact several consider it a very bad idea to pass the option data over via javaScript, if its already generated on page for the following reasons
Duplicate data, wasted bandwith.
Less portable code, non-OOP.
Harder to maintain, changes in your php code, requires changes in your javaScript code.
Also if you are really interested (this practice is sometimes frowned on). You can use the following as PHP code somewhere in the header. To pass PHP variables to JavaScript. However there are lots of better ways to do this, from JSONS to XML.
<?php optList = ['one', 'two', 'three']; ?>
<script type="text/javascript">
//Window represents the global variable space, and doing this is really bad practice as listed above.
window.optionList = [ <?php echo( implode(' , ', optList) );?> ];
</script>
Hi i want to get changed text value from JQuery but i can't select edit text with JQUERY because edit texts generated from php while loop that this php code query on database and get value of edit texts and in my program i have edit button for every edit texts and when the user changed value of edit text i select new value and when user click edit button send this value from get method to another php page with jquery $.ajax function and send new value to that php code with ajax.But i don't know how can i select edit text that it's value changed because i don't know id of that edit text!.And when i set one id for every edit text i only get first edit text value from $("#id").change().val();.I use below code but it doesn't work.I am beginner in java script and don't know how fix this problem!.
var testAnswer;
function setNewTestAnswer(id){
testAnswer = $("#id").val();
}
function sendToEdit(pID,phID,thDate,type){
var info = 'pId='+pID+'&phId='+phID+'&testAnswer='+testAnswer+'&thDate='+thDate+'&type='+type;
}
2nd function use testAnswer that user changed in edit text.
php code
<?php
include 'Connect.php';
if(match($_POST['pId'], "/^[\d]+$/") ){
$pId = $_POST['pId'];
$result = mysql_query("select pName, pID, phName, phID, testHistoryDate, type, testAnswer from patient join reception using(pID) join physician using(phID) join testHistory using(rID) join test using(tID) where pID = $pId",$connection);
}
else
die("Insert true value");
while($row=mysql_fetch_array($result)){
echo "<tr><td>";
echo $row["pName"].'</td>';
echo '<td>'.$row["phName"].'</td>';
echo '<td>'.$row["testHistoryDate"].'</td>';
echo '<td>'.$row["type"].'</td>';
$type = $row['type'];
$testHistoryDate = $row['testHistoryDate'];
?>
<td>
<span id='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer' value='<?php echo $row['testAnswer']; ?>' />
</span>
</td>
<td>
<input type='submit' value='Edit' name='edit' id='edit' onclick="sendToEdit('<?php echo $row['pID'] ?>','<?php echo $row['phID'] ?>', '<?php echo $row['testHistoryDate'] ?>', '<?php echo $row['type'] ?>')" />
</td>
</tr>
<?php } ?>
tl;dr
So it isn't completely clear what you are trying to do here but I can explain a couple things that might help.
in html ids should be unique. You dont have to obey this rule for your page to work but you have found one of the consequences if breaking it: jQuery will only find the first one.
it is a good idea to base html ids on some unique attribute of your data eg the table row id.
You can get more creative with your jQuery selectors for example
$('input[type="text"]') // gets all the text inputs
Use classes. When you want to be able to easily select all of a group of html elements you should give them all the same class name. one element can have multiple class names and many elements can share a class name. you can then select them by class name using jquery like this:
$('.myclassname')
I think you need to change your php to look more like this:
<span class='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer-<?php echo $row['id'] ?>' value='<?php echo $row['testAnswer']; ?>' />
</span>
Since you're creating elements inside a php loop, you must be sure that every element has a unique id (or no id at all). You can use either an incrementing index, or some unique value in your array. At first glance, seems that $row['pID'] is a good candidate:
<input id='edit_<?php $row['pID'] ?>' type='submit' value='Edit' ... />
After that you should be able to target individual elements.