Book quantity output problem in library management system - javascript

I am building a library management system using PHP, JavaScript. Each book has a unique code. There will be a system in the form of book borrowing pages. If you input the code of any book, the name of the book and the quantity of the book will come down. I was able to get the name of the book using JavaScript. But I could not bring the amount of books.
issue-book.php
function getbook() {
$("#loaderIcon").show();
jQuery.ajax({
url: "get_book.php",
data:'bookid='+$("#bookid").val(),
type: "POST",
success:function(data){
$("#get_book_name").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
//function for quantity
function getquantity() {
$("#loaderIcon").show();
jQuery.ajax({
url: "get_quantity.php",
data:'bookid2='+$("#bookid2").val(),
type: "POST",
success:function(data){
$("#get_quantity").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>
<style type="text/css">
.others{
color:red;
}
</style>
</head>
<body>
<!------MENU SECTION START-->
<?php include('includes/header.php');?>
<!-- MENU SECTION END-->
<div class="content-wra
<div class="content-wrapper">
<div class="container">
<div class="row pad-botm">
<div class="col-md-12">
<h4 class="header-line">Issue a New Book</h4>
</div>
</div>
<div class="row">
<div class="col-md-10 col-sm-6 col-xs-12 col-md-offset-1"">
<div class="panel panel-info">
<div class="panel-heading">
Issue a New Book
</div>
<div class="panel-body">
<form role="form" method="post">
<div class="form-group">
<label>Student id<span style="color:red;">*</span></label>
<input class="form-control" type="text" name="studentid" id="studentid" onBlur="getstudent()"
autocomplete="off" required />
</div>
<div class="form-group">
<span id="get_student_name" style="font-size:16px;"></span>
</div>
<div class="form-group">
<label>ISBN Number or Book Title<span style="color:red;">*</span></label>
<input class="form-control" type="text" name="booikid" id="bookid" onBlur="getquantity()"
required="required" />
</div>
<div class="form-group">
<select class="form-control" name="bookdetails" id="get_book_name" readonly></select>
</div>
<div class="form-group">
<select class="form-control" name="quantity" id="get_quantity" readonly></select>
</div>
<button type="submit" name="issue" id="submit" class="btn btn-info">Issue Book </button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
get_quantity.php
<?php
require_once("includes/config.php");
if(!empty($_POST["bookid2"])) {
$bookid2=$_POST["bookid2"];
$sql ="SELECT Quantity, id FROM tblbooks WHERE (ISBNNumber=:bookid2)";
$query= $dbh -> prepare($sql);
$query-> bindParam(':bookid2', $bookid2, PDO::PARAM_STR);
$query-> execute();
$results = $query -> fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query -> rowCount() > 0)
{
foreach ($results as $result) {?>
<option value="<?php echo htmlentities($result->id);?>"><?php echo htmlentities($result-
>Quantity);?></option>
<b>Book Name :</b>
<?php
echo htmlentities($result->Quantity);
echo "<script>$('#submit').prop('disabled',false);</script>";
}
}
else{?>
<option class="others"> Invalid ISBN Number</option>
<?php
echo "<script>$('#submit').prop('disabled',true);</script>";
}
}
?>

I found the solution
//function for quantity
function getquantity() {
$("#loaderIcon").show();
jQuery.ajax({
url: "get_quantity.php",
data:'bookid2='+$("#bookid").val(),
type: "POST",
success:function(data){
$("#get_quantity").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}

This is not specifically an answer to your question, but you might make life a lot easier for yourself if you add some error detection. For instance in your AJAX calls your error reporting now looks like this:
jQuery.ajax({ ... },
error: function (){}
});
That is completely useless. Why not do:
jQuery.ajax({ ... },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("ERROR: " + textStatus);
}
});
That way you know immediately if your AJAX call had a problem, or not.
Same with PDOStatement::execute() that returns TRUE on success and FALSE on failure. That's useful to know. You can give yourself some feedback.
You could also use your browser's developer tools to see what your Javascript code is doing.
Debugging code is often as much work as writing it in the first place. Why not make that slightly easier for yourself?

Related

show submit button js

check_availability.php
this is my php to check the form if it is already exist.
<?php
require_once("config.php");
//code check email
if (!empty($_POST["CUSUNAME"])) {
$result = mysqli_query($con, "SELECT count(*) FROM tblcustomer WHERE CUSUNAME='" . $_POST["CUSUNAME"] . "'");
$row = mysqli_fetch_row($result);
$email_count = $row[0];
if ($email_count > 0) echo "<span style='color:red'>Username is already used.</span>";
else echo "<span style='color:green'>Username is available.</span>";
}
// End code check email
//Code check user name
if (!empty($_POST["PHONE"])) {
$result1 = mysqli_query($con, "SELECT count(*) FROM tblcustomer WHERE PHONE='" . $_POST["PHONE"] . "'");
$row1 = mysqli_fetch_row($result1);
$user_count = $row1[0];
if ($user_count > 0) echo "<span style='color:red'>Phone is already used.</span>";
else echo "<span style='color:green'>Phone number is available.</span>";
}
// End code check username
?>
LogSignModal.php
here is my page.
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4 control-label" for=
"CUSUNAME">Username:</label>
<div class="col-md-8">
<input class="form-control input-sm" onBlur="checkUserNameAvailability()" id="CUSUNAME" name="CUSUNAME" placeholder=
"Username" type="text" value="">
<span id="username-availability-status"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4 control-label" for=
"PHONE">Contact Number:</label>
<div class="col-md-8">
<input class="form-control input-sm" onBlur="checkPhoneAvailability()" id="PHONE" name="PHONE" placeholder=
"Phone Number" type="number" value="">
<span id="Phone-availability-status"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4" align = "right"for=
"image"></label>
<div class="col-md-8">
<input type="submit" name="submit" value="Sign Up" class="submit btn btn-pup" />
<button class="btn btn-default" data-dismiss="modal" type=
"button">Close</button>
</div>
</div>
</div>
<script>
function checkUserNameAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'CUSUNAME='+$("#CUSUNAME").val(),
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
function checkPhoneAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'PHONE='+$("#PHONE").val(),
type: "POST",
success:function(data){
$("#Phone-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>
my code is all worked, but I can't make a submit button to appear when the value I input in textbox is available in database and disappear if it is already use.
I hope someone help me, thank you.
Edit: First, you should definitely also check the comment of Dharman and rewrite how you fetch data from MySQL in your PHP code since the current state is vulnerable to SQL Injections and is absolutely not safe to use!
The problem is how you pass your data to your ajax function. The way you do it, the server receives nothing but a plain string, for example 'CUSUNAME=dave'. This way $_POST["CUSUNAME"] will find nothing and your server response will stay empty. So you should pass your data as an object the following way :
<script>
function checkUserNameAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:{'CUSUNAME': $("#CUSUNAME").val()},
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
function checkPhoneAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:{'PHONE': $("#PHONE").val()},
type: "POST",
success:function(data){
$("#Phone-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>

Contact form not working after migration from HTML (static) to WP

Thanks in advance for reading.
I converted my static HTML page to Wordpress, after the contact-form stopped working. I think it has something to do with the linking in the form.js and handler.php. See ** in handler.php and form.js. Help me out !!! :)
Live version: 050management.nl
Form HTML
<div class="row">
<div class="col-md-7">
<div class="input-group">
<input type="text" class="form-control" type="text" name="Name" id="name" placeholder="Uw naam..." required data-error="Voer uw naam in">
</div>
</div>
</div>
<div class="row">
<div class="col-md-7 pt-2">
<div class="input-group">
<input type="text" class="form-control" type="email" name="Email" id="email" placeholder="Uw e-mailadres..." required data-error="Voer uw e-mailadres in">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-2">
<div class="input-group">
<textarea name="Message" id="message" class="form-control" cols="30" rows="5" placeholder="Uw bericht..." data-error="Stel uw vraag"></textarea>
</div>
</div>
</div>
<div class="input-group pt-2">
<div class="g-recaptcha" data-sitekey="6LddA2oUAAAAAHmFtwEkS68c4_UUi3hGpd7AZyOo"></div>
</div>
<div class="row">
<div class="col-md-9 pt-2">
<div class="input-group">
<input type="submit" class="contact-submit" value="Verzenden">
</div>
</div>
</div>
</form>
<div id="success_message" style="display:none">
<h4>Dank voor uw bericht.</h4>
<p>
We zullen spoedig contact met u opnemen.
</p>
</div>
<div id="error_message"
style="width:100%; height:100%; display:none; ">
<h4>Er ging iets mis...</h4>
<p>Mail ons of bel ons rechtsreeks. Dank u wel.
</div>
</div>
.........
<script src="<?php echo get_template_directory_uri().'/js/form.js' ?>"></script>
form.js (url: /js/form.js)
$(function()
{
function after_form_submitted(data)
{
if(data.result == 'success')
{
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
}
else
{
$('#error_message').append('<ul></ul>');
jQuery.each(data.errors,function(key,val)
{
$('#error_message ul').append('<li>'+key+':'+val+'</li>');
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function()
{
$btn = $(this);
label = $btn.prop('orig_label');
if(label)
{
$btn.prop('type','submit' );
$btn.text(label);
$btn.prop('orig_label','');
}
});
}//else
}
$('#reused_form').submit(function(e)
{
e.preventDefault();
$form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function()
{
$btn = $(this);
$btn.prop('type','button' );
$btn.prop('orig_label',$btn.text());
$btn.text('Sending ...');
});
$.ajax({
type: "POST",
**url: 'handler.php',**
data: $form.serialize(),
success: after_form_submitted,
dataType: 'json'
});
});
});
handler.php (url: handler.php) same folder as index.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
**require_once '/vendor/autoload.php';**
use FormGuide\Handlx\FormHandler;
$pp = new FormHandler();
$validator = $pp->getValidator();
$validator->fields(['Name','Email'])->areRequired()->maxLength(50);
$validator->field('Email')->isEmail();
$validator->field('Message')->maxLength(6000);
$pp->requireReCaptcha();
$pp->getReCaptcha()->initSecretKey('REMAINS SECRET :)');
$pp->sendEmailTo('info#050management.nl');
echo $pp->process($_POST);
In WordPress things are done a little differently.
You can post data from client to server through ajax with setting a right action.
specify a global variable ajaxurl inside head tag or anywhere before your form handling:
<script>
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
When you submit the data you can do it like this:
$.post( ajaxurl, {
action: 'handle_form',
form_data: $form.serialize()
}, function(data) {
// logic after receiving a response
}, 'json'
);
On the server side in functions.php:
function handle_form_ajax_handler() {
$form_data = $_POST['form_data'];
// logic with $form_data
wp_die();
}
add_action('wp_ajax_handle_form', 'handle_form_ajax_handler'); // add action for logged users
add_action( 'wp_ajax_nopriv_handle_form', 'handle_form_ajax_handler' ); // add action for unlogged users

How can i execute a php query from an html form?

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

Bootstrap dismissable success message not showing longer with ajax

I have an ajax form which gets data with PHP post method. Instead of using the alert function of Javascript, I called bootstrap success message. But problem it doesn't show longer last only for less than a second. How to show its length until the user manually closed it as it's dismissable.
Coding Part:
function send_form() {
$.ajax({
url: "./admin-security.php",
type: "POST",
data: {
ip: $("#ip").val()
},
success: function(response) {
if(response==1) {
$("#ajax-ip-success").show();
location.href = "./admin-security.php";
}
else alert("Fail! DataBase Error");
}
});
}
<?php
//--AJAX PART CALLING
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
echo 1;
}
else {
echo 0;
}
exit;
}
?>
<div class="alert alert-success alert-dismissable fade in" style="display: none;" id="ajax-ip-success">
×
<strong>Success!</strong> IP added successfully.
</div>
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="button" onClick="send_form()" class="btn btn-default"
>Submit</button>
</div></div>
</div>
You can set Timeout for location redirect
setTimeout(function(){
location.href = "./admin-security.php";
},2000);

Showing hidden div in ajax success function for displaying a remaining registration form

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.

Categories