jquery hide div when click search button and display result - javascript

newbie here, having problem with my jquery right now. When I clicked search the result is posted on the right div, only problem is the div1 is not being able to hide. Help please.
Here is the composition of my code so far. Just really getting messed up with the hide function of the div id=tab1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="./js/sample.js"></script>
<script src="./js/quicksearch.js"></script>
<script src="./js/lytebox.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="./css/sample.css">
<link rel="stylesheet" type="text/css" href="./css/table_blue.css">
<link rel="stylesheet" type="text/css" href="./css/lytebox.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script>
$(function () {
var $dtps = $("#datepicker, #datepicker2"); //use a class selector to simplify this
$dtps.hide().datepicker({
dateFormat: 'yy/mm/dd'
});
$("#category").on('change', function () {
$dtps.toggle(this.value == 'ORIGINAL_DEADLINE')
});
//should be outside of the change event hanlder
$("#cmdsearch").click(function () {
//e.preventDefault();
$("#tab1").hide();
$("#tab_result").show();
});
});
</script>
<div class="tabs">
<ul class="tab-links">
<li class="active">Overdue</li>
<li>Next 60 days</li>
<li>Others</li>
<li>No Deadline</li>
<li>Finished Documents</li>
<li>Register User</li>
<li>Generate Report</li>
<li>Manage Users</li>
<li>Logout</li>
</ul>
<form method="post" action="beta_table.php">
Category<select name="category" id="category">
<option value='APP_NUMBER' >APP_NUMBER</option>
<option value='SPOC_ASSIGNED' >SPOC_ASSIGNED</option>
<option value='BORROWER_NAME' >BORROWER_NAME</option>
<option value='DEFERRED_TYPE' >DEFERRED_TYPE</option>
<option value='ORIGINAL_DEADLINE' >ORIGINAL_DEADLINE</option>
</select>
Search Text<input type="text" name="txtsearch" placeholder="Type to Search" />
<input type="text" id="datepicker" name="date1" placeholder="Input Start Date"/>
<input type="text" id="datepicker2" name="date2" placeholder="Input End Date"/>
<input type="submit" id="cmdsearch" name="cmdsearch" value="Search" />
</form>
<div class="tab-content">
<div id="tab1" class="tab active" >
<?php
//conection:
include "conn.php";
//consultation:
$query = "SELECT * FROM export_workflow.COLLATERAL_MANAGEMENT where DATEDIFF(CURDATE(),ORIGINAL_DEADLINE)>1 and SUBMITTED_PENDING='PENDING'";
//execute the query.
if($result = $link->query($query)){
echo "<table class='data' id='table_example'>".
"<thead>".
"<tr>".
"<td>App Number</td>".
"<td>Spoc Assigned</td>".
"<td>Borrower Name</td>".
"<td>App Finish Date</td>".
"<td>Developer & Project</td>".
"<td>Collateral Address Details</td>".
"<td>Deferred Document</td>".
"<td>Deferred Type</td>".
"<td>Original Deadline</td>".
"<td>Date Completed</td>".
"<td>SPOC Remarks</td>".
"<td>File Location</td>".
"<td>JUW MA Remarks</td>".
"<td>COSU Remarks</td>".
"<td>SMU Notes</td>".
"<td>SUBMITTED/PENDING</td>".
"<td> EDIT </td>".
"</tr></thead>";
while($row = $result->fetch_assoc()){
echo "<tr><td>".$row['APP_NUMBER']."</td>".
"<td>".$row['SPOC_ASSIGNED']."</td>".
"<td>".$row['BORROWER_NAME']."</td>".
"<td>".$row['APP_FINISH_DATE']."</td>".
"<td>".$row['DEVELOPER_PROJECT']."</td>".
"<td>".$row['COLLATERAL_ADDRESS_DETAILS']."</td>".
"<td>".$row['DEFERRED_DOCUMENT']."</td>".
"<td>".$row['DEFERRED_TYPE']."</td>".
"<td>".$row['ORIGINAL_DEADLINE']."</td>".
"<td>".$row['DATE_COMPLETED']."</td>".
"<td>".$row['SPOC_REMARKS']."</td>".
"<td>".$row['FILED_LOCATION']."</td>".
"<td>".$row['JUW_MA_REMARKS']."</td>".
"<td>".$row['COSU_REMARKS']."</td>".
"<td>".$row['SMU_NOTES']."</td>".
"<td>".$row['SUBMITTED_PENDING']."</td>".
"<td><a href='spoc_remarks.php?id=".$row['ID']."' class='lytebox'><image src='./images/pen.png' height=30 width=30></a></td>".
"</tr>";
}
$result->close();
echo "</table>\r\n";
} else {
printf("<p>Error: %s</p>\r\n", $mysqli->error);
}
?>
</div>
<div id="tab_result">
<?php
if(isset($_POST['cmdsearch'])){
$category=$_POST['category'];
$text=$_POST['txtsearch'];
$date1=$_POST['date1'];
$date2=$_POST['date2'];
//connect to db
$link = mysqli_connect("10.20.8.70","stcutie","qwerty123","export_workflow") or die("Error " . mysqli_error($link));
if($link->connect_error){
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($category==='ORIGINAL_DEADLINE'){
$sql="SELECT * FROM COLLATERAL_MANAGEMENT where ($category BETWEEN '$date1' AND '$date2')";
}else{
$sql="SELECT * FROM COLLATERAL_MANAGEMENT where $category LIKE '%$text%'";
}
if (mysqli_query($link, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
$result = $link->query($sql);
echo "<table class='data' id='table_example'>".
"<thead>".
"<tr>".
"<td>App Number</td>".
"<td>Spoc Assigned</td>".
"<td>Borrower Name</td>".
"<td>App Finish Date</td>".
"<td>Developer & Project</td>".
"<td>Collateral Address Details</td>".
"<td>Deferred Document</td>".
"<td>Deferred Type</td>".
"<td>Original Deadline</td>".
"<td>Date Completed</td>".
"<td>SPOC Remarks</td>".
"<td>File Location</td>".
"<td>JUW MA Remarks</td>".
"<td>COSU Remarks</td>".
"<td>SMU Notes</td>".
"<td>SUBMITTED/PENDING</td>".
"<td> EDIT </td>".
"</tr></thead>";
while($row = $result->fetch_assoc()){
echo "<tr><td>".$row['APP_NUMBER']."</td>".
"<td>".$row['SPOC_ASSIGNED']."</td>".
"<td>".$row['BORROWER_NAME']."</td>".
"<td>".$row['APP_FINISH_DATE']."</td>".
"<td>".$row['DEVELOPER_PROJECT']."</td>".
"<td>".$row['COLLATERAL_ADDRESS_DETAILS']."</td>".
"<td>".$row['DEFERRED_DOCUMENT']."</td>".
"<td>".$row['DEFERRED_TYPE']."</td>".
"<td>".$row['ORIGINAL_DEADLINE']."</td>".
"<td>".$row['DATE_COMPLETED']."</td>".
"<td>".$row['SPOC_REMARKS']."</td>".
"<td>".$row['FILED_LOCATION']."</td>".
"<td>".$row['JUW_MA_REMARKS']."</td>".
"<td>".$row['COSU_REMARKS']."</td>".
"<td>".$row['SMU_NOTES']."</td>".
"<td>".$row['SUBMITTED_PENDING']."</td>".
"<td><a href='spoc_remarks.php?id=".$row['ID']."' class='lytebox'><image src='./images/pen.png' height=30 width=30></a></td>".
"</tr>";
}
}
?>
</div>
</div>

Try adding this someware just call removeDiv()
http://pastebin.com/f5EUwszt

You are hiding the div (with id=tab1) with onclick event of a submit button.
<input type="submit" id="cmdsearch" name="cmdsearch" value="Search" />
A submit button is supposed to use to submit a form. So when you click it, it submits the form data to 'beta_table.php' and the page is refreshed. If you want to hide the div (with id=tab1), you could use a button like
<input type="button" id="cmdsearch_btn" name="cmdsearch_btn" value="Search" />
You have to decide according to your need. When a page gets submitted using a submit button there's no point hiding a div because the page gets refreshed. I hope that helps.

Related

Syntax Highlighting PHP SQL

I have a page that searches a database. I am looking to get the data that the user enters in the search box to be highlighted in the search results.
The data from the user is stored in the variable '$criteria', and all contents of that variable I am aiming to highlight.
My PHP looks as follows:
<?php
session_start();
if ($_SESSION['loggedin'] != 1) {
header("Location: ../");
}
include("../php_includes/connection.php");
$queryErrorMessage = "";
?>
<html>
<head>
<title>Search Tasks</title>
<link rel="stylesheet" href="../css/bootstrap.min.css">
<script src="../js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<?php include("header.php"); ?>
<?php include("sidebar.php"); ?>
<div class="row">
<div class="col-md-9">
<div class="well well-lg">
<h3>Search Tasks</h3>
<hr>
<form method="post" action="">
<div class="input-group">
<input name="criteria" type="text" class="form-control" placeholder="What would you like to search for?...">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
Submit
</button>
</div>
</div>
</form>
<?php
//Run section of code if the POST criteria is provided for "criteria"
if(isset($_POST['criteria'])){
$criteria = mysqli_real_escape_string($db,$_POST['criteria']);
//If the user does not provide criteria to search, an error will be displayed.
if($criteria == ""){
$queryErrorMessage = "You did not provide any criteria";
GoTO errorMsg;
}
//Prepare sql statement checking each column with the criteria that is provided.
$sql = "SELECT * FROM taskinfo WHERE clientCompany LIKE '%".$criteria."%' OR clientName LIKE '%".$criteria."%' OR email LIKE '%".$criteria."%' OR contactNo LIKE '%".$criteria."%' OR details LIKE '%".$criteria."%'";
//Run sql query storing the records in $result
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result)>0){
//Get each row and put it into the array $row
echo '<h4>Displaying results for search criteria: <b>'.$criteria.'</b></h4>';
while($row = mysqli_fetch_array($result)){
$queryErrorMessage = "";
//Display the query results
?>
<div class="panel panel-default">
<div class="panel-body">
<h6><b>Task Details:</b></h6>
<?php echo $row['details'];?>
<h6><b>Task Information</b></h6>
<ul>
<li>Client Name: <?php echo $row['clientName'];?></li>
<li>Email: <?php echo $row['email'];?></li>
<li>Phone: <?php echo $row['contactNo'];?></li>
<li>Posted by <b><?php echo $row['postedBy'];?></b></li>
<li>Posted On: <b><?php echo $row['timeAdded']; ?></b></li>
</ul>
</div>
</div>
<?php
}
} else {
$queryErrorMessage = "No records found with your criteria.";
}
} else {
$queryErrorMessage = "Failed to perform query.";
}
}
//Check if there is an error message
//If true, echo the error to the user.
//
//Section of code is called errorMsg to
//Allow it to be called in the code above.
errorMsg:
if($queryErrorMessage != ""){
echo 'An Error Occurred: ';
echo $queryErrorMessage;
}
?>
</div>
</div>
</div>
</body>
</html>
If anyone can help, it'd be much appreciated.
this might help
<?php echo preg_replace_callback('/'.$criteria.'/i', function($matches){
return '<strong>' . $matches[0] . '</strong>';
}, $row['clientName']); ?>
it would make the search keyword in the content bold

