PHP,Javascript, select and alert - javascript

Hello I am new to Javascript and currently trying to update another developers code. I have a very simple 4 question for with a mix of checkboxes and text fields.
My first piece of Javascript works: it says if there is no info typed in postsitesurvey then alert that it must be filled out. The next step I am stuck on. The employee has 2 visible options and 1 hidden. Were parts left over? I want it that if he checks yes then the next field which is the Left with field must be filled out and if not yes then he can go ahead and submit the form. Any help would be appreciated.
echo "<form id=\"myForm\" name=\"myForm\" method=\"post\" action=\"edit.php?
action=upbill2\" onsubmit=\"return validateForm()\">";
echo "<table width=\"100%\" border=\"0\" cellspacing=\"5\" cellpadding=\"0\"
class=\"table2\">";
echo "<div class=\"col-sm-6\">";
echo "<b>Post Site Survey</b>";
Echo "&nbsp&nbsp&nbsp";
echo "<textarea style=\"width:70%\" name=\"postsitesurvey\"
id=\"postsitesurvey\" value=\"$postsitesurvey\" />";
echo $postsitesurvey;
echo "</textarea>";
echo "</div>";
echo "<div class=\"col-sm-6\">";
echo "<b>Was There Equipment Left Over?</b>";
Echo "&nbsp&nbsp&nbsp";
echo "<input name=\"eq_left\" type=\"checkbox\" id=\"eq_left_yes\"
value=\"1\"";
if ($eq_left == "1") { echo " checked=\"checked\" "; }
echo "/> &nbsp&nbsp&nbspYes ";
Echo "&nbsp&nbsp&nbsp";
echo "<input name=\"eq_left\" type=\"checkbox\" id=\"eq_left_no\"
value=\"2\"";
if ($eq_left == "2") { echo " checked=\"checked\" "; }
echo "/> &nbsp&nbsp&nbspNo ";
echo "</div>";
echo "<input name=\"eq_left\" type=\"checkbox\" id=\"eq_left_empty\"
value=\"\" style=\"display:none;\" checked";
if ($eq_left == "") { echo " checked=\"checked\" "; }
echo "</div>";
echo "<div class=\"col-sm-6\">";
echo "<b>Left with?</b>";
Echo "&nbsp&nbsp&nbsp";
echo "<input style=\"width:45%\" name=\"eq_poc_\" type=\"text\"
id=\"eq_poc\" value=\"$eq_poc\" placeholder=\"Name of customer\"";
echo "</div>";
echo "&nbsp&nbsp&nbsp or";
Echo "&nbsp&nbsp&nbsp";
echo "<input name=\"eq_poc\" type=\"checkbox\" id=\"chkNo\" value=\"MCS\"";
if ($eq_poc == "MCS") { echo " checked=\"checked\" "; }
echo "/> &nbsp&nbsp&nbspMCS";
echo "</div>";
echo "<br>";
echo "<div class=\"col-sm-12 text-center\">";
echo "<input name=\"st_id\" type=\"hidden\" id=\"st_id\" value=\"3\" />";
echo "<input name=\"job_id\" type=\"hidden\" id=\"job_id\" value=\"$job_id\" />";
echo "<input type=\"submit\" name=\"Submit\" value=\"Submit\" class=\"btn btn-primary\"/>";
echo "</div>";
echo "</table>";
echo "</form>";
}
----JAVASCRIPT----
function validateForm() {
var x = document.forms["myForm"]["postsitesurvey"].value;
if (x == "") {
alert("Post site survey must be filled out");
return false;
}

I removed the distracting stuff, you can copypaste to your question, I will then delete this post...
<?php
$checked_1 = ($eq_left == "1") ? 'checked="checked"' : '';
$checked_2 = ($eq_left == "2") ? 'checked="checked"' : '';
$checked_3 = ($eq_left == "") ? 'checked="checked"' : '';
$checked_4 = ($eq_poc == "MCS") ? 'checked="checked"' : '';
?>
<form id="myForm" name="myForm" method="post" action="edit.php?action=upbill2" onsubmit="return validateForm()">
<b>Post Site Survey</b>
<textarea name="postsitesurvey" id="postsitesurvey" value="$postsitesurvey" />
<?=$postsitesurvey?>
</textarea>
<b>Was There Equipment Left Over?</b>
<input name="eq_left" type="checkbox" id="eq_left_yes" value="1" <?=$checked_1?>/>
<input name="eq_left" type="checkbox" id="eq_left_no" value="2" <?=$checked_2?>/>
<input name="eq_left" type="checkbox" id="eq_left_empty" value="" style="display:none;" <?=$checked_3?>/>
<b>Left with?</b>
<input name="eq_poc_" type="text" id="eq_poc" value="$eq_poc" placeholder="Name of customer"/>
<b>or</b>
<input name="eq_poc" type="checkbox" id="chkNo" value="MCS" <?=$checked_4?>/><b>MCS</b>
<input name="st_id" type="hidden" id="st_id" value="3" />
<input name="job_id" type="hidden" id="job_id" value="<?=$job_id?>" />
<input type="submit" name="Submit" value="Submit" class="btn btn-primary"/>
</form>

I think something like this would work for you. I changed your checkboxes to radio buttons and removed the eq_left = "". You also had two fields with the name "eq_poc". You cannot do this. I removed one, but you may want to consider a different option or explain what you are trying to do a bit better.
I have also added a toggleHide() function to show or hide the customer name field.
Alert messages can be annoying, so I removed them and added a <div> to put error messages on the page in red color.
One other thing to note is that I added the required attribute to your textarea. This allows the browser to inform the user that they haven't filled in a required field. Doing it this way, however, will not show the error message on the page in red. So, depending how you want to implement it, you may want to remove the required attribute.
The following code below will work by itself, once you are happy with it, remove the two lines at the top that are for testing and see if it works with variables passed from your other code.
<?php
//The two lines below are for testing purposes only. Once you are done testing, you can remove them to implement it with the rest of your code.
$eq_left = "1";
$eq_poc = "";
$checked_yes = ($eq_left == "1") ? 'checked="checked"' : '';
$checked_no = ($eq_left == "2") ? 'checked="checked"' : '';
?>
<html>
<script>
function toggleHide() {
var equipment_left = document.getElementById('eq_left_yes').checked;
if (equipment_left){
document.getElementById('leftwith').style.display = 'block';
}
else {
document.getElementById('leftwith').style.display = 'none';
}
}
function validateForm() {
var message = "";
var postsitesurvey = document.getElementById('postsitesurvey').value;
if (postsitesurvey == "") {
message = "Post site survey must be filled out";
}
else if (equipment_left && eq_poc == ""){
var equipment_left = document.getElementById('eq_left_yes').checked;
var eq_poc = document.getElementById('eq_poc').value;
message = "Customer name must be filled in";
}
if (message != ""){
document.getElementById('message').textContent = message;
return false;
}
return true;
}
</script>
<style>
.formfield {
font-weight: bold;
}
#leftwith {
display: none;
}
#message {
color: red;
}
</style>
</body>
<form id="myForm" name="myForm" method="post" action="edit.php?action=upbill2" onsubmit="return validateForm()">
<div class="formfield">Post Site Survey</div>
<textarea name="postsitesurvey" id="postsitesurvey" value="$postsitesurvey" required="required" /><?php echo $postsitesurvey ?></textarea>
<div class="formfield">Was There Equipment Left Over?
<input name="eq_left" type="radio" id="eq_left_yes" value="1" onclick="toggleHide()" <?php echo $checked_yes ?> /> Yes
<input name="eq_left" type="radio" id="eq_left_no" value="2" onclick="toggleHide()" <?php echo $checked_no ?> /> No
</div>
<div class="formfield" id="leftwith">
Left with?
<input name="eq_poc_" type="text" id="eq_poc" value="<?php echo $eq_poc ?>" placeholder="Name of customer"/>
</div>
<input name="st_id" type="hidden" id="st_id" value="3" />
<input name="job_id" type="hidden" id="job_id" value="<?php echo $job_id ?>" />
<div id="message"></div>
<input type="submit" name="Submit" value="Submit" class="btn btn-primary"/>
</form>
<script>
toggleHide();
</script>
</body>
</html>

