I know php is a server-side language and html a client-side language and to do this i would use javascript but i don't know how to do.
Can someone help me to write the script called changeFunction()?
This is my form in index.php:
<form method="POST">
<div class="row"style="margin-top: 5%;">
<div class="col-3">
</div>
<div class="col-6">
<label for="inputUsername">Insert username</label>
<input type="text" class="form-control" name="inputUser" style="margin-bottom: 2%">
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">Convert account type to: </label>
</div>
<select class="custom-select" id="inputGroupSelect01" name="inputSelected">
<option selected>Choose...</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<button type="button" class="btn btn-outline-primary" onclick="changeFunction()">Submit</button>
</div>
</div>
<div class="col-3">
</div>
</div>
</form>
This is my query in query.php:
<?php
$var1= $_POST["inputGroupSelect01"];
$var2= $_POST["inputUser"];
require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
?>
I hope this is the solution you want .
First add the following div in you html form <div id='resultDiv' ></div>
so your html form code be like this
<form method="POST" >
<div class="row"style="margin-top: 5%;">
<div class="col-3">
<h2>Testing Form</h2>
</div>
<div class="col-6">
<label for="inputUsername">Insert username</label>
<input type="text" class="form-control" name="inputUser" style="margin-bottom: 2%" id="inputUser">
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">Convert account type to: </label>
</div>
<select class="custom-select" id="inputGroupSelect01" name="inputSelected">
<option selected>Choose...</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<button type="button" class="btn btn-outline-primary" onclick="changeFunction()">Submit</button>
</div>
<!-- this need to be added -->
<div id='resultDiv' ></div>
</div>
<div class="col-3">
</div>
</div>
</form>
Second add the jQuery and following script to your code
two jquery variable define userName and role which is later passed as data
and if server response is SUCCESS then success condition executed or you can send data or particular error message by setting ERROR with YOUR ERROR TEXT
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type='text/javascript'>
function changeFunction(){
var userName = $('#inputUser').val();
var role =$('#inputGroupSelect01').val();
$.ajax({
method: "POST",
url: "server.php",
data: JSON.stringify( { "userId": userName, "userRole": role } ),
dataType: "text",
success: function (response){
if(response=='SUCCESS'){
$('#resultDiv').append('<br/>Successful Updated'+response);
}else{
$('#resultDiv').append('<br/>Error'+ response);
}
}
});
}
</script>
**Third ** you have to write the new server.php file with following code
<?php
$var1= $_POST["userId"]; // change here userId as used in jquery block
$var2= $_POST["userRole"];// change here userRole as used in jquery Block
//require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
//suppose query is executed successfull then
//it will return no of rows updated
$query_result = mysql_query($query);
//SUCCESS_CONDITION is normally if number of row updated is 1 in return
///of query execution so kindly define by your own way
$num_rows = mysql_num_rows($query_result);
//if($num_rows==1 || define your own SUCCESS_CONDITION){
if($num_rows ==1){
$result ='SUCCESS';
}else{
$result ='ERROR';
}
echo $result;
?>
I hope it will help
Thanks
Ask for help if needed
You can do this using PHP but you need to check $_POST data.
if(isset($_POST['inputGroupSelect01']) && isset($_POST['inputUser;]){
$var1= $_POST["inputGroupSelect01"];
$var2= $_POST["inputUser"];
require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
}
By the way, that code is entirely vulnerable. You are taking 2 inputs from users and placing them directly, and placing them into a SQL query.
What if my input for var2 was '; DROP TABLE user; ?
Related
I'm trying to do the 2nd drop down population based on the 1st drop down by using ajax in codeigniter. But my problem is after I choose for 1st drop down value, when I try to choose for 2nd drop down value, it shows empty only.
(Update: I already fixed my problem. So, I already updated my code.)
Image below shows that the result after I choose for 1st option. When I try to select for 2nd option, it can't shows the value:
Here's is the code for view:
<div class="container">
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<div class="card">
<div class="card-body">
<h3 class="card-title text-center"><?php echo $content_heading;?></h3>
<form action="#" id="form" novalidate>
<div class="form-row">
<div class="col-sm-12">
<div class="form-group">
<label for="subject_name">Subject Name</label>
<select class="form-control" name="subject_name" id="subject_name">
<option>-- Select Subject Name --</option>
<?php foreach($attendance as $row){
echo "<option value='".$row['subject_id']."'>".$row['subject_name']."</option>";
}
?>
</select>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="lecturer_name">Lecturer Name</label>
<input name="lecturer_name" placeholder="Lecturer Name" class="form-control" type="text" disabled="">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="subject_section">Section</label>
<select class="form-control" name = "subject_section" id='subject_section'>
<option>-- Select Subject Section --</option>
</select>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_date">Date</label>
<input name="attendance_date" placeholder="Date" class="form-control" type="date">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_start_time">From</label>
<input name="attendance_start_time" placeholder="From" class="form-control" type="time">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_end_time">To</label>
<input name="attendance_end_time" placeholder="To" class="form-control" type="time">
<div class="invalid-feedback"></div>
</div>
<button type="button" id="btnSave" class="btn btn-primary btn-block" onclick="save()">Confirm</button>
</div>
</div>
</form>
</div>
</div>
</div>
Here is the javascript for the ajax function. (I already updated my javascript code.)
<script>
$(document).ready(function(){
// Subject change
$('#subject_name').change(function(){
var subject_id = $(this).val();
// AJAX request
$.ajax({
url : "<?php echo site_url('attendance/get_subject_section')?>",
method: 'POST',
data: {subject_id: subject_id},
dataType: 'JSON',
success: function(response){
// Remove options
$('#subjectsection').find('option').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#subject_section').append('<option value="'+data['subject_id']+'">'+data['subject_section']+'</option>');
});
}
});
});
});
</script>
Here is the code for controller:
<?php class attendance extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Attendance Data/attendance_model','attendance');
}
function index(){
//$this->load->view('Manage User Registration/user_login_view');
$data['meta_title'] = 'Attendance';
$data['content_heading'] = 'Attendance';
$data['main_content'] = 'Manage Student Attendance/attendance';
$data['user_id'] = $this->session->userdata('id');
if($this->session->userdata('user_type')==='lecturer'){
$data['user_type'] = 'lecturer';
$data['meta_user_level_title'] = 'Lecturer';
$data['id'] = $this->session->id;
$data['main_content'] = 'Manage Student Attendance/lecturer_attendance_view';
$this->load->view('template/template', $data);
}else{
echo "Access Denied";
}
}
public function create_attendance()
{
$data['meta_title'] = 'Add Subject Attendance';
$data['content_heading'] = 'Add Subject Attendance';
$data['main_content'] = 'Manage Student Attendance/attendance';
$data['user_id'] = $this->session->userdata('id');
$data['user_type'] = 'lecturer';
$data['heading'] = 'Lecturer';
if($this->session->userdata('user_type')==='lecturer'){
$data['user_type'] = 'lecturer';
$data['attendance'] = $this->attendance->get_subject_name();
$data['meta_user_level_title'] = 'Lecturer';
$data['id'] = $this->session->id;
$data['main_content'] = 'Manage Student Attendance/create_attendance';
$this->load->view('template/template', $data);
}else{
echo "Access Denied";
}
}
public function get_subject_section()
{
// POST data
$subject_id= $this->input->post('subject_id');
// get data
$data = $this->attendance->get_subject_section($subject_id);
echo json_encode($data);
}}
Here is my code for model:
<?php class attendance_model extends CI_Model{
//Get subject name
public function get_subject_name()
{
$user_id = $this->session->userdata("id");
$response = array();
// Select record
$this->db->select('*');
$this->db->where('lecturer_id', $user_id);
$this->db->group_by('subject_id');
$query = $this->db->get('lecturer_timetable');
$response = $query->result_array();
return $response;
}
//Get subject section
public function get_subject_section($subject_id){
$user_id = $this->session->userdata("id");
$response = array();
// Select record
$this->db->select('subject_id, subject_section');
$this->db->where('lecturer_id', $user_id);
$this->db->where('subject_id', $subject_id);
$query = $this->db->get('lecturer_timetable');
$response = $query->result_array();
return $response;
}}
Can someone help me to solve this problem? Thanks.
your url in ajax is unreadable because of quotation. Try to writer in proper quotation. Use either single quotes inside double quotes or use double inside single. Second is, you are using method as 'POST' but in lowercase. Write POST in uppercase.
$.ajax({
url : "<?php echo site_url('attendance/get_subject_section')?>",
method: 'POST',
data: {subject_name: subject_name},
dataType: 'json',
success: function(response){
console.log(response); // first check by console that you are getting records in response. once you get response then append it or do whatever you want
}
});
I have a system project where I can create fuel expenses records, so the process to create an expenses records, I fill up the first form with names of employee,
here's my first form:(using this form, I can access all employee's name from database)
<div class="form-group">
<label>Employee Name</label>
<select name="employee" onchange="getEmp(this.value)" class="form-control">
<option value="">Select Employee</option>
<?php foreach($emps as $emp) : ?>
<option value="<?php echo $emp["employee_id"]; ?>"><?php echo $emp["surname"] . ', ' . $emp["firstname"]; ?></option>
<?php endforeach; ?>
</select>
<div class="help-block with-errors"></div>
</div>
the name of employee is already stored in the table named tbl_employee, each names are provided with codename and issued with vehicle. so in other words, I have two tables in my database named, tbl_employee and tbl_vehicle.
the tbl_employee has attribute: employee_id(primary key), carid(foreign key) surname, firstname and codename,
the tbl_vehicle has attribute: carid(primary key) and reg_num(registration number or plate number)
what I want is, when I select a names from the form stated above, I want to automatically fill the form (stated below) with its codename and a reg_num(plate number):
<div class="form-group">
<label>Employees Code Name</label>
<input class="form-control" name="codename" type="text"/>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label>Plate Number</label>
<input class="form-control" name="reg_num" type="text"/>
<div class="help-block with-errors"></div>
</div>
I also using this SQL statement to access the employees name directly from the database:
$emp = query("SELECT * FROM tbl_employee");
render("./fuel/list.php", ["title" => "Fuel Expenses List", "fuels" => $rows, "emps" => $emp]);
as you see, there is no javascript written on my codes, that's one of the reason why I need everyone's help.
You try this:
onkeyup(getEmp(this.value));
The following is the jquery script for my otp.
<Script>
$(document).ready(function(){
$('#otp_submit').click(function(){
var otp_insert=$('#otp_insert').val();
$.ajax({
url:'smsverify.php',
type:'POST',
data:{otp_insert:otp_insert},
/* beforeSend: function(){
$('.image_loading').show();
},
complete: function(){
$('.image_loading').hide();
},*/
success: function(data){
if(data.success==1){
$('.hide2show').show();
$('html, body').animate({ scrollTop: $('.hide2show').offset().top }, 'slow');
}
else
{
$('.result').html(data);
}
},
error: function() {
console.error('Failed to process ajax !');
}
});
});
});
</Script><!-- Send Otp To the mobile number using ajax -->
This is the script which send data to smsverify.php and now this is my smsverify.php script
<?php
session_start();
$otp_password=$_POST['otp_insert'];
echo $otp_password;
if($_SESSION['otpkey']==$otp_password) {
echo "OTP is granted using session";
} else {
echo "otp is not granted not session";
}
?>
This is php script to validate sms otp which send by user.
actually script works fine , but when it returns the data .it is only showing the echo message. not showing the .hide2show class which is contain remaining registration form.
<div class="row">
<h4 class=""> <Strong> Primary Details : </Strong></h4>
<div class="col-md-3">
<label> Your Email - </label>
</div>
<div class="col-md-6">
<input type="text" name="email_user" id="email_user" placeholder="Enter Your Email" class="form-control">
<span id="error" style="display:none;color:red;">Wrong Email Id , Kindly Enter valid E-mail Id</span><i class="fa fa-file-text-o errspan"></i>
</div>
</div><!-- end of emaiol row--><label></label>
<div class="row">
<div class="col-md-3">
<label> Your Mobile Number - </label>
</div>
<div class="col-md-6">
<input type="text" name="mobile_user" id="mobile_user" placeholder="Enter Your Mobile Number ( 10 Numbers Allowed Only)" class="form-control" required title=" Wrong Mobile Number , Only 10 Digits Allowed" onkeypress='return isNumberKey(event)' maxlength="10"><i class="fa fa-lg fa-mobile-phone errspan" ></i> <span id="error_mob" style="display:none;color:red;">Wrong Mobile Number Kindly Enter Valid Number</span>
</div>
<div class="col-md-3">
<input type="button" name="otp_send" id="otp_send" class="btn btn-info btn-block" Value="Send OTP" disabled="disabled">
</div>
</div><!-- end of emaiol row--><label></label>
<img src="../assets/img/289.gif" class="image_loading" style="display:none;">
<div class="row hide4otp" style="display:none;">
<div class="col-md-3">
<label> One Time Password - </label>
</div>
<div class="col-md-6">
<input type="text" name="otp_insert" id="otp_insert" placeholder="Enter One Time Password" class="form-control" maxlength="5" ><span id="error_otp" style="display:none;color:red;">Wrong OTP , Kinldy Enter a Valid OTO Which You Have Received On Your Mobile</span>
</div>
<div class="col-md-3">
<input type="button" name="otp_submit" id="otp_submit" class="btn btn-danger btn-block" Value="Press Me !!" disabled="disabled">
</div>
</div><!-- end of emaiol row--><label></label>
<div class="row hide2show">
<h4 class=""> <Strong> Property Information : </Strong></h4>
<div class="col-md-3">
<strong>Property For : </strong>
</div>
<div class="col-md-6">
<select name="proerty_for" id="proerty_for" class="form-control" >
<option value="Sale"> For Sale</option>
<option value="Rent"> For Rent</option>
</select>
</div>
</div><!-- end of Property_for--><label></label>
This is html code for your relevnce
data.success is accessing the the success property of the object data . However, you are not returning an object from your PHP. Modify your PHP to return an object in JSON.
<?php
session_start();
$otp_password=$_POST['otp_insert'];
$response = array();
if($_SESSION['otpkey']==$otp_password) {
$response['success'] = 1;
$response['message'] = "OTP is granted using session";
} else {
$response['success'] = 0;
$response['message'] = "OTP is not granted using session";
}
echo json_encode($response);
Try following code ,it may work for you
<?php
session_start();
$otp_password=$_POST['otp_insert'];
if($_SESSION['otpkey']==$otp_password) {
echo "1";
} else {
echo "0";
}
?>
and in your ajax response check with
if(data=='1'){
// your code
}
success: function(data){
var result = $.trim(data);
if(result=="OTP is granted using session") {
$('.hide2show').show();
$('html, body').animate({ scrollTop: $('.hide2show').offset().top }, 'slow');
}
else
{
$('.hide2show').hide();
$('#error_otp_valid').show();
console.log('Wrong OTP , Please try again Later');
}
},
error: function() {
console.log('Failed to process ajax !');
}
This is my Ajax success part. thanks everyone . it helps me alot. i also learn a new things of console and trim function in jquery.
I am trying to get the value from a drop down menu (list) and use that value to create another drop down menu. I have a database in mysql, in that database is a list of departments and then each department has a list of courses. What I am trying to do is have a drop down list for the departments which I have already created and then use the value the user selected to make a drop down list for the courses.
EDIT: Updated code:
JavaScript dropmysql.js
<!-- start: Container -->
<div class="container">
<!-- start: Contact Form -->
<div class="title">
<h4>Contact Form</h4>
</div>
<!-- start: Contact Form -->
<div id="contact-form">
<form method="post" action="assets/upload.php" enctype="multipart/form-data">
<fieldset>
<div class="clearfix">
<label for="name"><span>Name:</span>
</label>
<div class="input">
<input tabindex="1" size="18" id="name" name="name" type="text" value="">
</div>
</div>
<div class="clearfix">
<label for="email"><span>Email:</span>
</label>
<div class="input">
<input tabindex="2" size="25" id="email" name="email" type="text" value="" class="input-xlarge">
</div>
</div>
<div class="dropdown">
<label for="department"><span>Department:</span>
</label>
<select tabindex="3" type="text" name="Department">
<?php while($dept=m ysqli_fetch_array($result)) { echo "<option value=\" ".$dept['dname']."\ ">".$dept[ 'dname']. "</option>"; } //<option value="volvo">Volvo</option>
?>
</select>
</div>
<div class="dropdown" id="course-container">
<!-- SELECT WILL BE PLACED USING JAVASCRIPT -->
</div>
<div class="actions">
<p>
<label for="file"><span>Select file to upload:</span>
</label>
<input tabindex="8" type="file" name="fileToUpload" id="fileToUpload">
</p>
<p>
<input tabindex="3" type="submit" value="Upload File" name="submit" class="btn btn-succes btn-large">
</p>
</div>
</fieldset>
</form>
</div>
<!-- end: Contact Form -->
</div>
<!-- end: Container -->
<!-- start: Java Script -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery-1.8.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/flexslider.js"></script>
<script src="js/carousel.js"></script>
<script src="js/dropmysql.js"></script>
<script def src="js/custom.js"></script>
<!-- end: Java Script -->
PHP upload.php
<?php
include ("../config/database.php");
if (isset($_POST) && !empty($_POST)) {
$department = $_POST['department'];
$query = "SELECT * FROM courses WHERE dname = '{$department}'";
while (mysql_fetch_assoc($query)) {
echo '<option value="{$value}>{$name}</option>"'; // Loop through the database again and echo them here
}
}
?>
PHP ddown.php:
<?php
include ("../config/database.php");
if (isset($_POST) && !empty($_POST)) {
$department = $_POST['department'];
$query = "SELECT * FROM courses WHERE dname = '{$department}'";
while (mysql_fetch_assoc($query)) {
echo '<option value="{$value}>{$name}</option>"'; // Loop through the database again and echo them here
}
}
?>
First it will be helpful to add an id/class to the first select such as:
<select tabindex="3" type="text" name="Department" id="department">
<option value="BSEN">BSEN</option>
<option value="CPSC">CPSC</option>
<option value="ENGG">ENGG</option>
</select>
You'll need to setup the 2nd dropdown list with empty options, or setup an empty div similar to this
<div id="course-container">
<!-- SELECT WILL BE PLACED USING JAVASCRIPT -->
</div>
Then a javascript file similar to this could be used:
$(function() {
var course_container = $("div#course-container");
var data = {};
$('select#department').change(function() {
$(course_container).html("<select id=\"courses\"></select>");
var courses = $("select#courses");
var d = document.getElementById("department");
data['department'] = d.options[d.selectedIndex].value;
$.ajax({
url: "path/to/php/script.php",
type: "post",
data: data,
success: function(response) {
$(courses).innerHTML = response;
}
});
});
});
Then just a php script like this:
<?php
if (isset($_POST) && !empty($_POST)) {
$department = $_POST['department'];
$query = "SELECT * FROM `DATABASE` WHERE `DEPARTMENT` = {$department}";
while (mysql_fetch_assoc($query)) {
echo '<option value="{$value}>{$name}</option>"'; // Loop through the database again and echo them here
}
}
If you have a select element that looks like this:
<!-- language: lang-html -->
<input type="hidden" id="depthidden" name="depthidden">
<select tabindex="3" id="Department">
<option value="BSEN">BSEN</option>
<option value="CPSC">CPSC</option>
<option value="ENGG">ENGG</option>
</select>
Run this code:
<!-- language: lang-js -->
var d = document.getElementById("Department");
document.getElementsById('depthidden').Value = d.options[d.selectedIndex].value;
The above is just a JS demo to help you.
The php section:
$dname = mysql_real_escape_string($_POST['depthidden']);
while($dept= mysqli_fetch_assoc($result))
{
if($dname==$dept[dname])
echo "<option value = '".$dept[dname]."' selected>".$dept[dname]."</option>";
else
echo "<option value = '".$dept[dname]."'>".$dept[dname]."</option>";
}
The $dname is the dept name to be populated. Otherwise, remove the if and keep the else part.
I have used the code below elsewhere in my site and it works. For the life of me I can't understand why it doesn't work here. PROBLEM: keeps throwing alert message.
My HTML:
<form action="processForms.php" method="post" id="joinCommitteeForm" class="headForm shadow">
<div class="outerBlue" style="background:white">
<button type="button" id="cancelForm" class="button" title="Cancel">X</button>
<br><br>
<h3>Get involved—join a committee!</h3>
<?php if(empty($name)||empty($email)||empty($workPhone)){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
<label for="name" style="width:40px">Name</label><input type="text" name="name" id="name"/><br>
<label for="email" style="width:40px" class="clear">Email</label><input type="text" name="email" id="email"/><br>
<label for="phone" style="width:40px;margin-bottom:20px" class="clear">Phone</label><input type="text" name="dayPhone" id="phone"/>
<hr>
<p class="clear">Please select a committee from the list below</p><br><br>
<select name="comName" id="comName" style="width:215px;margin-left:50px;float:left">
<option value="">Select one...</option>
<?php
$sql = mysql_query("SELECT committeeName FROM committeeName ORDER BY committeeName");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value = '".$row['committeeName']."'>".$row['committeeName']."</option>";
}
echo "</select>";?>
<input type="submit" name="submitCommitteeInterest" class="button orange-button clear" value="Submit" style="margin-top:40px"/>
<div class="clear"></div>
<p class="small white" style="line-height:1em;margin-top:20px">NSGP never sells or gives away your personal information</p>
</div>
</form>
My JS:
$("#joinCommitteeForm").submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "") {
alert('All fields are required');
return false;
}
});
What I suspect the problem is here, is that you are testing if $name or $email is empty, but since you never define them, they will always be empty, per PHP empty() docs: "A variable is considered empty if it does not exist or if its value equals FALSE".
To fix that, you'll need to change your PHP if-statement to:
<?php if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['dayPhone'])){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
Also, your POST parameter $workPhone doesn't seem to exist in your form. I've changed it to dayPhone here.
The variable $_POST will contain all parameters in the POST request from the form that's submitted.