Load Data From Database PHP - javascript

I need to transfer data from my HTML table to my modal(I am not using bootstrap). As you can see from the image below, I displayed the data from my MySQL database into the table.
The problem is when I click the EDIT button of the 1st row the data will be transferred to my modal. However, when I click the EDIT button of the 2nd row the data transferred to my modal is still the data of the 1st row. Please help me in fixing this problem. I am still learning PHP and JavaScript.
Table Data Generation Here |
Modal Here
PHP Code:
while ($row = mysqli_fetch_array($result)) {
echo "<tr class='table-row'>
<td class='table-cell'>".$row['program']."</td>
<td class='table-cell'>".$row['project_name']."</td>
<td class='table-cell'>".$row['department']."</td>
<td class='table-cell'>".$row['start_date']."</td>
<td class='table-cell'>".$row['end_date']."</td>
<td class='table-cell'><span style='color:".$color."'><i class='fa fa-circle-o'></i></span> ".$row['priority']."</td>
<td class='table-cell'><span style='color:".$color_2."'><i class='fa fa-circle-o'></i></span> ".$row['status']."</td>
<td class='table-cell'><a id='edit-modal-show' class='btn btn-edit'>Edit</a>
<div class='editProject-modal' id='edit-project-modal'>
<div class='editProject-modal-dialog'>
<div class='editProject-modal-content'>
<div class='editProject-onboard'>
<header class='onboard-header'>
<h1 class='onboard-title'>Edit Project</h1>
<button class='onboard-close-2'>
<i class='fa fa-close'></i>
</button>
</header>
<div class='onboard-body'>
<form autocomplete='off' method='POST'>
<input type='hidden' id='".$row['project_id']."' name='p-id' value=".$row['project_id'].">
<div class='row'>
<div class='column-2'>
<div class='form-field'>
<label class='field-label'>Program</label>
<input type='text' placeholder='Program' name='program' id='pr-".$row['project_id']."' class='form-control' value='".$row['program']."' required>
</div>
</div>
<div class='column-2'>
<div class='form-field'>
<label class='field-label'>Project Name</label>
<input type='text' placeholder='Project Name' name='pname' id='pn-".$row['project_id']."' class='form-control' value='".$row['project_name']."' required>
</div>
</div>
</div>
<div class='row'>
<div class='column-2'>
<div class='form-field'>
<label class='field-label'>Project Description</label>
<textarea type='text' placeholder='Project Description' name='description' id='desc-".$row['project_id']."' class='form-control' required>".$row['description']."</textarea>
</div>
</div>
<div class='column-2'>
<div class='form-field'>
<label class='field-label'>Lead Department</label>
<select class='form-control' name='department' required>
<option value=''>Department</option>";
if ($count_2> 0) {
while ($row_2 = mysqli_fetch_array($result_2)) {
if ($row_2['department'] == $row['department']){
$selected = "selected";
}
else {
$selected = "";
}
echo "<option value='".$row_2['department']."'".$selected.">".$row_2['department']."</option>";
}
}
echo"</select>
</div>
</div>
</div>
<div class='row'>
<div class='column-2'>
<div class='form-field'>
<label class='field-label'>Start Date</label>
<input type='date' name='s-date' id='s-date-".$row['project_id']."' class='form-control' value='".$row['start_date']."' required>
</div>
</div>
<div class='column-2'>
<div class='form-field'>
<label class='field-label'>End Date</label>
<input type='date' name='e-date' id='e-date-".$row['project_id']."' class='form-control' value='".$row['end_date']."' required>
</div>
</div>
</div>
<div class='row'>
<div class='column-2'>
<div class='form-field'>
<label class='field-label'>Priority</label>
<select class='form-control' name='priority' id='priority' required>
<option value=''>Priority</option>";
if ($count_3 > 0) {
while ($row_3 = mysqli_fetch_array($result_3)) {
if ($row_3['priority'] == $row['priority']){
$selected = "selected";
}
else {
$selected = "";
}
echo "<option value='".$row_3['priority']."'".$selected.">".$row_3['priority']."</option>";
}
}
echo "</select>
</div>
</div>
<div class='column-2'>
<div class='onboard-btn'>
<button type='submit' class='btn btn-update' name='update'>Update</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</td>
<td class='table-cell'><a href='delete.php?del=".$row['project_id']."' class='btn btn-delete'>Delete</i></a></td>
</tr>";
}
Javascript:
/* Edit Project Modal Event */
var modal_edit = document.getElementById('edit-project-modal');
var span_edit = document.getElementsByClassName("onboard-close-2")[0];
$(document).on('click',".btn-edit",function(){
$(modal_edit).toggleClass("edit-modal-show");
});
span_edit.onclick = function() {
$(modal_edit).removeClass("edit-modal-show");
}

