I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed
Related
I am trying to multiply to fields together to obtain a total in PHP form.
<label for="190_mnth2"></label>
<div align="center">
<input name="190_mnth" type="text" id="190_mnth2" value="10" size="5" />
</div></td>
<td><div align="center">
<label for="190_rate"></label>
<input name="190_rate" type="text" id="190_rate" value="190.00" size="10" />
</div></td>
<td><div align="center">
<input name="total_190" type="text" id="total_190" value=<? echo '190_mnth2' * '190_rate' ?> size="10" />
The above is my current code but the answer is totally wrong it gives me 36100 What is wrong with my formula if anyone can assist?
First of all you cannot calculate the total like that, it's not Javascript, you need a form with a get/post request which will send a request to the server, server will process and throw the calculated value back to the user.. so wrap the fields around forms, set your method to post(preferred) and than you can write your PHP code like
<?php
if(isset($_POST['submit_button_name'])) { //Use $_GET if it's a GET request
//Save the values in variable
$mnth_190 = $_POST['190_mnth'];
$rate_190 = $_POST['190_rate'];
//Calculate here
$total = $mnth_190 * $rate_190;
/* Now you can use $total either to echo straight in your page,
or inside another input field */
}
?>
Also make sure you validate the data before the form is posted and is calculated, check whether the user input doesn't have string or any other special character.
The purpose of PHP is to generate HTML to display, not to update the HTML of the current page. You can create a POST request that submits your data for display on another page. If you want to dynamically update the total on the current page, you should use Javascript or another front end language.
<? echo '190_mnth2' * '190_rate' ?>
You're attempting to multiply two strings, which will probably be converted by PHP as 190 * 190.
In order to get this to work, you're going to have to do it in two separate steps (with PHP anyway). Because PHP is a server side language, you'll have to $_POST[''], or submit these two values as part of the query string and use $_GET[''] to calculate.
If you don't want to do it this way, then I'd suggest looking at some JavaScript to handle it instead.
I'm going to take a shot at doing something like this, as an example.
$190_mnth2 = 10;
$190_rate = 190;
$total = $190_mnth2 * $190_rate;
then using: value=<? echo '$total'; ?>
I'm doing an android app in eclipse (using phonegap + json + php) and i have some troubles... I really don't know how to ...
I have a php file (consulta.php) that generates the json, whichc is locate in my server (192.168.1.200/test/consulta.php:
header('content-type: application/json');
mysql_connect("localhost","jhonatan","jsandoval");
mysql_select_db("tesis");
$array = array();
$query = mysql_query("SELECT * FROM GRIFO");
while($fila = mysql_fetch_object($query)){
//echo $fila['id'] . " " . $fila['grifo'] . " " . $fila['distrito'] . "<br/>";
$array[] = array('id'=>$fila->id,
'grifo'=>$fila->grifo,
'distrito'=>$fila->distrito,
'latitud'=>$fila->latitud,
'longitud'=>$fila->longitud);
}
echo json_encode($array);
So, in my index.html (from android app, phonegap in eclipse) , have a form wich gets 2 selects (HTML).
<form id="combustibleForm" method="get">
<select id="combustibleSelect" name="combustibleSelect" data-theme="a">
<option value="gnv" >Gas Natural Vehicular</option>
<option value="glp" >Gas Licuado de PetrĂ³leo</option>
</select>
<br/>
<select id="distritoSelect" name="distritoSelect" data-theme="a">
<option value="SJL" >San Juan de Lurigancho</option>
<option value="Miraflores" >Miraflores</option>
<option value="Chorrillos" >Chorrillos</option>
<option value="Surquillo" >Surquillo</option>
</select>
<br/>
<input type="submit" data-role="button" id="continuarBtn" value="Continuar.." />
</form>
I must pass the values of these selects to the php file above and generate a json from there:
// GET THE VALUE OF THE SELECTS ... I don't know if this is correct? :S
$tipo = $_GET['tipo'];
$distrito = $_GET['distrito'];
...
...
$query = mysql_query("SELECT * FROM GRIFO WHERE (tipo='$tipo' and distrito='$distrio')");
...
...
// Generate json
echo json_encode($array);
This is what i have to do:
After that... i have another html page (mapa.html, in eclipse), that get the json from the php (wtf!? ) ... HOW TO DO THIS? :S ..
Also, when i Click the submit form (in index.html), must redirect to mapa.html , to get the json....
I really don't know and don't have any ideas to do this big problem...
Can someone please help me?...
Sorry for bad english
Your form element in the HTML has no action attribute. This is where the browser will send the request when the user clicks on submit. So, if you want to send the request to your PHP script you will need you need to set that in the action attribute of your form.
Assuming consulta.php is located in the same directory as that of your HTML page...
<form id="combustibleForm" method="get" action="consulta.php">
<select id="combustibleSelect" name="combustibleSelect" data-theme="a">
<option value="gnv" >Gas Natural Vehicular</option>
<option value="glp" >Gas Licuado de PetrĂ³leo</option>
</select>
<br/>
<select id="distritoSelect" name="distritoSelect" data-theme="a">
<option value="SJL" >San Juan de Lurigancho</option>
<option value="Miraflores" >Miraflores</option>
<option value="Chorrillos" >Chorrillos</option>
<option value="Surquillo" >Surquillo</option>
</select>
<br/>
<input type="submit" data-role="button" id="continuarBtn" value="Continuar.." />
</form>
Now, when this form is submitted the request will be directed to your PHP script, which will generate the JSON.
As for getting the values sent by the form in your PHP you need to use the name attributes you defined for those SELECT elements.
In your case that is combustibleSelect and distritoSelect.
$_GET['combustibleSelect']; // This will be the value of the 1st SELECT box
$_GET['distritoSelect']; // This will be the value of the 2nd SELECT box
Please do not use the old ext/mysql API to interface with your database as it has been deprecated and may be removed in future versions of PHP. Consider using the newer PDO or MySQLi APIs instead to interface with your MySQL databse in PHP.
As for getting the data into javascript, you want to use ajax to make an XHR request to your PHP script. This will allow you to populate whatever you want to populate in the DOM of your HTML with javascript, by asking javascript to go out and make a request to your PHP script in the background and then hand you back the JSON to do with as you please without the user ever having to leave the page.
You could pass the json as an url_encoded string appended to the url or a hidden field. if you need to communicate beteween pages, have the generating page echo the json into a hidden field. You could also do ajax or curl request for the json
Something like (in index.html)
<?php $data = url_encode(json_encode($array)) ?>
<form action="mapa.html?data=<?php echo $data?>" method="get">
...
</form>
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>
This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}
I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>