Make select options disable after submitting the form

I've been trying this for awhile. I appreciate your help.
I've a form with two fields. 1- Username. 2- City.
Users can select their cities from the city select options (the cities come from the database).
However, if the user didn't find his/her city, he/she can check the checkbox to enable a text input to enter his/her city (and at the same time the select options will be disable).
The issue is, if the user writes new city, the select options will be disable (this is good), but when the user submits the form a and there was a validation issue (for example: empty username!), the form will go back with the following:
The city select options will be enable !!
The city text input will be disable (with sticky city name that the user entered) !!
So, how can I keep the city name in the text input enable with the value, and make the city select options disable??
This is my code:
<title> Form </title>
<link rel="icon" type="image/png" href="images/icon/anta_ana.png">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<div id="page-wrapper">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$city_name = $_POST['city_name'];
//errors handling :
$error = array();
if(empty($username)) $error[]= "<div class='alert alert-danger alert-dismissible input-sm' role='alert' dir='rtl' style='padding-top: 5px; padding-right: -5px; padding-bottom: 0px; padding-left: 0px'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
<strong style='color: #e62e00;'>Warning!</strong> Please write your name!
</div>";
if($city_name == 'all') $error[]= "<div class='alert alert-danger alert-dismissible input-sm' role='alert' dir='rtl' style='padding-top: 5px; padding-right: -5px; padding-bottom: 0px; padding-left: 0px'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
<strong style='color: #e62e00;'>Warning!</strong> Please selects a city!
</div>";
if(empty($error)) {
include("dbc.php");
$q = "INSERT INTO users (username,
city_name) VALUES
('$username',
'$city_name')";
$r = mysqli_query($dbc, $q);
if($r){
echo "<script>window.open('successfully_registered.php', '_self')</script>";
}
else{
echo "error";
}
}
else{
foreach ($error as $err){
echo $err;
}
}
}
?>
<form action="question.php" method="POST" name="" dir="rtl">
<!-- Userame -->
<div class="form-group">
<label class="control-label" style="float: right;"> Username </label>
<input type="text" class="form-control" placeholder="Username" name="username" value =
<?php if(isset($_POST['username'])) echo $_POST['username'] ?>>
</div>
<!-- City -->
<div class="form-group">
<label style="float: right;">City </label>
<?php
include("dbc.php");
$qm = "SELECT DISTINCT city_name FROM cities ORDER BY city_name";
$rm = mysqli_query($dbc,$qm);
while ($row = mysqli_fetch_array($rm)){
$cities_array[] = $row['city_name'];
}
echo '<select class="form-control border-input" name="city_name" id="city_name">';
echo '<option value="all"> All </option>';
foreach($cities_array as $cities){
$selected = '';
if($_POST['city_name'] == $cities) {
$selected = 'selected="selected"';
}
echo '<option value="'.$cities.'"'.$selected.'>'.$cities.'</option>';
}
echo '</select>';
?>
</div>
<!-- Another City? -->
<div class="form-group">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i> Didn't find you city? Check this box to enter your city: <input type="checkbox" id="another_city"/>
<input placeholder="Write your city here" class="form-control" type="text" name="new_city" id="new_city" disabled value =
"<?php if (isset($_POST['new_city'])) echo $_POST['new_city']; ?>" >
<script>
document.getElementById('another_city').onchange = function() {
document.getElementById('new_city').disabled = !this.checked;
if(document.getElementById('new_city').disabled){
$("#city_name").prop('disabled', false);
}
else{
$("#city_name").prop('disabled', true);
}
};
</script>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info btn-fill form-control" name="submit" value="Send"><i class="fa fa-paper-plane"></i> Send </button>
</div>
</form>
</div>
if you want to disable Select just use this code
$('select').attr('disabled','disabled');
first of all: your code is (principally) vulnerable to sql injection,
http://php.net/manual/de/security.database.sql-injection.php
second: the reason is fairly simple, you submit your form, check it in the BACKEND and redirect. The reason why option is enabled and textbox disabled is simply because the page is reloaded, and thats your default setting. you could pass a parameter indicating the failure in your url (like err=wrongArgument) or whatever) and disable the options box with javascript in that case.
If the problem only occurs because of validation you can first submit the form details via an ajax request. validate it and if there are no errors then submit them. If you were using jquery then you could do something like
$("#form-id").submit(function(e){
e.preventDefault();
$.ajax({
method: 'POST',
url: 'validate.php',
data: $(this).serialize(),
success: function(res){
if(res == "success") {
$(this).submit();
} else { // error }
},
fail: function(){
// error
}
})
})
one other thing that you could do is if you redirect to the current page after validation fails and pass a query string at the end that denotes that the user checked the checkbox or not. you have to give your checkbox a name for this so it gets submitted over as well when you submit the form.
if(isset($_POST['another_city']) and $_POST['another_city'] == "on") {
// header("Location: ...") redirects the page to the provided location
header("Location: question.php?checked=1"&city=".$city_name);
}
once you do this you will have to add code to check whether the $_GET['checked'] and $_GET['city'] are set or not. if they are set then you can set the provided values in the form using js like:
php:
$checked = "";
$city = "";
if(isset($_GET['checked']) and $_GET['checked'] == 1) {
$checked = "checked";
}
if(isset($_GET['city'])) {
$city= $_GET['city'];
}
html:
<div class="form-group">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i> Didn't find you city? Check this box to enter your city: <input type="checkbox" <?php echo $checked?> id="another_city"/>
<input placeholder="Write your city here" class="form-control" type="text" name="new_city" id="new_city" disabled value = "<?php echo $city; ?>" >

How to pass Variable One page to another in php

I have created dynamic button and i need to pass the button ID to another page when my button is clicked. I have pass it but it didn't work
Please give any solution
Here is my code for dash.php:
<?php
session_start();
function dash () {
include 'config.php';
$sql = "SELECT RoomNumber FROM roommaster ";
if ($result = mysqli_query($db, $sql)) {
$str = '';
while ($row = mysqli_fetch_array($result)) {
// generate array from comma delimited list.
$rooms = explode(',', $row['RoomNumber']);
//create the dynamic button and set the value.
foreach ($rooms as $v) {
$str .= "<a href = 'booking.php'?btn='btn'><input type='button' name='b1' id='btn' value='" . $v . "' /></a>";
}
}
return $str;
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
}
Here is my booking.php page:
<?php
if (isset($_POST['btn'])) {
$btn = $_POST['btn'];
echo $btn;
}
$sql = "SELECT RoomNumber FROM roommaster where RoomId=' " . $_GET['btn'] . " '";
if ($result = mysqli_query($db, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$RoomNumber = $row['RoomNumber'];
// $RoomType=$row['RoomType'];
// $Location=$row['Location'];
// $ChargesPerDay=$row['ChargesPerDay'];
}
// Free result set
mysqli_free_result($result);
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Customer book Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link href="css/book.css" rel="stylesheet">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</style>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.12.4.js"></script>
<script src="js/book1.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="head" id="link">
<div class="panel panel-primary" style="margin:20px;">
<div class="panel-heading">
<center><h3 class="panel-title"> Customer booking Form</h3></center>
</div>
<div class="panel-body">
<form method="post" action="">
<div class="col-md-12">
<div class="form-group col-md-12 ">
<label for="roomno">Room Number* </label>
<input type="text" class="form-control input-sm" name="RoomNumber" value="<?=$_GET['btn'];?>"required>
</div>
<div class="form-group col-md-6">
<label for="type">Room Type*</label>
<input type="text" class="form-control input-sm" name="RoomType" required >
</div>
<div class="form-group col-md-6">
<label for="location">Location*</label>
<input type="text" class="form-control input-sm" name="Location" required>
</div>
<div class="form-group col-md-12">
<label for="charges">Facilities*</label>
<input type="text" class="form-control input-sm" name="Facilities" required>
</div>
<div class="form-group col-md-12">
<label for="charges">ChargesPerDay*</label>
<input type="text" class="form-control input-sm" name="ChargesPerDay" required>
</div>
<div class="form-group col-md-4">
<label for="customer name">First Name*</label>
<input type="text" class="form-control input-sm" name="FirstName" required>
</div>
</div>
</form>
</div>
</body>
</html>
Try to use $_GET instead of $_POST
if (isset($_GET['btn'])) {
$btn = $_GET['btn'];
echo $btn;
}
Try linking using a form. BUTTONID should be the value to pass. $str should be:
<form action='booking.php' method='POST'>
<input type='hidden' value='BUTTONID' name='bttn'>
<input type='submit' value='".$v."'>
</form>
And then get the value of the hidden field as you already did...
$if (isset($_POST['bttn'])) {
$btn = $_POST['bttn'];
echo $btn;
}
i have modified script of dash.php and booking.php files. Please copy and paste this script.
dash.php file
<?php
session_start();
function dash(){
include 'config.php';
$sql = "SELECT RoomNumber FROM roommaster ";
if($result = mysqli_query($db, $sql))
{
$str = '';
while($row = mysqli_fetch_array($result))
{
// generate array from comma delimited list
$rooms = explode(',', $row['RoomNumber']);
//create the dynamic button and set the value
foreach ( $rooms as $v )
{
$str .= "<input type='button' name='b1' id='btn' value='".$v."' />";
}
}
return $str;
}
else {
echo "ERROR: Could not able to execute $sql. " .mysqli_error($db);
}
mysqli_close($db);
booking.php file
$sql = "SELECT RoomNumber FROM roommaster where RoomId=' " .$_GET['btn']." '";
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$RoomNumber=$row['RoomNumber'];
//$RoomType=$row['RoomType'];
// $Location=$row['Location'];
// $ChargesPerDay=$row['ChargesPerDay'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
To pass little data from one page to another page use parameters in the URL as below is parameter with the value you want to pass to next page as:
Click Button
Then on the anotherpage.php use $_GET to get the value passed by the URL as:
$val = isset($_GET['parameter']) ? $_GET['parameter'] : NULL;
Then use the $val for other processing. I think this may can help you to understand how to pass data from one page to another page simply.
Try to use $_REQUEST by that you can get both GET and POST values.In booking.php print the array like below:
print_r($_REQUEST);
if (isset($_REQUEST['btn'])) {
$btn = $_REQUEST['btn'];
echo $btn;
}

can I get text from html and put it into variable in php without submitting a form?

I have a form in html:
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
and I want to get the value of this input in php without submitting it in a form.
this is my javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
pName= $(this).attr("name");
console.log(pName);
});
});
My php:
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
what I want is. you click on the picture,
1.the value of the name attribute of the picture is going to be saved into the variable pName (javascript),
2.it then goes into the form and changes the value of the form to the variable pName (javascript),
3.php picks up the value of the form (which should now be equal to pName),
4.then stores it into a variable $pName (php).
5.I also want $pName (php) to be globally used throughout all the pages of the website.
edit
this is my index page:
<?php
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<a href='project.php'>" ."<img name=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>". "</a>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
what I want: click on the image then you get sent to the project page where (php) $pName is equal to the value of (javascript) pName
project page:
<?php
$newRecord = null;
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
<?php
echo $newRecord;
?>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
HTML:
do you have more then 1 image on page? its better if you add ID in image. No need for form and hidden fields for what you want done.
make sure your img has ID like <img id="imageID"...
JavaScript:
var pName= null;
$(document).ready(function(){
$('#imageID').click(function(){
pName= $(this).attr("name");
$.post("project.php", { pNameChange: pName },
function(data) {
// do something here.
});
});
});
above code should work as expected. Now in project.php > $_POST['pNameChange'] should receive the value of pName (image's name attr).
I don't understand what you want when you said $pName available globally on all pages. Please elaborate further, may be look into storing it as cookie/session?
EDIT:
Consider using session to pName value... by simple starting/resuming session in start of file:
<?PHP
session_start();
and then...
to set/update value:
if(isset($_POST["pNameChange"]))
$_SESSION["pName"] = $_POST["pNameChange"];
and then use $_SESSION["pName"] instead of $pName on all pages.
Try Ajax method in jQuery , hope it solves your problem
https://api.jquery.com/jQuery.ajax/
or
https://api.jquery.com/jQuery.post/
Actually, you do not need AJAX for this, all your index.php does it passes the image's name to project.php so try:
In index.php:
<form name='form1' method="post" action='project.php'> <!-- form attributes given -->
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
Javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
//onclick of image, we will save the image name into the hidden input
//and submit the form so that it goes to project.php
$('input[name="pNameChange"]').val($(this).attr("name"));
$('form1').submit()
});
});
And in your project.php:
//now project.php can get the posted value of 'pNameChange'
//There is no input field with `name`->`value`, so $_POST['value'] is invalid.
$pName = isset($_POST['pNameChange']) ? $_POST['pNameChange'] : '';
And if you need this value across multiple pages, global will not work, use sessions.
ok this "additional" answer is to focus on session only. use the codes for client-end from my previous answer and try this on server-end.
index.php Page:
<?php
session_start();
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : '';
project.php Page:
<?php
session_start();
$newRecord = null;
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : null;
if(is_null($pName) && isset($_POST['pNameChange'])) {
$_SESSION['pNameChange'] = $_POST['pNameChange'];
$pName = $_POST['pNameChange'];
}
hope it helps