Related

Why I need to use history.back(); twice for cancel button

I created a cancel button using the method explained by macino in this thread
cancel button using php
But I have to use history.back(); twice to cancel the form. What is the reason for that? Thanks.
$post_counter=1;
foreach ($comment as $c) {
echo $c['comment'] . "<br>";
echo "By " . $c['first_name'] . "<br>";
if($c['uid'] == $current_user) { ?>
Edit<br>
<div id="<?php echo "post_edit_box" . $post_counter; ?>" style="display:none">
<form id="<?php echo "reply_form" . $post_counter; ?>" method="post" action="<?php echo site_url('Forum/update_comment'); ?>">
<input type="text" name="edit_comment" value="<?php echo $c['comment'];?>" class="form-control">
<input type='hidden' name='edit_cid' value='<?php echo $c['id']; ?>'/>
<button type="submit">Save Changes</button>
<input type="button" value="Cancel" onclick="history.back();history.back();" />
</form>
</div>
<script>
function show_postedit_box(clicked_edit_id){
let str_edit = clicked_edit_id;
str_edit.replace("post_edit_link", "");
//console.log('mylink' + str.replace("mylink", ""));
document.getElementById('post_edit_box' + str_edit.replace("post_edit_link", "")).style.display = "block";
document.getElementById('post_edit_link' + str_edit.replace("post_edit_link", "")).style.display = "none";
}
</script>
<?php
$post_counter++;
}

JSon array increment my id value from $_POST['id']

In my php script, I have managed to get all the data from a form into a json database, however everytime I submit my form, the id value is always == 1. How would I be able to change this, and add more values to my id value, like value++? How would I be able to do that?
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
{
if(empty($_POST["title"]))
{
$error = "<label class='text-danger'>Enter title</label>";
echo $error;
}
else if(empty($_POST["decs"]))
{
$error = "<label class='text-danger'>Enter Gender</label>";
echo $error;
}
else if(empty($_POST["cont"]))
{
$error = "<label class='text-danger'>Enter Designation</label>";
echo $error;
}
else
{
if(file_exists('postbl.json'))
{
$current_data = file_get_contents('postbl.json');
$array_data = json_decode($current_data, true);
$extra = array(
'id' => $_POST['id'],
'title' => $_POST['title'],
'decs' => $_POST["decs"],
'cont' => $_POST["cont"]
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('postbl.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
echo $message;
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
my form is like this
<?php session_start();
if(!isset($_SESSION['loggedin'])) header("Location: session.php");
if($_SESSION['loggedin']===FALSE) header("Location: session.php");
?>
<!DOCTYPE html>
<html><head><title>Secret Area</title></head>
<body>
<form action="/admin/form_process.php" method="POST">
<br />
<input type="hidden" name="id" value="1" />
<label>Title</label>
<input type="text" name="title" class="form-control" /><br />
<label>Description</label>
<input type="text" name="decs" class="form-control" /><br />
<label>Content</label>
<input type="text" name="cont" class="form-control" /><br />
<input type="submit" name="submit" value="Append" class="btn btn-info" /><br />
<?php
if(isset($message))
{
echo $message;
}
?>
</form>
<form action="logout.php" method="POST">
<input type="submit" name="logout" value="Log out">
</form>
<p>© 2017 Blog Message</p>
</body>
</html>
Your problem is here
<input type="hidden" name="id" value="1" />
Notice how the 1 is set as value.
Change the 1 with a variable. Something like
<input type="hidden" name="id" value="<?= $id ?>" />

Hide/Show toggle echo results in php

I am trying to toggle results i have echo'd out of table but i am having no luck.
I have tried the same code in HTML and it works perfectly.
Ive been working on this for a while now, and was wondering if someone could point me in the right direction.
What I've tired
Adding the javascript inside the php echo.
Adding a counter to the id, to make it unique on loop
Placing each line of the echo results in echo(""); tags.
adding a counter, to make the id unique on loop.
PHP
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
echo"
<div id='first_product'>
<button onclick='toggle_visibility('tog')'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility('tog')'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
";
}
}
JAVASCRIPT
<script>
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
The single quotes in onclick='toggle_visibility('tog')' are conflicting with the outer single quotes. So either escape them or use double quotes in either the outer pair or the inner pair.
Then in PHP, remove the <?php echo. Just put the HTML in PHP. The echo only complicates things. If you need dynamic data in your HTML, just inject it at that place with <?php ... ?>. But so far I haven't seen any of that in your HTML: it is static.
Here is a working snippet, after having made that change in two places:
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
<div id='first_product'>
<button onclick="toggle_visibility('tog')">Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick="toggle_visibility('tog')"> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
Edit after modification of the question
The code in the question was extended so the HTML is produced in a loop now.
You should now take care to produce unique id values only. So you'll probably want to add <?=$i?> at several places, like this:
<?php
session_start();
// ....
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name'];
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc'];
?>
<div id='first_product<?=$i>'>
<button onclick="toggle_visibility('tog<?=$i>')">Toggle</button>
<div id='tog<?=$i>'>
<div id='red_head<?=$i>'>
...etc. Note that the PHP was closed before the HTML output started. Do this, instead of a large echo. Then at the end of it, open PHP tag again to end the loop:
<?php
}
?>
please modify your code
echo "
<div id='first_product'>
<button onclick='toggle_visibility(\"tog\")'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility(\"tog\")'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
"
<button value='tog' onclick='toggle_visibility(this)'>Toggle</button>
Just use "this" and assign value to button its working
Try this ;)
<?php
$i = 1;
while($output = $fc_sel->fetch_assoc()){
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
?>
<div id="first_product<?php echo $i; ?>">
<button onclick="javascript:toggle_visibility('tog<?php echo $i; ?>')">Toggle</button>
<div id="tog<?php echo $i; ?>">
<div id="red_head<?php echo $i; ?>">
<p id="menu_title<?php echo $i; ?>" class ="hidden" onclick="toggle_visibility('tog<?php echo $i; ?>')"> Add your first menu item</p>
</div>
<h3 id="menu<?php echo $i; ?>">Menu Section</h3>
<form name="first_prod" id="first_prod<?php echo $i; ?>" enctype="multipart/form-data" action="testing.php" method="POST" accept-charset="utf-8">
<label id="cat_label<?php echo $i; ?>" name="cat_label">Name</label>
<input type="text" id="cat_name<?php echo $i; ?>" name="cat_name" value="">
<label id="desc_label<?php echo $i; ?>" name="desc_label">Description</label>
<input type="text" id="cat_desc<?php echo $i; ?>" name="cat_desc" value="">
</form>
</div>
</div>
<?php
$i++;
}
?>

js submit not works not sending post form data to php

After certain time (2min) when i try form submit using javascript it just submit form without post data value !!! searched solution on web but unable to find solution!! Hope someone can help me
Code:
<script type="text/javascript">
$(function() {
$('.countdown.callback').countdown({
date: +(new Date) + 120000,
render: function(data) {
$(this.el).text( this.leadingZeros(data.min, 2) + "min " + this.leadingZeros(data.sec, 2) + " sec");
if(this.leadingZeros(data.min, 2) < 01 && this.leadingZeros(data.sec, 2) <= 10){
$(this.el).addClass('ended');
}
},
onEnd: function() {
document.getElementById('myform').submit();
}
});
});
</script>
html code with php
<?php
foreach($row as $r){
if(!empty($r['question'])){
?>
<form method="post" id="myform" action="subanswer.php" >
<p><span style="color:rgb(33,79,157);"><?php echo $r['id'];?> <?php echo $r['question'];?></span><br />
<input type="radio" name="<?php echo $r['test_id'].'_'.$r['id'];?>" value="<?php echo $r['ans1'];?>"> <?php echo $r['ans1'];?>
<br>
<input type="radio" name="<?php echo $r['test_id'].'_'.$r['id'];?>" value="<?php echo $r['ans2'];?>"> <?php echo $r['ans2'];?>
<br>
<input type="radio" name="<?php echo $r['test_id'].'_'.$r['id'];?>" value="<?php echo $r['ans3'];?>"> <?php echo $r['ans3'];?>
<input type="hidden" name="testname" value="<?php echo $_GET['id']?>">
</p>
<?php
}
}
?>
<input type="submit" name="subans" value="add" class="but" style="width:15%;" />
</form>
From your code, it looks like you're calling the wrong form:
document.getElementById('myForm').submit();
The ID myFom does not exist. You have:
<form method="post" id="myform1" action="subanswer.php" >
Also not sure why people don't stick to JQuery throughout. Would advise:
$("#myForm1").submit();

Display alert when user input is less than specified value.

i want to display alert box when value inserted by user is less than specified value.and this specified value is taken from database. I am new in php so that i m not getting whats wrong with this code.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gunjanbid", $con);
$username=$_SESSION['userName'];
$id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM bids WHERE id =$id");
//$query=mysql_query("SELECT * FROM bid
$numrow = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
]
$bidfee=$row[5];
}
?>
<?php
echo '<script type="text/javascript">';
echo "function validateForm1()";
{
echo "var c=document.forms['auction1']['fir'].value";
echo "var d=document.forms['auction1']['bidamount'].value";
if echo "( c==null || c=="" )";
{
echo "alert('UserName must be filled out')";
echo "return false";
}
echo "else";
{
echo "if(c<$bidfee)"
{
echo "alert('Bid can not be less than Bid fee')";
echo "return false";
}
}
echo "if (d==null || d=="")";
{
echo "alert('UserName must be filled out')";
echo "return false";
}
echo "else";
{
echo "if(d<$bidfee)";
{
echo "alert('Bid can not be less than Bid fee')";
echo "return false";
}
}
}
echo "</script>";
?>
<form action="multiplebid.php" name="auction1" onsubmit="return validateForm1()" method="post" >
<input type="hidden" name="description" value="" >
<input type="hidden" name="closing_date" value="" >
<input type="text" name="fir" value="" size="5" >
<input type="text" name="sec" value="" size="5" ></td><td> </td><td><input type="submit" name="submit" class="button" value="Bid Now" ></form>
The above code is not displaying alert box and showing error that syntax error, unexpected T_ECHO, expecting '(' in C:\wamp\www\old\detailproduct.php on line 426
or if there be any another way to display alert box then plz help me.
Try below code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gunjanbid", $con);
$username=$_SESSION['userName'];
$id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM bids WHERE id =$id");
$numrow = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$bidfee=$row[5];
}
?>
<script type="text/javascript">
var bidfee = '<?php echo $bidfee;?>';
function validateForm1(){
var c=document.forms['auction1']['fir'].value;
var d=document.forms['auction1']['bidamount'].value;
if ( c==null || c=="" ){
alert('UserName must be filled out');
return false;
}else{
if(c<bidfee){
alert('Bid can not be less than Bid fee');
return false;
}
}
if (d==null || d==""){
alert('UserName must be filled out');
return false;
}else{
if(d<bidfee){
alert('Bid can not be less than Bid fee');
return false;
}
}
}
</script>
<form action="multiplebid.php" name="auction1" onsubmit="return validateForm1()" method="post" >
<input type="hidden" name="description" value="" >
<input type="hidden" name="closing_date" value="" >
<input type="text" name="fir" value="" size="5" >
<input type="text" name="bidamount" value="" size="5" ></td><td> </td><td><input type="submit" name="submit" class="button" value="Bid Now" >
</form>

Categories

Resources