PHP form validate with javascript - php

I've been at this the whole day. First I tried to validate my form in php but finally gave up. Now I'm trying to validate the form with JavaScript. It works but since I don't know JavaScript at all and have limited knowledge of PHP I really need help please. It is a test and I want to validate that each question has been answered. The field name in the form = php variable/array, can't get this to work in the javascirpt
var x=document.forms["myForm"]["question_{$q_nr}"].value;
. If I just use a text field name it works fine.
The form
<html>
<head>
<?php
session_start();
?>
<script type="text/javascript" src="counter.js"></script>
<script language="JavaScript">
<!--
function validateForm()
{
var x=document.forms["myForm"]["question_{$q_nr}"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
//-->
</script>
</head>
<body>
<?php
if ($_SESSION['auth']) {
$tid = $_GET['tid'];
echo "<span id='counter'></span>";
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY q_nr";
$result1=mysql_query($sql1);
echo "<form name='myForm' action='http://localhost/index.php?option=com_content&view=article&id=51' onsubmit='return validateForm()' method='post'>";
while($row1 = mysql_fetch_array($result1))
{
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
echo "<P><strong>$q_nr $question</strong><BR>";
echo "<img src='images/tests/$pic'>";
echo "<BR>";
echo "<BR>";
echo "</p>";
if ($q_type != 'mr') {
if($option1!="") {
echo "<input type='radio' name='question_{$q_nr}' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='radio' name='question_{$q_nr}' value='B'>$option2<BR>";
} else {
echo ''; }
} else { // else if not <> mr
if($option1!="") {
echo "<input type='checkbox' name='question_{$q_nr}[]' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='checkbox' name='question_{$q_nr}[]' value='B'>$option2<BR>";
} else {
echo ''; }
} //if q_type <> mr
} //while row1
echo "First name: <input type='text' name='fname'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
} //else if now > testend
} //if ses auth
?>

why do you think so complicated ?
just use unique ID's for each label, input field, etc ... and check for the innerHTML or value stored; and also you can change the values whenever you want;
btw, your code is messy;
write your code like this:
zone 1: all the js goes here
zone 2: all the html goes here
zone 1:
<script language="text/JavaScript">
//alljs code here
function validate()
{
if( document.getElementById('unique_2').value == null ) document.getElementById('unique_3').innerHTML = 'error1';
if(document.getElementById('unique_4').value == null ) document.getElementById('unique_6').innerHTML = 'error 2';
}
</script>
zone 2:
<form onsubmit="validate()">
all html label and fields go here, like:
<label id="unique_1">label text</label>
<input type="text" id="unique_2" value="" />
<label id="unique_3"></label> this is for the error message
<label id="unique_4">label text</label>
<input type="text" id="unique_5" value="" />
<label id="unique_6"></label> this is for the error message
</form>

This is simple JQuery validation.
I think you must have both validation if you want to be secured...
p.s. Just add 'required' in class of input if you want to be required...

Well for one thing -- validating on the server side is the way to go.
If you just validate on the client side, it can be futzed with (a lot)

Related

PHP - Populate form fields based upon <select> <option> value

I am trying to populate a form based upon the option selected in the <select>. The eventTitle field in the DB has corresponding fields located at the bottom of the code. If I select option 1, I want the form to be populated with the fields corresponding to option 1. I am not sure the best way to do this. Thanks in advance.
Also, if you have any other recommendations on things I should do differently, like if I am coding a bad practice, please advise. Thanks!
require_once "functions.php";
//this creates a reference to the connection which is in the functions.php file
$connection = getConnection();
//so far this gets all the event titles and echos out a drop down list with them in. yay
$sqlPopulateQuery = "SELECT eventTitle, eventID from NE_events";
$queryResult = $connection->query($sqlPopulateQuery);
echo "Event Title: <select name='eventTitle'>";
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}'>{$record->eventTitle}</option>";
}
echo "</select>";
//if a specific event is selected
//get eventID from database
//populate textfield with eventID
//echo "Event ID: <input type='text' ' name='eventID' readonly><br>";
//echo "Venue ID: <input type='text' name='venueID'><br>";
//echo "Category ID: <input type='text' name='categoryID'><br>";
//echo "Start Date: <input type='date' name='eventStartDate'><br>";
//echo "End Date: <input type='date' name='eventEndDate'><br>";
//echo "Price: <input type='text' name='eventPrice'><br>";
?>```
You can achieve your requirement with either plain javascipt or with Jquery library, below I have listed each of the methods
1.Using javascript solution
<?php
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}' onChange="popuplateData({$record->eventTitle})">{$record->eventTitle}</option>";
}
echo "Event ID: <input type='text' id='eventID' name='eventID' readonly><br>";
?>
<script>
function popuplateData(option){
if(option === 'title1'){ // For each option you can modify based on value
document.getElementById('eventID').value = 'event 1';
//More fields goes here
}
}
</script>
2.Using Jquery solution
<?php
echo "Event Title: <select name='eventTitle' id='eventTitle'>";
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}'>{$record->eventTitle}</option>";
}
echo "</select>";
echo "Event ID: <input type='text' id='eventID' name='eventID' readonly><br>";
?>
<script>
jQuery(document).ready(function($) {
$("#eventTitle").change(function(){
var optionVal = $(this).val();
if(optionVal != ''){
if(optionVal === 'title1'){// For each option you can modify based on value
$('#eventID').val('event 1');
//More fields goes here
}
}
});
});
</script>

How do I pass value from Jquery to PHP ? HTML is a hidden input form field

I have a form:
<form action="post.php" method="POST">
<p class="select1">Northern Cape</p>
<p class="select1">Eastern Cape</p>
<p class="select2" >New Goods</p>
<p class="select2" >Used Goods</p>
<input id="submt" type="submit" name="submit" value="Submit">
</form>
JQUERY .... appends input/value to the selected items:
$(document).ready(function() {
$('.select1').click(function() {
if ($(this).text() == "Northern Cape"){
$(this).append("<input id='firstloc' type='hidden' name='province'
value='Northern Cape' />");
$("#firstloc").val('Northern Cape');
}; // end of if statement
if ($(this).text() == "Eastern Cape"){
$(this).append("<input id='firstloc' type='hidden' name='province'
value='Eastern Cape' />");
$("#firstloc").val('Eastern Cape');
}; // end of if statement
}); // end of click function
}); // end of document ready
$(document).ready(function() {
$('.select2').click(function() {
if ($(this).text() == "New Goods"){
$(this).append("<input id='category' type='hidden' name='cat'
value='New Goods' />");
$(this).val('New Goods');
};
if ($(this).text() == "Used Goods"){
$(this).append("<input id='category' type='hidden' name='cat'
value='Used Goods' />");
$("#category").val('Used Goods');
};
});
});
How do I pass the values to PHP ie. first value Province second value Category?
<?php
$province = $_POST['province'];
$category = $_POST['cat'];
echo $province;
echo $category;
?>
I get a message Undefined index:cat when passing to PHP.
User must select 2 items and values must be passed to PHP,I do not want to use a drop down menu with "options"
Here is the solution.
You made a several mistakes in your code.
You are using ; after if statement
You didnot close $document.ready tag properly
You have to check in your post.php if data posted or not
And you only appends input type hidden you weren't remove it.
post.php
<?php
$province = '';
$category = '';
if(isset($_POST['province'])):
$province = $_POST['province'];
endif;
if(isset($_POST['cat'])):
$category = $_POST['cat'];
endif;
echo $province;
echo $category;
?>
$(document).ready(function() {
$('.select1').click(function() {
if ($(this).text() == "Northern Cape"){
$("#firstloc").remove();
$(this).append("<input id='firstloc' type='hidden' name='province' value='Northern Cape' />");
} // end of if statement
if ($(this).text() == "Eastern Cape"){
$("#firstloc").remove();
$(this).append("<input id='firstloc' type='hidden' name='province' value='Eastern Cape' />");
} // end of if statement
});
$('.select2').click(function() {
if ($(this).text() == "New Goods"){
$("#category").remove();
$(this).append("<input id='category' type='hidden' name='cat' value='New Goods' />");
}
if ($(this).text() == "Used Goods"){
$("#category").remove();
$(this).append("<input id='category' type='hidden' name='cat' value='Used Goods' />");
}
}); // end of click function
}); // end of document ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<form action="post.php" method="POST">
<p class="select1">Northern Cape</p>
<p class="select1">Eastern Cape</p>
<p class="select2" >New Goods</p>
<p class="select2" >Used Goods</p>
<input id="submt" type="submit" name="submit" value="Submit">
</form>
</html>
Try this code hope it will helps you.
PHP does not set $_POST for all post operations, for example for text/xml:
Try adding adding application/x-www-form-urlencoded or multipart/form-data to your form just to make sure.
<form action="post.php" method="POST" enctype="multipart/form-data">
Also make sure you don't have broken HTML that is causing your form tag to be close prematurely. Verify what is getting posted and the content type using web developer tools.
You should also be using isset to check the existence of a variable:
if (isset($_POST["cat"])) {
$cat = $_POST["cat"];
echo $cat;
echo " is the category";
}
else
{
$cat = null;
echo "no category supplied";
}

Put words from mysql db in order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I would like to make a "put words in order" php script from data stored in mysql but I have no clue in how to start. Could someone help me? I just need to separate each word in order to the person could select the word, not type.
Like any of this:
http://a4esl.org/q/j/ck/wo-01.html
http://baladre.info/english/sedaviwebfront/pastSimporder1.htm
Thank you for the attention and help!
#chris85 I'm new in this php programing thing.
I could kind of make this script, sorry maybe for the bad "programming" but it is working:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "questions";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST["topic"])) {
$topic = $_POST["topic"];
$subjectid = $_POST["subjectid"];
} else {
$row['topicid'] = $_GET["id"];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Questions</title>
</head>
<body>
Question: <br><br>
<form action="questions.php" method="post">
<?
if (isset($_POST["topic"])) {
$sql = "SELECT topicid FROM topic WHERE topic=\"$topic\" AND subjectid=\"$subjectid\"";
$id = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($id);
}
$sql2 = "SELECT * FROM question WHERE topicid=\"$row[topicid]\" ORDER BY rand() LIMIT 1";
$result = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_assoc($result);
echo "<font size=\"6\"><b>".$row2['question']."</b></font>"; ?>
</form>
<?
if ($row2['check'] == "0"){
echo "Level 0: Try to memorize and type the answer according with the text bellow";
} elseif ($row2['check'] == "1"){
echo "Level 1: Try to type the answer by looking the begining of it, if you can't remember go back to level 1 by clicking in \"I got it wrong!\"";
}elseif ($row2['check'] == "2"){
echo "Level 2: Try to type the answer without looking at any part of it, if you forget a simple part you can give a little look";
}elseif ($row2['check'] == "3"){
echo "Level 3: Type the answer without realy looking at any part of it, anyways you still having the color hint";
}elseif ($row2['check'] == "4"){
echo "Level 4: Type the answer without any hint. Now when you will just be able the hit the button \"I got it right!\" when the answer be completely right, if you want you may go back to <b>level 3</b> by presing \"I got ir wrong!\"";
}elseif ($row2['check'] == "5"){
echo "Level 5: Congrats: you got it, fell free to repeat as many times you want! Now you don't need to type exactly as the answer, for it you will have the buttons bellow to check if your answer is right. Just be honest! =D";
}
?>
<!-- start -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<?
echo "<textarea name=\"password\" id=\"password\" hidden='1'>" . $row2['answer']. "</textarea>";
?>
</label>
<br>
<label>Answer: <br />
<textarea name="confirm_password" id="confirm_password" style="width: 80%; height: 100px; font-size:20px" /></textarea> <span id='message'></span>
<? if ($row2['check'] <= "3"){
echo "<script>
$('#confirm_password, #password').on('input', function(e){
changeColor($('#confirm_password').val(), $('#password').val());
});
function changeColor(c, p){
var color;
if(c === p){
color = 'green';
} else if(p.indexOf(c) === 0 && c != ''){
color = 'yellow';
} else {
color = 'red';
}
$('#confirm_password').css('background-color', color);
}
</script>"; }
if ($row2['check'] == "4"){
echo "<script>
$('#confirm_password, #password').on('input', function(e){
changeColor($('#confirm_password').val(), $('#password').val());
});
function changeColor(c, p){
var color;
if(c === p){
color = 'visible';
} else {
color = 'hidden';
}
$('#certo').css('visibility', color);
}
</script>"; }
?>
<!-- end --><br><br>
<table width="80%" border="0">
<tbody>
<tr>
<? echo "<td width=\"33.3%\"><form action=\"right.php\" method=\"post\"><input type=\"hidden\" name=\"topicid\" value=\"" . $row['topicid']. "\"></input><input name=\"questionid\" type=\"hidden\" value=\"" . $row2['questionid']. "\"></input>";
if ($row2['check'] == "5"){ echo "<input type=\"hidden\" name=\"ncomp\" value=\"1\"></input>"; }
echo"<input name=\"certo\" id=\"certo\" type=\"submit\" value=\"I got it Right!\"";
if ($row2['check'] == "4"){ echo "style=\"width:500px; visibility:hidden\""; } else { echo "style=\"width:500px\""; }
echo"></form></td>";
echo "<td align=\"center\" width=\"33.3%\"><a align=\"center\" href='questions.php?id=".$row['topicid']."'>Skip</a></td>";
echo " <td width=\"33.3%\"><form action=\"wrong.php\" method=\"post\"><input type=\"hidden\" name=\"topicid\" value=\"" . $row['topicid']. "\"></input><input name=\"questionid\" type=\"hidden\" value=\"" . $row2['questionid']. "\"></input><input type=\"submit\" value=\"I got it Wrong!\" style=\"width:500px;\"></form></td>"; ?> </div>
</tr>
</tbody>
</table>
<?
echo "<br><br>
<form action=\"aquestion.php\" method=\"post\">";
echo "<input type=\"hidden\" name=\"topicid\" value=\"" . $row['topicid']. "\"></input>"; ?>
<input type="submit" value="New Text Question"></input>
</form>
<br><br><br>
Show answer:
<script type="text/javascript">
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.visibility = 'visible';
}
else document.getElementById('ifYes').style.visibility = 'hidden';
}
</script><? if ($row2['check'] >= "3" && $row2['check'] <= "4"){ echo"<div id=level style=\"visibility:hidden\">"; } ?>
Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck" > No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"><br>
<div id="ifYes" <? if ($row2['check'] >= "2"){ echo "style=\"visibility:hidden\"";} else ?> >
<textarea type='text' id='yes' name='yes' <? if ($row2['check'] == "0"){ echo "style=\"width:80%; height:100px\""; }?> ><?php echo $row2['answer']; ?></textarea><br>
</div><? if ($row2['check'] >= "3" && $row2['check'] <= "4"){ echo "</div>"; } ?>
</body>
</html>
What I would like is, to put the scramble words thing at the "level 1"
Use Javascript to put the selected (clicked) text into a variable and add it to the previous selected text in a div with an ID - for example "answer_div". One textbox given as an example but it could be a div and you would then need to get its innerHTML instead.
You could also have a hidden input with a name and an ID and use getElementById() to put the completed sentence into that in your function so it can be submitted to PHP.
You seem to have managed to get your words displayed in the text boxes so you would need to add an onClick; function and pass this to it:
<html>
<head>
<script language=JavaScript>
var answer_var = '';
var elem = '';
function add_answers(elem){
answer_var = elem.value+" ";
document.getElementById('answer_div').innerHTML = document.getElementById('answer_div').innerHTML + answer_var;
}
</script>
</head>
<body>
<input type ="text" id="answer_var" value="word" onclick="add_answers(this);" />
<div id="answer_div"></div>
</body>
</html>

PHP code is not submitting data from POST

It was working until I tried adding this statement
<?php echo "<input type=\"hidden\" name=\"hidden1\" value=\"$id\">" ?>
I was able to get the indexnum from my form before but when I added that line nothing seems to load in the fields.
Here is the full form:
<form name="approveform" method="POST" action="">
<?php echo "<input type=\"hidden\" name=\"hidden1\" value=\"$id\">" ?>
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
</form>
Its getting late and I probably need to just go to sleep but IM SO CLOSE!!! Here is the full code that processes the POST.
if($user_data['permissions'] >= 1)
{
// If users permission is 1 or 2 they get a field for inputting the index # and a button to change the approve field from 0 to 1 may need to make a new field to record who approved it....
//Determine if the order is already approved. If not approved show index field and allow user to approve it with index number
if($data2[0]['Approved'] == 1)
{
echo " <font color=\"green\"> Approved";
}
if($data2[0]['Approved'] == 0)
{
echo " Not Approved. Supply an index number and click approve to authorize this order to be completed.";
if (empty ($_POST) === false)
{
$required_fields = array('IndexNum');
foreach ($_POST as $key=>$value)
{
if (empty($value) && in_array($key, $required_fields) === true)
{
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
if (isset($_POST['success']) === true && empty($_POST['success']) === true)
{
echo 'Index has been updated and Order is now set to Approved';
}
else
{
if (empty($errors) === true)
{
$indexnum=$_POST['IndexNum'];
$approvedby=$user_data['lname'];
$vendorid1= $_POST['hidden1'];
echo $indexnum;
echo $approvedby;
echo $vendorid1;
//update_approved($indexnum, $approvedby, $vendorid1);
//header('Location: index.php');
//exit();
}
else if(empty($errors) === false)
{
echo output_errors($errors);
}
}
}
?>
<form name="approveform" method="POST" action="">
<?php echo "<input type=\"hidden\" name=\"hidden1\" value=\"$id\">" ?>
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
</form>
<?php }
}
Thank you all for looking into this. I get that $id value from a previous POST. I use it elsewhere in the code without issue.
Thank you all so much!
Try like
<input type="hidden" name="hidden1" value="<?php echo $id;?>">
Also try like
<?php echo '<input type="hidden" name="hidden1" value=".$id.">' ?>

If uncheck the check box delete row in my SQL table

Actually I am very new to php.. I have a task that select records from database as checkboxes checked. When I uncheck a checkbox it should delete that particular record from my database..
My code is
<?php
if(isset($_POST['delete']))
{
$test=$_POST['test'];
$qun1=$_POST['question1'];
//DB connection
$CON=mysql_connect("localhost","root","");
mysql_select_db("Dbname");
if($qun1!=0 && $test!=0)
{
foreach($qun1 as $qunestion)
{
echo $question; //this is for testing
$query=mysql_query("delete from test_question where test_questions_id='$test' AND question_id IN ('$question') " ) or die(mysql_error());
}
if($query)
{
echo "success";
}
else
{
echo "No";
}
}
}
?>
my code is working properly but if i use NOT IN in the place of IN it is not working..why?..if unchecked the records it should be delete..i already retrieve records from database as checked fields..
My html markup:
<script>
function fun2(ts)
{
$.post("ajax2.php",{qs:ts},function(data)
{
document.getElementById('div1').innerHTML=data
})
}
</script>
<form action="somepage.php" method="post">
//dynamic selection test code
<select name="test" id="test" onChange="fun2(this.value);">
<option value="">Select Test</option> </select>
<div id="div1" > </div>
<input type="submit" name="delete" value="Delete" >
</from>
my ajax code:
<?php
$qs=$_REQUEST['qs'];
mysql_connect("localhost","root","");
mysql_select_db("advancedge");
$sql=mysql_query("select question_id from test_question where test_questions_id='$qs'");
if($sql)
{
while($rec=mysql_fetch_row($sql))
{
echo "<input type='checkbox' name='question1[]' value='$rec[0]' checked='checked' >";
}
}
?>
If I understand correctly, you want to delete as soon as the item is unchecked? To check if a checkbox is unchecked, you have to use javascript. PHP runs on the server, not the client side (you could use ajax, but I would recommend not to for this).
I would recommend, you delete whatever you want to on form submission, if you don't know how to do that,I can tell you if you post the html part up.
I would also recommend you learn PHP from a course on the internet, so you know some standards and get some good practices. (Youtube or Lynda.com)
It is an old post, but if someone end up here - this might solve the problem:
<?php
echo "<form action='' method='post'>";
echo "<input type='checkbox' id='chk_1' name='chk_1' value='First' />chk 1 </br>";
echo "<input type='checkbox' id='chk_2' name='chk_2' value='Second' />chk 2 </br>";
echo "<input type='submit' />";
echo "</form>";
$check = array();
// Set all checkboxes to 0 if unchecked
for($i = 1; $i<=2; $i++) {
$check["chk_$i"] = isset($_POST["chk_$i"]) ? 1 : 0;
}
// Output of the array
echo '<pre>';
var_export($check);
echo '</pre>';
The code will set all unchecked checkboxes to 0.
Then you have to take care of that using something like this:
<?php
if($_GET['chk_1'] == 0) {
$sql = "DELETE FROM mytable WHERE...";
}

Categories