Get Select Value in textfield As Well As On Change - javascript

I'm just learning Mysql/PHP and I'm trying to update a textfield depending on the selected value from the dropdownlist. I have read through several tutorials, and tried to apply them, but I cannot get this working...
Dont mind my messy code, will clean later !!!
Page with dropdown list and texfields:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
if (isset($_SESSION['logged_in'])) {
include("/includes/connect.php");
$sql="SELECT id, nr, model, serienummer, capaciteit, persoon, opmerking, datumuitgeleend, datumretour FROM ipads WHERE uitgeleend='Ja' ORDER BY nr";
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
if(isset($_POST['btnAdd'])) {
$id=$_REQUEST['id'];
$persoon=$_POST['persoon'];
$datumuitgeleend=$_POST['datumuitgeleend'];
$datumretour=$_POST['datumretour'];
$opmerking=$_POST['opmerking'];
$sql="UPDATE ipads SET uitgeleend='Ja', persoon='$persoon', datumuitgeleend='$datumuitgeleend', datumretour='$datumretour', opmerking='$opmerking' WHERE id='$id'";
$result=$db->query($sql);
header("location:index.php");
}
include("/includes/get_header.php");
?>
<h1 class="page-title">iPad uitlenen</h1>
<ul class="breadcrumb">
<li>Home </li>
<li class="active">Nieuw</li>
</ul>
</div>
<form id="gegevensForm" class="col-xs-4" form method="POST" action="ipad-uitlenen.php">
<div class="form-group">
<label>Selecteer leen iPad</label>
<select name="id" class="form-control">
<option value="">Selecteer een leen iPad</option>
<?php foreach($result as $row): ?>
<option data-datumuitgeleend="<?= $row['datumuitgeleend']; ?>" data-datumretour ="<?= $row['datumretour']; ?>" data-opmerking="<?= $row['opmerking']; ?>" data-persoon="<?= $row['persoon']; ?>" value="<?= $row['id']; ?>"><?= $row['nr']; ?> / <?= $row['serienummer']; ?> / <?= $row['model']; ?> / <?= $row['capaciteit']; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Naam</label>
<input type="text" class="form-control" name="persoon" value="" />
</div>
<div class="form-group">
<label>Datum uitgeleend</label>
<input type="text" id="datepicker" class="form-control" name="datumuitgeleend" value="" />
</div>
<div class="form-group">
<label>Datum retour</label>
<input type="text" id="datepicker1" class="form-control" name="datumretour" value="" />
</div>
<div class="form-group">
<label for="comment">Opmerking</label>
<textarea class="form-control" rows="5" id="comment" name="opmerking" value=""></textarea>
</div>
<button class="btn btn-primary pull-right" name="btnAdd" type="submit"><i class="fa fa-save"></i> Opslaan</button>
<input type="button" name="btnCancel" value="Annuleer" class="btn btn-primary pull-left">
<?php
include('../includes/get_footer.php');
?>
</form>
<?php
}
?>
get_header.php
<html lang="en"><head>
<meta charset="utf-8">
<title>Admin Control Panel</title>
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="lib/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="lib/font-awesome/css/font-awesome.css">
<link rel="stylesheet" type="text/css" href="stylesheets/theme.css">
<link rel="stylesheet" type="text/css" href="stylesheets/premium.css">
<link rel="stylesheet" href="./resources/demos/style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="lib/jQuery-Knob/js/jquery.knob.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.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>
<script type='text/javascript'>
$(document).ready(function() {
$("select[name='id']").on('change',function() {
$("input[name='persoon']").val($(this ).children(":selected").data( "persoon" ));
$("input[name='datumretour']").val($(this ).children(":selected").data( "datumretour" ));
$("input[name='datumuitgeleend']").val($(this ).children(":selected").data( "datumuitgeleend" ));
$("input[name='opmerking']").val($(this ).children(":selected").data( "opmerking" ));
; })
;})
</script>
</head>
<body class=" theme-blue">
<style type="text/css">
#line-chart {
height:300px;
width:800px;
margin: 0px auto;
margin-top: 1em;
}
.navbar-default .navbar-brand, .navbar-default .navbar-brand:hover {
color: #fff;
}
</style>
<script type="text/javascript">
$(function() {
var uls = $('.sidebar-nav > ul > *').clone();
uls.addClass('visible-xs');
$('#main-menu').append(uls.clone());
});
</script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
$( "#datepicker1" ).datepicker();
});
</script>
<script type="text/javascript">
$(function() {
$(".knob").knob();
});
</script>
<div class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="" href="index.html"><span class="navbar-brand"><span class="glyphicon glyphicon-phone"></span> iPad Control Panel</span></a></div>
<div class="navbar-collapse collapse" style="height: 1px;">
<ul id="main-menu" class="nav navbar-nav navbar-right">
<li class="dropdown hidden-xs">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-user padding-right-small" style="position:relative;top: 3px;"></span>
<i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu">
<li class="dropdown-header">Admin Panel</li>
<li><a tabindex="-1" href="logout.php"><i class="glyphicon glyphicon-off"></i> Logout</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div class="sidebar-nav">
<ul>
<li><img src="./images/ipad.png" width="16" height="16"> Overzicht iPads</li>
<li><ul class="dashboard-menu nav nav-list collapse in">
<li><span class="fa fa-caret-right"></span> Beschikbaar</li>
<li><span class="fa fa-caret-right"></span> Uitgeleend</li>
<li><span class="fa fa-caret-right"></span> Geschiedenis</li>
</ul></li>
</div>
<div class="content">
<div class="header">
<div class="stats">
</div>
Table :
click here for table
Site :
Click here for example