Jquery load() puts display and opacity in element style

I have an html that, by AJAX, fetches data from a php file and shows a table with the content ofthe database.
In another file, I try to call load(initial.html) to a div and the code shows up fine, but when I hit the button to retrieve the table, the element style of the div where the tabçe will be written shows up automatically "display: none; opacity: 0". And than in that table I have a tablesorter and it doesn't work.
But if I enter the original page all works, but I can't put it work if I load the html to another file.
Anyone can help me?
Thanks very much
EDIT:
I tried other way, but now the ("#teste").on('submit') doesn't work.
and if I put the code in the main page and forget the load() it works fine. Why is that?
Thank you for the help
Here is the code:
the main page, when o click link_1 I call load() to populate the div id="principal"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Teste </title>
</head>
<link rel="stylesheet" href="css/index.css" />
<link rel="stylesheet" href="css/procura.css" />
<link rel="stylesheet" href="css/theme.blue.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="js/procura.js"></script>
<script type="text/javascript" src="js/jquery.metadata.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.widgets.js"></script>
<body>
<div id="banner-image">
<img src="images/logo.jpg" />
</div>
<div id="banner-content">
<a id="link_1" href="">Procurar Colaborador</a>
<a id="link_2" href="">Confirmação de Colaboradores</a>
</div>
<div id="principal">
</div>
</body>
</html>
The Html that I call called procura.html
<form action="" id="teste" method="post" enctype="multipart/form-data">
<div id="itemRows">
<p>
<select name="tipo_procura[]" >
<option value="" selected></option>
<option value="loja_integracao">Loja de Integração</option>
<option value="nome_completo">Nome</option>
</select>
<input name="valor_procura[]" type="text" maxlength="255" size="50" />
<input onclick="addRow(this.form);" class="form_button" type="button" value="Adicionar Procura" />
</p>
</div>
<input id="submit_button" type="submit" value="Procurar" />
</form>
<div class="result" id="result">
</div>
THE JS file procura.js
$(document).ready(function() {
$("#link_1").click(function(event) {
$("#principal").load("procura.html");
event.preventDefault();
});
$('#teste').on('submit', function(event) {
$.ajax({
url : 'procura_colaborador.php',
data : $(this).serialize(),
type : 'POST',
success : function(data) {
console.log(data);
$("#result").fadeOut('slow', function() {
$(this).html(data);
}).fadeIn("slow");
}
});
event.preventDefault();
});
});
var rowNum = 0;
function addRow(frm) {
rowNum++;
var row = '<p id="rowNum' + rowNum + '"><select name="tipo_procura[]" ><option value="" selected></option><option value="loja_integracao">Loja de Integração</option><option value="nome_completo">Nome</option></select><input name="valor_procura[]" type="text" maxlength="255" size="50" /><input type="button" value="Remover Procura" class="form_button" onclick="removeRow(' + rowNum + ');"></p>';
jQuery('#itemRows').append(row);
}
function removeRow(rnum) {
jQuery('#rowNum' + rnum).remove();
}
And the PHP file
$query = "SELECT * FROM colaboradores";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
echo '<table id="tabela_resultados" class="tablesorter-blue">';
echo '<thead><tr><th>Loja de Integração</th><th>Nome</th><th>Telemóvel</th><th>NIF</th><th>Data de Nascimento<th>Nacionalidade</th><th>Acção</th></tr></thead><tbody>';
while ($gear = mysqli_fetch_array($result)) {
echo "<tr><td>";
echo $gear['loja_integracao'];
echo "</td><td>";
echo $gear['nome_completo'];
echo "</td><td>";
echo $gear['num_tlm'];
echo "</td><td>";
echo $gear['num_nif'];
echo "</td><td>";
echo $gear['data_nascimento'];
echo "</td><td>";
echo $gear['nacionalidade'];
echo "</td><td><a href=''>Contrato</a></td></tr>";
}
echo '</tbody></table>';
echo '<script type="text/javascript">$("#tabela_resultados").tablesorter();</script>';
if i understand you correctly
try to change your json function to retrive html data , because you cant't retrive json when you
do echo in php file if you want to retrive your table you must add to json function , dataType: "html"
$('#teste').on('submit', function(event) {
$.ajax({
url : 'procura_colaborador.php',
data : $(this).serialize(),
type : 'POST',
dataType: "html",
success : function(data) {
console.log(data);
$("#result").fadeOut('slow', function() {
$(this).html(data);
}).fadeIn("slow");
}
});
event.preventDefault();
});
});

Categories

Resources