Because it does not know which edit button is related to witch modal.
use
var modal_edit;
$(document).on('click',".btn-edit",function(){
modal_edit = $(this).parent().find(".edit-project-modal");
$(modal_edit).toggleClass("edit-modal-show");
});
$(".onboard-close-2").click(function(){
$(modal_edit).removeClass("edit-modal-show");
});
An other thing I know this is not related to your request but it will give you wrong result when you fix this problem. The form in the model should have a unique name such as your record id so that when it submits it you know which form has been submitted.
P.S. - If you are using double quotes in echo() then rather than doing .." . $PHPVariable . ".. use can directly write echo "<p id='$PHPVariable'>" double quotes can parse PHP Variables, but beware of messing up the single and double quotes.

I think you have to do this in your listing page you have to call onClick method on the button taking the respecting id as an argument
<td onClick="editRow(<?php echo $value['id']; ?>);"><?php echo ($value['display_offer']); ?></td>
and then by using ajax in the function get the respective value according to the id and populate the model.

I think the problem is the same Id for every edit modal. ID must be unique on a page.
You can fix it in two ways:
Use a counter variable inside loop $counter and assign ids like ...id='edit-project-modal-".$counter."'> in this way you will get unique ids like edit-project-modal-1, edit-project-modal-1.
Make a single Modal and dynamically add content to it when edit button is clicked. In this way, you have a single modal with unique Id and also page size will be smaller. For adding content you can make good use of data attributes or jQuery's .closest() and .find() methods.
Some Suggestions:
Use <p id='$phpvariables'> directly if you are using echo() with double quotes. double quotes can parse PHP variables.
Use bootstrap's Modal only build see https://getbootstrap.com/docs/3.3/customize/ to avoid modal related bugs.

Related

Using jQuery to insert PHP variable into form input