To get the on change value with php you have you reload the page if the select box changes a better alternative would be to use js.
You could do something like:
$("select[name='id']").on('change',function()
{$("input[name='persoon']").val($(this).val()); //this will put the select value in text field
})
the above code will put select $row['id'] in text box if you want $row['persoon'] to be updated you might want to update your option html first to have $row['persoon'] as any of the attribute something like
<option data-datumuitgeleend="<?= $row['datumuitgeleend']; ?>" data-datumretour ="<?= $row['datumretour']; ?>" data-opmerking="<?= $row['opmerking']; ?>" data-persoon="<?= $row['persoon']; ?>" value="<?= $row['id']; ?>"><?= $row['nr']; ?> / <?= $row['serienummer'];
an you javascript should update this value like use:
$("select[name='id']").on('change',function( { $("input[name='persoon']").val($(this ).children(":selected").data( "persoon" ));
$("textarea[name='opmerking']").html($(this ).children(":selected").data( "opmerking" ));
$("input[name='datumretour']").val($(this ).children(":selected").data( "datumretour" ));
$("input[name='datumuitgeleend']").val($(this ).children(":selected").data( "datumuitgeleend" ));
})
If you're not using jQuery Way to do in plain js:
var select =document.getElementsByName('id')[0];
select.addEventListener("change", function() {
var options = this.options;
var persoon = options[options.selectedIndex].getAttribute('data-persoon');
document.getElementsByName('persoon')[0].value = attr;
var datumuitgeleend= options[options.selectedIndex].getAttribute('data-datumuitgeleend');
document.getElementsByName('datumuitgeleend')[0].value = attr;
var opmerking= options[options.selectedIndex].getAttribute('data-opmerking');
document.getElementsByName('opmerking')[0].value = attr;
var datumretour = options[options.selectedIndex].getAttribute('data-datumretour');
document.getElementsByName('datumretour')[0].value = attr;
}
And also change your sql select statement to have datumretour, datumuitgeleend,
$sql="SELECT id, nr, model, serienummer, capaciteit, datumretour, datumuitgeleend, persoon, opmerking FROM ipads WHERE uitgeleend='Ja' ORDER BY nr";
Hope it helps!

I did mind the messy code, but mostly the lack of minimum code to reproduce the problem you are facing, so forgive me if I did not distill your question properly.
I think the problem you describe boils down to "how to populate a <textarea> whenever the chosen <select> option changes?"
$(function() {
var select = $('select[name="pickAnOption"]');
function update(select) {
var value = select.val(),
textarea = $('textarea[name="describeTheOption"]');
if (value) {
textarea.attr('disabled', false).text('You picked ' + value);
}
else {
textarea.attr('disabled', true).text('Pick an option first');
}
}
select.on('change', function() {
update(select);
});
update(select);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Choose wisely:
<select name="pickAnOption">
<option value="">Pick one</option>
<option value="a">option A</option>
<option value="b">option B</option>
<option value="c">option C</option>
</select>
<br>
Gives some options:
<textarea name="describeTheOption"></textarea>
</form>
As to explain what is going on, here's the flow of the javascript broken down into pieces
$(function() {, this function is executed when the document is ready (all elements are available, assets such as images/stylesheet may or may not be loaded yet)
var select = ..., store a reference to the <select> element as we will be using it multiple times and don't fancy to look it up constantly
function update() {..}, as we want to update both on changes and the first time the page is loaded (as some browsers remember form state across page refresh), we want a function to call for these occasions
var value = select.val(), take the selected option value
(var) textarea = $(..), store a reference to the textarea
if (value), if an option with a non-false(-ish) value (in this example: value is not the empty value we've added to the 'Pick one' option), execute the code in this block
$(textarea).attr('disabled', false) make sure the textarea becomes editable (not disabled)
.text('You picked ' + value), set the contents of the textarea to display the option value
else, pretty much the same as above, but acting on a non-value (disabling the textarea, setting a default text).
select.on('change', function() {..}), listen to change events on the <select> element and trigger the update when another option is picked
update(select), initially trigger the update to ensure the textarea is on par with the selected option.
It is a matter of taste if you like to have the initial update (I prefer to do this), it would save one additional function if you don't.
Or you could use an alternative notiation, should you want to prevent a stand-alone function, for example
$('select[name="pickAnOption"]')
.on('change', function() {
// update code here.
})
.change(); // invoke the change handler immediately

Related

How to search dropdown with input on PHP

hope all be will. I face to like this problem anyone can help me.
I get the value of dropdown and I put it to input, but I am unable to search it.
I used from jQuery to get the value from bootstrap dropdown to give for input.
<!-- HTML Code With Form -->
<!-- Basic dropdown -->
<form method="post" enctype="multipart/form-data" action="team.php"
class="form-inline active-purple-3 active-purple-4" style="width:400px;
margin-top:-50px; margin-left:125px; ">
<button id="sb" class="btn btn-primary dropdown-toggle mr-4" type="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
style="margin-top:20px; margin-left:-140px;">Search By</button>
<div class="dropdown-menu" id="dm" style="margin-left:89px; margin-
top:-963px;">
<a class="dropdown-item" id="dl" href="#" value="ID">BY ID</a>
<a class="dropdown-item" id="dl" href="#" value="Name">Name</a>
<a class="dropdown-item" id="dl" href="#" value="Positon">Position</a>
</div>
<input type='hidden' name='thenumbers'>
<!-- Basic dropdown -->
<!-- Search form -->
<i class="fa fa-search" aria-hidden="true" style="margin-top:15px;"></i>
<input name="txtSearch" class="form-control form-control-sm ml-3 w-75"
id="in" type="text" placeholder="Search" style=" margin-top:15px; border-
radius:5px 5px 5px 5px;" aria-label="Search">
<button type="Submit" name="searchrec" class="btn btn-primary"
style="margin-left:365px; margin-top:-55px;">Search</button>
</form>
<!-- jQuery Code -->
<script>
$(document).ready(function(){
$('#dm a').on('click', function(){
$('#sb').text($(this).text());
});
});
</script>
<script>
$(function(){
//Listen for a click on any of the dropdown items
$("#dm a").click(function(){
//Get the value
var value = $(this).text();
//Put the retrieved value into the hidden input
$("input[name='thenumbers']").val(value);
});
});
</script>
<!-- jQuery Code End -->
<!-- PHP Code -->
<?php
include "Config.php";
if(isset($_POST['searchrec']))
{
$txtSearch=$_POST['txtSearch'];
$column=$_POST['thenumbers'];
if($column == "BY ID")
{
$query1="SELECT * FROM ourteam WHERE id LIKE '%$txtSearch%'";
$result1=mysqli_query($db,$query1);
$count=mysqli_num_rows($result1);
if($count == 0)
{
}else{
while($rowr=mysqli_fetch_array($result1))
{
$id=$rowr['id'];
$name=$rowr['name'];
echo "<script>alert($name);</script>";
}
}
This PHP code is just for ID and I used elesif statement also for other entities.
First, get the values not the text:
//Get the value
var value = $(this).attr('value'); // instead of text
Then, map it on the server side
$allowed_columns = ['id', 'name', 'position'];
$column = $_POST['thenumbers'];
$txtSearch = $_POST['txtSearch'];
// Check the field name
if (!in_array($column, $allowed_columns)) {
// Throw some exception, or do whatever you want
}
// Sanitize the value
$txtSearch = mysqli_real_escape_string($txtSearch);
$query1="SELECT * FROM ourteam WHERE `$column` LIKE '%$txtSearch%'";
// ...

Submission form is not properly submitting information to SQL (PHP and JS)

I've made a jobs post form in which a user fills out and after submitting the form, the job should be displayed on the same page under it. for some reason, the job description and job location data that's returned comes up as undefined. I'm thinking it might be because they're a drop-down list and text area? but I can't see to fully comprehend why the error shows up. Also, how would I go about submitting radio buttons to a database? would they need specific values?
Below is the jobs.html page
<?php
//allow the config
define('__CONFIG__', true);
//require the config
require_once "inc/config.php"; //possibly have to change the location
Page::ForceLogin();
?>
<!DOCTYPE html>
<html>
<head>
<!-- UIKit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.24/css/uikit.min.css" />
<link rel="stylesheet" href="style.css">
<title>Login Page</title>
<base href="/"/>
<nav class="uk-navbar-container uk-margin" uk-navbar>
<div class="uk-navbar-left">
<a class="uk-navbar-item uk-logo" href="comp1687/index.php"><img src="/comp1687/jobswatchsmall.png" alt="sitelogo"></a>
<ul class="uk-navbar-nav">
<li>
<a href="comp1687/index.php">
<span class="uk-icon uk-margin-small-right" ></span>
<b>Home Page</b>
</a>
</li>
<li>
<a href="comp1687/jobs.php">
<span class="uk-icon uk-margin-small-right" ></span>
<b>Jobs</b>
</a>
</li>
</div>
<div class="uk-navbar-center">
<div class="uk-navbar-item">
<form action="javascript:void(0)">
<input class="uk-input uk-form-width-small" style="width:350px; border-radius: 10px; " type="text" placeholder="Input">
<button class="uk-button uk-button-default" style="border-radius: 10px;">Button</button>
</form>
</div>
</div>
<div class="uk-navbar-right">
<ul class="uk-navbar-nav">
<li>
<a href="comp1687/about.php">
<span class="uk-icon uk-margin-small-right" ></span>
<b>About Us</b>
</a>
</li>
<li>
<a href="comp1687/dashboard.php">
<span class="uk-icon uk-margin-small-right" ></span>
<b>Profile Page</b>
</a>
</li>
</div>
</nav>
</head>
<body>
<div class="uk-section uk-container">
<div class="uk-grid uk-child-width-1-3#s uk-child-width-1-1" uk-grid></div>
<h2><b><center>Jobs</center></b></h2>
<div style="border: 3px solid #ddd; border-radius: 10px; padding: 10px;">
<h4><center>Welcome to the job browsing section. You are able to browse the available jobs below, and if desired, you may post your own job!</center></h4>
<div class="jobspost" style="border: 3px solid #ddd; border-radius: 10px; padding: 10px;">
<h4><center><b>Post a job</b></center></h4>
<form class="uk-form-stacked js-jobs">
<fieldset class="uk-fieldset">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Job title:</b></label>
<input id="jobTitle" class="uk-input" type="text" required placeholder="Insert the name of the job">
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Skills required:</b></label>
<input id="jobSkills" class="uk-input" type="text" required placeholder="Insert the skills needed for the job">
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Job description:</b></label>
<textarea id="jobDescription" class="uk-textarea" rows="5" required placeholder="Insert a description of the job"></textarea>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Images (If necessary):</b></label>
<input id="jobImage" class="uk-button uk-button-default" type="file" name="jobImage" >
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Job location:</b></label>
<select id="jobLocation" required class="uk-select">
<option>-Select a region of london for the jobs location-</option>
<option>-------CENTRAL-------</option>
<option>Camden</option>
<option>City of London</option>
<option>Kensington and Chelsea</option>
</select>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Job reward:</b></label>
<input id="jobReward" class="uk-input" required type="text" placeholder="Insert the amount of credits this job is worth">
</div>
<div class="uk-margin uk-grid-small uk-child-width-auto uk-grid">
<label class="uk-form-label" for="form-stacked-text"><b>Job status:</b></label>
<label><input id="jobStatus" class="uk-radio" type="radio" name="radio2" checked> Available</label>
<label><input id="jobStatus" class="uk-radio" type="radio" name="radio2"> Completed</label>
</div>
<center><button id="jobbtn" name="jobbtn" class="uk-button uk-button-default" type="submit"><b>SUBMIT JOB</b></button></center>
<br>
</fieldset>
</form>
</div>
<br>
<div class="jobsbrowse" style="border: 3px solid #ddd; border-radius: 10px; padding: 10px;">
<h4><center><b>Browse the jobs</b></center></h4>
</div>
</div>
</div>
<?php require_once "inc/footer.php"; ?> <!-- possibly have to change the location -->
</body>
</html>
The code below is the ajax/jobs
<?php
//allow the config
define('__CONFIG__', true);
//require the config
require_once "../inc/config.php"; //possibly have to change the location
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//Always return JSON format
//header('Content-Type: application/json');
$return = [];
$jobTitle = Filter::String($_POST['jobTitle']);
$jobSkills = Filter::String($_POST['jobSkills']);
$jobDescription = Filter::String($_POST['jobDescription']);
$jobLocation = Filter::String($_POST['jobLocation']);
$jobReward = Filter::String($_POST['jobReward']);
$jobStatus = Filter::String($_POST['jobStatus']);
// make sure the user adds a job.
$addJob = $con->prepare("INSERT INTO jobs(jobTitle, jobSkills, jobDescription, jobLocation, jobReward, jobStatus) VALUES(:jobTitle, :jobSkills, :jobDescription, :jobLocation, :jobReward, :jobStatus)");
$addJob->bindParam(':jobTitle', $jobTitle, PDO::PARAM_STR);
$addJob->bindParam(':jobSkills', $jobSkills, PDO::PARAM_STR);
$addJob->bindParam(':jobDescription', $jobDescription, PDO::PARAM_STR);
$addJob->bindParam(':jobLocation', $jobLocation, PDO::PARAM_STR);
$addJob->bindParam(':jobReward', $jobReward, PDO::PARAM_STR);
$addJob->bindParam(':jobStatus', $jobStatus, PDO::PARAM_STR);
$addJob->execute();
// return the proper information back to Javascript to redirect us.
echo json_encode($return, JSON_PRETTY_PRINT);
} else {
//Kill the script. Redirect the user.
exit('Invalid URL');
}
?>
The code below is the JS responsible for submittion.
.on("submit", "form.js-jobs", function(event) {
event.preventDefault();
var _form = $(this);
var _error = $(".js-error", _form);
var jobObj = {
jobTitle: $("input[id='jobTitle']", _form) .val(),
jobSkills: $("input[id='jobSkills']", _form) .val(),
jobDescription: $("input[id='jobDescription']", _form) .val(),
jobLocation: $("input[id='jobLocation']", _form) .val(),
jobReward: $("input[id='jobReward']", _form) .val(),
jobStatus: $("input[id='jobStatus']", _form) .val(),
};
if(jobObj.length < 1) {
_error
.text("Please fill in all fields.")
.show();
return false;
}
// Assuming the code gets this far, we can start the ajax process
_error.hide();
console.log(jobObj)
$.ajax({
type: 'POST',
url: 'comp1687/ajax/jobs.php', //possibly have to change the location
data: jobObj,
dataType: 'json',
async: true,
})
.done(function ajaxDone(data) {
// Whatever data is
if(data.redirect !== undefined) {
window.location.reload();
console.log('data');
} else if(data.error !== undefined) {
_error
.html(data.error)
.show();
console.log('data');
}
})
.fail(function ajaxFailed(e) {
//this failed
console.log(e);
})
.always(function ajaxAlwaysDoThis(data) {
//always do
console.log('Always');
})
return false;
})

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; ?>" >

jquery hide div when click search button and display result

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.

Submit form refresh the page

I have an index.html
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>League of Legends Straw Poll</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">Game Straw Poll</h1>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<!-- FORM -->
<form name="submitForm" id="submitForm" action="process.php" method="post">
<div class="row">
<div class="col-md-12">
<!-- GAME -->
<select class="form-control" id="game-group" name="game" onchange="ChangeBackground();">
<option selected disabled>Select your Game...</option>
<option value="League_of_Legends">League of Legends</option>
<option value="Heartstone">Hearthstone</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<!-- QUESTION -->
<div class="input-group" id="question-group">
<input type="text" class="form-control" name="question" id="question" placeholder="Start typing your question...">
<span class="input-group-addon">
<i class="glyphicon glyphicon-question-sign"></i>
</span>
</div>
</div>
</div>
<br>
<div class="row">
<!-- OPTIONS -->
<div class="form-group form-group-options col-md-12 col-sm-12 col-xs-12">
<div class="input-group input-group-option col-md-12 col-sm-12 col-xs-12" id="options-group">
<input type="text" name="option[]" id="option" class="form-control" placeholder="Options...">
<span class="input-group-addon input-group-addon-remove">
<span class="glyphicon glyphicon-remove"></span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<!-- CHOICE -->
<div class="checkbox" id="choice-group">
<label>
<input type="checkbox" id="choice" name="choice" value="Yes">Allow multiple choice
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-lg pull-left" name="submit_button" id="submit_button" data-toggle="modal" data-target="#myModal">Create Poll</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Poll created</h4>
</div>
<div class="modal-body">
<p>Share it: http://gamepoll.net/<?php echo $rand_value; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary">Invia</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type='text/javascript' src='js/addfield.js'></script>
<script type='text/javascript' src='js/changebackground.js'></script>
<script type='text/javascript' src='magic.js'></script>
</body>
</html>
An AJAX function into a js script
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'game' : $('input[name=game]').val(),
'question' : $('input[name=question]').val(),
'option' : $('input[name=option[]]').val(),
'choice' : $('input[name=choice]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for game ---------------
if (data.errors.game) {
$('#game-group').addClass('has-error'); // add the error class to show red input
$('#game-group').append('<div class="help-block">' + data.errors.game + '</div>'); // add the actual error message under our input
}
// handle errors for question ---------------
if (data.errors.question) {
$('#question-group').addClass('has-error'); // add the error class to show red input
$('#question-group').append('<div class="help-block">' + data.errors.question + '</div>'); // add the actual error message under our input
}
// handle errors for option ---------------
if (data.errors.option) {
$('#option-group').addClass('has-error'); // add the error class to show red input
$('#option-group').append('<div class="help-block">' + data.errors.option + '</div>'); // add the actual error message under our input
}
// handle errors for choice ---------------
if (data.errors.choice) {
$('#choice-group').addClass('has-error'); // add the error class to show red input
$('#choice-group').append('<div class="help-block">' + data.errors.choice + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
And a process.php
<?php
//Include configuration file
include('includes/config.php');
//Define variables
$question=$_POST['question'];
$game=$_POST['game'];
$option=$_POST['option'];
$choice=$_POST['choice'];
//Generate random number
$rand_value=rand();
//Create temporary folder
mkdir($rand_value);
//Copy page of Ask Poll
copy('page.php', $rand_value . '/page.php');
rename($rand_value . '/page.php', $rand_value . '/index.php');
//Add data into database
mysql_connect($db_host, $db_username, $db_password) or die ("Errore di connessione!");
mysql_select_db($db_name) or die ("Impossibile selezionare database!");
$sql1="CREATE TABLE `" . $rand_value . "` (Question VARCHAR(200), Options VARCHAR(200), Choice INT(11))";
mysql_query($sql1) or die ("Impossibile eseguire la query!");
//Count number of Options available
$count=count($option);
for ($i=0; $i<($count-1); $i++)
{
${$sql . $i}="INSERT INTO `" . $rand_value . "` (Question, Options, Choice) VALUES ('$question', '$option[$i]', '$choice')";
mysql_query(${$sql . $i});
}
?>
But when i send the form, the page redirect me to process.php
I don't want that the site refresh the page
EDIT
Werner, I followed your suggestion adding preventDefault but it doesn't work :(
You have an syntax error in your magic.js file. You should start by enabling your console and watch it for errors.
Uncaught Error: Syntax error, unrecognised expression: input[name=option[]]
That is what I could read when pressing the submit button and then Escape just after that to stop the submit.
The problem lies the part where you create your formData. (Which you can actually create a lot easier with http://api.jquery.com/serialize/)
You have a typo on line 15. Notice the extra brackets? You are not supposed to add the brackets even though they are in the name of the field. I recommend you to use the Serialize solution or at least select the fields using their IDs (that's what they are basically for).
$('input[name=option[]]') // Not valid
$('#option') // Better way to select a field
Hope this will get you in the right direction.

Categories

Resources