pass the value inside php while loop to javascript using button onclick - php

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>

Related

Populating 56 input fields in PHP / mySQL / JQuery environoment

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
}
?>

Updating hidden input depending on what user has checked

I've created a test system that has multiple steps (using jquery) allowing users to check checkboxes to select their answers, with a summary page and a final submission button... all within a form. I now want to create the scoring system.
1) Firstly this is the code (within a loop) that grabs the answers from Wordpress for each question:
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo $row['answer']; ?>" />
2) In Wordpress next to each answer is a dropdown with a yes or no option to mark whether the answer is right or wrong. This is output in the following way:
<?php $row['correct']; ?>
3) Each correct answer the user checks should be worth 1 point. The passmark is determined by the field:
<?php the_field('pass_mark'); ?>
4) I want it to update a hidden field with the score as the user checks the correct answer:
<input type="hidden" value="<?php echo $score; ?>" name="test-score" />
How can I update the hidden field with the user score as the user is checking the correct answer? I'm not sure what to try with this to even give it a go first!
Ok, everyones spotted a big hole in this. I'm completely open to doing it a hidden way so people can't check out the source. The type of user this is targeted at wouldn't have a clue how to look at the source but might as well do it the right way to start with!
The whole test is within a form so could it only update the hidden field on submit?
I still need some examples of how to do it.
In my opinion you should use sessions for that purpose, because any browser output may be saved and viewed in ANY text editor. This is not right purpose oh hidden input elements. You use hidden inputs when you need to submit something automatically, but never use it when processing some important data.
Mapping your questions and answers via id will allow you not to reveal real answers and scores in HTML.
Just a very simple example how to do that:
<?php
$questions = array(
125 => array("text"=>"2x2?", "answer"=>"4", 'points'=>3),
145 => array("text"=>"5x6?", "answer"=>"30", 'points'=>2),
);
?>
<form method="post">
<?php foreach ($questions as $id => $question): ?>
<div><?php echo $question['text'] ; ?></div>
<input type="text" name="question<?php echo $id ; ?>"/>
<?php endforeach ; ?>
<input type="submit" value="Submit"/>
</form>
/* In submission script */
<?php
if (isset($_POST['submit'])){
foreach($questions as $id => $question){
if (isset($_POST["question{$id}"])){
$answer = $_POST["question{$id}"] ;
if ($answer === $question['answer']){
$_SESSION['score'] += $question['points'] ;
}
}
}
}
Spokey is right - the user would be able to cheat if your score it on the client side like using the method you suggested.
Instead, either user a JQuery $.post call to post each answer and then store the score in a PHP Session. Or just wait until the entire form is submitted and evaluate the score of the form as a whole on the server side.
* Update *
You have to submit the form to a script that can evaluate the form. So say it gets submitted to myForm.php
In myForm.php, get the post vars:
$correct_answers = $however_you_get_your_correct_answers();
//Assuming $correct_answers is a associative array with the same keys being used in post -
$results = array();
if($_POST){
foreach ($_POST as $key=>$value) {
if ($_POST[$key] == $correct_answers[$key]){
$results[$key] = 'correct';
}
else $results[$key] = 'incorrect';
}
}
This is untested, but it should work.

check if checkbox is checked in php

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
}
?>

header('Location: ) in php switch to execute url with onclick function

To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>

Javascript mysql interface?

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

Categories