I have been staring at this problem for hours, but my jQuery skills are quite basic, so please I need some help here.
I have a 3 form inputs.
When I click on one of the inputs it opens a bootstrap modal that contains my image gallery (which is populated by PHP), and below each image is an "Insert" button.
When I click the Insert button I wish to pass the title of that image back into the specific input field that I clicked.
I know this should be done with jQuery using "this" but just cant figure it out.
Here is my code so far:
The form fields
<form>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter">
</div>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter">
</div>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter">
</div>
</form>
My image gallery code (with insert button)
<?php
$query = $conn->query("SELECT * FROM images ORDER BY id DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageURL = '../../images/'.$row["file_name"];
$imageTitle = $row['file_name'];
$imageID = $row['id'];
?>
<div class="image-gallery-item">
<div class="image-gallery-img">
<img class="gallery-img" src="<?php echo $imageURL; ?>" alt="" />
</div>
<p class="mt-2"><?php echo $imageTitle; ?></p>
<button onclick="insert('<?= $imageTitle; ?>')" class="btn btn-primary" type="button" data-dismiss="modal">INSERT IMAGE</button>
</div>
My ineffective piece of jQuery
$(document).ready(function(){
$(".image_up").click(function insert(image){
$(this).val(image);
});
});
Any help would be greatly appreciated!
$(document).ready(function(){
$(".image_up").click(function insert(image){
$(this).val(image);
});
});
Should be changed to:
function insert(image){
document.querySelector('input[data-caller=' + document.getElementById('exampleModalCenter').dataset.caller + ']').value = image;
}
Also add this:
$('#exampleModalCenter').on('shown.bs.modal', function(e) {
this.dataset.caller = e.relatedTarget.dataset.caller;
});
Then on all of of your form text input add data-caller="". And give each of them a unique value. Like:
<form>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter" data-caller="first">
</div>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter" data-caller="second">
</div>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter" data-caller="third">
</div>
</form>

Can't select element's value loaded by PHP from Database

I have enlisted data from database using PHP. I'm unable to select element's value. Although the data is loaded in DOM. If i just write HTML markup then i'm able to select it other
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" onsubmit="return false">
<div class="product-content"><h3>{$obj->product_name}</h3>
<div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
Price {$currency}{$obj->price}
<fieldset>
<label>
<span>Color</span>
<select name="product_color" class='product_color'>
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</label>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" class='product_qty' id='product_qty' value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button class="add_to_cart" id='add_to_cart' type='submit'>Add</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
Here's the javascript im using.
window.onload = function () {
$('.add_to_cart').click(function(){
$parent = $(this).parent();
$qty = $parent.children('.product-desc').text();
alert($qty);
})
};
Above code works, if i just use HTML Markup rather using above HTML generated using PHP.
Thanks in advance. Searched a lot for this but didn't find anything relevant. Although i also tried Javascripts '.on' and '.live' function but they didn't worked.
$parent = $(this).parent(); selects the <div align="center"> around the button. Use $parent = $(this).closest('.product'); instead.
Though I would recommend actually binding to the submit event of the form instead of to the click of the button.

How to send href value in tablesorter to dialog modal?

Problem
I have problem in sending/passing href value in tablesorter to my dialog modal.
It's become complicated when the target location is the dialog modal.
Example (table.php)
This is a partial of my code since above it is a PDO PHP query to get my data from database. Important point is at the href code inside foreach
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter-dropbox' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr style='text-align: center;'>";
echo "<th style='text-align: center;'>No.</th>";
echo "<th style='text-align: center;'>Conference Name</th>";
echo "<th style='text-align: center;'>Conference Sponsor</th>";
echo "<th style='text-align: center;'>Date (Start)</th>";
echo "<th style='text-align: center;'>Date (End)</th>";
echo "<th style='text-align: center;'>Budget</th>";
echo "<th style='text-align: center;'>Status</th>";
echo "<th style='text-align: center;'>Approve</th>";
echo "<th style='text-align: center;'>Reject</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
//echo "<td><a href='reject.php?idstudent=".$row['matricno']."&idbook=".$row['serialno']."'><img src='pic/remove-icon-png-15.png' width=15px></a></td>";
foreach ($r as $row){
echo "<tr align='center'><td>".$row['id']."</td><td>". $row['conf_name'] ."</td><td>". $row['conf_sponsor'] ."</td><td>". $row['conf_fDate'] ."</td><td>". $row['conf_lDate'] ."</td><td>RM ". $row['conf_budget'] ."</td><td>". $row['conf_status'] ."</td><td><a href='#' onclick='this.href='indexSuperUser.php?idconf=".$row['id']."' role='button' data-toggle='modal' data-target='#login-modal3?idconf=".$row['id']."'><img src='images/good.png' width=15px></a></td><td><a href='#?idconf=".$row['id']."' role='button' data-toggle='modal' data-target='#login-modal4'><img src='pic/remove-icon-png-15.png' width=15px></a></td></tr>";
//$startrow++;
}
echo "</tbody>";
echo "</table>";
}
else{
echo "<p align='center'>Nothing to show you :( I am really sorry for this T_T </p>";
}
Example #2 (dialogmodal.php)
Now here is where i want to display the variable from the table. Just for testing purpose i am trying to display the idconf to see if the id displayed successfully.
<!-- BEGIN # MODAL LOGIN -->
<div class="modal fade" id="login-modal3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" align="center">
<img style="position:relative; LEFT:20px; WIDTH:100px; HEIGHT:100px" id="img_logo" src="images/logofpeNEW2.png">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</div>
<!-- Begin # DIV Form -->
<div id="div-forms">
<!-- Begin # Register Super User Form -->
<form id="approved-form">
<div class="modal-body">
<div id="div-register-msg">
<div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-register-msg">Approve this event?.</span>
</div>
<input type="text" id="idconf" class="form-control" value="<?php echo $_GET['idconf']; ?>">
</div>
<div class="modal-footer">
<div>
<button type="submit" class="btn btn-primary btn-lg btn-block" style="background-color: green">Approve</button>
</div>
</div>
</form>
<!-- End # Register Super User Form -->
</div>
<!-- End # DIV Form -->
</div>
</div>
</div>
<!-- END # MODAL LOGIN -->
<!--END LOGIN AREAD--------------------------------->
Result
The result? Its either undefined index: idconf or nothing. Means that im trying to send variable like this #?idconf=".$row['id']."....... since if i put like this dialogmodal.php?idconf=".$row['id'].".. my dialog ends up opening another dialog that is weird to say.
Flow
The flow is simple. Start from the table.php where it will grab the data from my database and display using tablesorter plugins. Then it will open at the dialog modal. Right side of the table have approved and rejected. So this two things comes from the href itself. Just like on the picture.
Duplicated?
Maybe yes. but its a little bit different. I give here two link almost the same problem as me:
Dynamically load information to Twitter Bootstrap modal
Send parameter to Bootstrap modal window?
However. My problem a bit slightly difficult i think. Mine is not about show the data when button clicked. But instead, i need to click the button to open the modal dialog first then clicked href button to open each row with unique id.
my stackoverflow account could be blocked at any time since i got many downvoted question. I dont know what happen to people nowadays. So i try to do proper and detailed here. If still downvoted, it will be my last here.. :)
Oh never mind. I got it work out by using from someone. I can't remember the link but credit to him for mentioning about using "data-your variable" and call it using jquery and send it back to the modal dialog id. Like this
<a id='approved' href='#' role='button' data-toggle='modal' data-target='#login-modal3' data-id='".$row['idconf']."' data-confname='".$row['conf_name']."' data-confsponsor='".$row['conf_sponsor']."' data-conffdate='".$row['conf_fDate']."' data-confldate='".$row['conf_lDate']."' data-confbudget='".$row['conf_budget']."' data-confstatus='".$row['conf_status']."' data-useremail='".$row['email']."' data-username='".$row['name']."' data-balanceuser='".$row['balance']."' data-m='".$row['matricNo_fk']."'><img src='images/good.png' width=15px></a>
See how many data i send? Then call it using jquery like this..
$(document).on("click", "#approved", function () {
var idconf = $(this).data('id');
var confname = $(this).data('confname');
var confsponsor = $(this).data('confsponsor');
var conffdate = $(this).data('conffdate');
var confldate = $(this).data('confldate');
var confbudget = $(this).data('confbudget');
var confstatus = $(this).data('confstatus');
var useremail = $(this).data('useremail');
var username = $(this).data('username');
var balanceuser = $(this).data('balanceuser');
var m = $(this).data('m');
After declare this variable, then on the next line of this code, send it to the modal dialog id such as this.
$(".modal-body #idconf").val( idconf );
$(".modal-body #nameconf").val( confname );
$(".modal-body #sponsorconf").val( confsponsor );
$(".modal-body #dateSconf").val( conffdate );
$(".modal-body #dateEconf").val( confldate );
$(".modal-body #budgetconf").val( confbudget );
$(".modal-body #statusconf").val( confstatus );
$(".modal-body #emailuser").val( useremail );
$(".modal-body #nameuser").val( username );
$(".modal-body #balanceuser").val( balanceuser );
$(".modal-body #m").val( m );
$('#addBookDialog').modal('show');
On the modal dialog, use the id mentioned.
<form id="approved-form">
<div class="modal-body">
<div id="div-register-msg">
<div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-register-msg">Approve this event?.</span>
</div>
<input type="hidden" id="idconf" class="form-control" value="" disabled>
<input type="text" id="nameconf" class="form-control" value="" disabled>
<input type="text" id="sponsorconf" class="form-control" value="" disabled>
<input type="text" id="dateSconf" class="form-control" value="" disabled>
<input type="text" id="dateEconf" class="form-control" value="" disabled>
<input type="text" id="balanceuser" class="form-control" value="" disabled>
<input type="text" id="budgetconf" class="form-control" value="" disabled>
<input type="text" id="statusconf" class="form-control" value="" disabled>
<input type="text" id="emailuser" class="form-control" value="" disabled>
<input type="text" id="nameuser" class="form-control" value="" disabled>
<input type="hidden" id="m" class="form-control" value="" disabled>
</div>
I am not saying this is efficient in terms of speed or whatever. but it solved my problem and user problem. Case solved

Toggling php generated div elements

I am fetching data from using mysql to generate div tags in a sort of hierarchy structure. There are div tags inside div tags which are inside div tags. This is created using nested while loops. The output is like this where the ids are uniquely made through php:
<div class="holder">
<label class="toggle" id=$courseCategory>Category 1</label>
<div class="content" id=$courseCategory>
<label class="toggle" id=$courseTopic>Topic 1</label>
<div class="content" id=$courseTopic>
</div>
</div>
<label class="toggle" id=$courseCategpry>Category 2</label>
</div>
And that is the basic structure of the generated content.
The PHP that is creating the structure is this:
<?php
include "connect.php";
global $con;
$qryCat=mysqli_query($con, "SELECT DISTINCT CourseCategory FROM tblCourse");
while($row=mysqli_fetch_array($qryCat, MYSQL_ASSOC)){
$courseCat = $row['CourseCategory'];
//print $courseCat
echo "<label class ='toggle' id='".$courseCat."'>".$courseCat."</label>";
echo "<div class ='content' style = 'display:none;' id='div".$courseCat."'>";
$qryTop=mysqli_query($con, "SELECT DISTINCT CourseTopic FROM tblCourse WHERE CourseCategory = '$courseCat'");
while($row=mysqli_fetch_array($qryTop, MYSQL_ASSOC)){
$courseTop = $row['CourseTopic'];
//print $courseTop;
echo "<label class ='toggle' id='".$courseTop."'>".$courseTop."</label><br/>";
echo "<div class ='content' style = 'display:none;' id='div".$courseTop."'>";
$qryLevel=mysqli_query($con, "SELECT DISTINCT CourseLevel FROM tblCourse WHERE CourseCategory = '$courseCat' AND CourseTopic = '$courseTop'");
while($row=mysqli_fetch_array($qryLevel, MYSQL_ASSOC)){
$courseLevel = $row['CourseLevel'];
//print $courseLevel;
echo "<label class ='toggle' id='".$courseTop.$courseLevel."'>".$courseLevel."</label><br/>";
echo "<div class ='content' style = 'display:none;' id='div'".$courseTop.$courseLevel."'>";
$qryCourse=mysqli_query($con, "SELECT DISTINCT CourseCode, CourseName FROM tblCourse WHERE CourseCategory = '$courseCat' AND CourseTopic = '$courseTop' AND CourseLevel = '$courseLevel'");
while($row=mysqli_fetch_array($qryCourse, MYSQL_ASSOC)){
$courseCode =$row['CourseCode'];
$courseName = $row['CourseName'];
//print $courseName;
echo "<label id='".$courseCode."'>".$courseName."</label><br/>";
echo "<div id='div".$courseCode."'></div>";
}
echo "</div>";
}
echo "</div>";
}
echo "</div><br/>";
}
?>
I want to use jQuery to toggle each section like a menu. So when I press Category 1, All the topics under Category 1 are show, which I can then click on the topics to show the next level of the menu.
I have tried a couple of different things in trying to get this to work. The below code works for the first level. I can toggle the categories, however nothing happens when clicking on the topics that are shown.
$(document).ready(function(){
$(".toggle").click(function() {
$(this).next(".content").toggle("slow");
});
});
I have also tried this code which allows the entire "tree" to expand, however it toggles all siblings.
$(document).ready(function(){
$(".toggle").click(function() {
$(this).siblings(".content").toggle("slow");
});
});
Both have aspects that I want for the final result but I can't figure out how to navigate the tree in order to do what I want.
Any help would be greatly appreciated.
EDIT: After looking through the PHP to see if that was the issue I still can't get it working. I have added the PHP to see if someone with sharper eyes can see if that is the problem.
Can you try it? Is this you are looking or
you are looking like "ACCORDION MENU"?
Your Code is working fine. The Problem may be there is no content in Category 2.
Script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".toggle").click(function() {
$(this).next(".content").toggle("slow");
});
});
</script>
CSS
<style>
label + .content{
display:none;
}
label + .open{
display:block;
}
</style>
HTML
<div class="holder">
<label class="toggle" id=$courseCategory>Category 1</label>
<div class="content open" id=$courseCategory>
<label class="toggle" id=$courseTopic>Topic 1</label>
<div class="content" id=$courseTopic>
</div>
</div><br/>
<label class="toggle" id=$courseCategpry>Category 2</label>
<div class="content" id=$courseCategory>
<label class="toggle" id=$courseTopic>Topic 2</label>
<div class="content" id=$courseTopic>
</div>
</div><br/>
<label class="toggle" id=$courseCategpry>Category 3</label>
<div class="content" id=$courseCategory>
<label class="toggle" id=$courseTopic>Topic 3</label>
<div class="content" id=$courseTopic>
</div>
</div><br/>
</div>
Attempt #2 In php
<div class="holder">
<?php
$count=0;
for($i=0;$i<5;$i++){
$count=$count+1;
?>
<label class="toggle" id=$courseCategory>Category <?php echo $count; ?></label>
<div class="content open" id=$courseCategory>
<label class="toggle" id=$courseTopic>Topic <?php echo $count; ?></label>
<div class="content" id=$courseTopic>
</div>
</div><br/>
<?php } ?>
</div>
Your are binding click event that are being generated dynamically. So may be the click function is not binded with elements at that moment.
Check below link
http://jsfiddle.net/23yxj3ny/1/
$(".holder").on('click','.toggle',function() {
$(this).siblings(".content").toggle("slow");
});
For future reference, the problem was with the PHP. I guess when the was being echo'd after the it was changing the structure of the . After removing the it works perfect!

Display a hidden div after a html form submit to show output

I have a html form to collect name and place and after user submit the form, the out will display at bottom of the page using PHP echo
My requirement is,
hide the output div before the form submit and after user enter data and submit, I have to make output div visible to display form output using PHP echo.
Here is my HTML code:
<div class="main">
<form id="main" name="main" action="#text" method="post">
<div class="input">
<div id="name">
<div class="block">
<div class="input-quest">Your Name</div>
<div class="input-resp"><span><input class="textbox" id="nm" name="nm" type="text" value="" /></span>
</div>
</div>
</div>
<div id="place">
<div class="block">
<div class="input-quest">Your Place</div>
<div class="input-resp"><span><input class="textbox" id="pl" name="pl" type="text" value="" /></span>
</div>
</div>
</div>
</div>
<div class="submit">
<input id="generate" type="submit" name="script" value="generate" />
<input type="submit" id="clear" name="clear" value="clear" />
</div>
</form>
<div class="output">
<?php $name = $_POST['nm']; $place = $_POST['pl']; echo "Hello, I am $name and I am from $place"; ?>
</div>
</div>
It contain the PHP echo codes at output div section.
I have searched for solution in previous questions and tried below methods mentioned there:
1.Added a inline CSS tag for output div to hide it
<div id="output" style="display: none;">
<!-- echo php here -->
</div>
and added JavaScript to call function during submit
$('main').submit(function(){
$('#output').show();
});
It didn't work.
2.Tried with below JavaScript code
$('main').submit(function(e){
$('#output').show();
e.preventDefault();
});
It didn't work.
3.Removed inline CSS for output div to hide and added the same to my CSS stylesheet
<div id="output">
and in stylesheet
#output{
display:none;
}
and used below JavaScript code on submit
$('main').submit(function(){
$('#output').css({
'display' : 'block'
});
});
It didn't work.
Added a onclick function along with the form submit
and submit button code:
<input id="generate" type="submit" name="script" value="generate" onclick="showoutput()"/>
and JavaScript:
showoutput(){
$('#output').slideDown("fast");
}
and with
showoutput(){
$('#output').show();
}
It didn't work.
Please suggest a solution to do this.
I'm not sure why you need to use js/css for this at all. Just check if the variables were posted, and if they were, echo them (you'd have to set your form action to point to the same page):
<?php if (!empty($_POST['nm']) && !empty($_POST['pl'])) { ?>
<div class="output">
Hello, I am <?php echo $_POST['nm']; ?>, and I am from <?php echo $_POST['pl']; ?>
</div>
<?php } ?>
If you just want to display the name and place in div.output, without actually submitting the form, you could do:
$('#main').submit(function(e) {
e.preventDefault(); // prevent form from being submitted
$('div.output').text('Hello, I am ' + $('#nm').val() + ', and I am from ' + $('#pl').val());
});
Here's a fiddle
<?php if(isset($_POST['nm'])) { ?>
<div class="output">
<?php $name = $_POST['nm']; $place = $_POST['pl']; echo "Hello, I am $name and I am from $place"; ?>
</div>
<?php } ?>
Create a separate page to process your form using javascript/jquery (ajax), and have it return the info you want, hide the form and show the .output div.
PHP Page:
<?php
$name = $_POST['nm'];
$place = $_POST['pl'];
echo "Hello, I am ".$name." and I am from ". $place;
?>
The javascript/jquery would catch that as responseText and then use innerHTML on your .output div to put that responseText. You'd then use the JS/Jquery to hide the form and show the .output
You can actually accomplish this entirely with php. The simplest method that I would use would be to make a hidden input with a given value. Once the user submits the form, that variable will exist and you can grab it in your php.
First you need to change the entire page to .php, and echo all of your html. then in the form, set the action to the name of the page so that it will send the variables to itself and then you can deal with them on the same page.
add this to the html:
<input type='hidden' name='display' value='display' />
In your php, add:
if (isset($_POST['display']){
echo "make the div here";
}else{
//don't show the div
}

Categories