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>
Related
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?
I am not sure how to word this title. Feel free to edit it.
Intro I am doing a datatables.net library server-side table using JSON and PHP. I am basically done except for the edit form.
My first problem was solved. I had a while loop instead of an if statement.
My second problem is now going to be transferring this Javascript code near before the AJAX call:
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
to here which is php:
$edit_id = $_POST['edit_id'];
They are both on the same page, index.php so I do not think I can use ajax for this.
Index.php
<script type="text/javascript">
$(document).on('click', '.edit_btn', function() {
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
$("#form2").show();
//console.log(edit_id[0]);
$.ajax({
type: 'POST',
url: 'edit.php',
data: {
edit_id: edit_id,
first_name: $("#edit2").val(),
last_name: $("#edit3").val(),
position: $("#edit4").val(),
updated: $("#edit5").val(),
},
success: function(data) {
alert(data);
if (data == 'EDIT_OK') {
alert("success");
} else {
// alert('something wrong');
}
}
})
});
</script>
<?php
$sql="select * from employees WHERE id=$edit_id";
$run_sql=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run_sql)){
$per_id=$row[0];
$per_first=$row[1];
$per_last=$row[2];
$per_position=$row[3];
//$per_date=$row[4];
$per_updated=$row[5];
?>
<form id="form2" class="form-horizontal">
<label class="col-sm-4 control-label" for="txtid">ID</label>
<input id="edit1" type="text" class="form-control" name="txtid" value="<?php echo $per_id;?>" readonly>
<div class="form-group">
<label class="col-sm-4 control-label" id="edit2" for="txtname">First Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="txtname" name="txtname" value="<?php echo $per_first;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtsalary">Last Name</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit3" name="txtsalary" value="<?php echo $per_last;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Position</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit4" name="txtage" value="<?php echo $per_position;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Updated</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit5" name="txtage" value="<?php echo $per_updated;?>">
</div>
<button type="button" class="close" value="Cancel" data-dismiss="modal">×</button>
<button type="button" class="update" value="Update"></button>
</form>
edit.php
$edit_id = $_POST['edit_id'];
$stmt = $conn->prepare("UPDATE employees SET first_name=?, last_name=?, position=?, updated=? WHERE id=?");
$stmt->bind_param('ssssi', $_POST['first_name'], $_POST['last_name'], $_POST['position'], $_POST['updated'], $_POST['edit_id']);
$confirmUpdate = $stmt->execute();
if($confirmUpdate) {
echo "EDIT_OK";
}else {
trigger_error($conn->error, E_USER_ERROR);
return;
}
?>
I eventually figured it out:
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
alert(edit_id);
$.ajax({
url: 'index.php',
data: { edit_id : edit_id },
contentType: 'application/json; charset=utf-8',
success: function(result) {
//alert(result);
}
});
});
</script>
I am trying to update an image in the my database. I have a modal that is loaded with jquery. When clicking on the save modification button, alla the form data shows up except for the image file, which does not show up in the $_FILES in php. I tried all the indication found on the web (php ini file enables file upload, images size is good). The code works if I use that classic submit method, but I don't want a full screen refresh, I need to do it all in ajax. Here is the html:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
alert(data);
var url = '/PubDev/updatePubDev';
$.post(url, data, null, 'json')
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error");
}
})
.fail(function (data) {
alert("ajax error");
})
.always(function () {
});
});
<div class="md-modal md-effect-1" id="updatePubDevModal" >
<div class="md-content">
<div class="modal-header">
<button class="md-close close">×</button>
<h4 class="modal-title">Update Publisher/Developer</h4>
</div>
<form id="updatePubDevFrm" class="dz-clickable dropzone" action="/PubDev/updatePubDev" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="row dropzone">
<div class="col-lg-5">
<div class="form-group">
<label for="pubDevName">System Id of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevIdDisplay" id="pubDevIdDisplay" class="form-control input-large" disabled="true">
<input type="hidden" name="pubDevId" id="pubDevId" >
</div>
<div class="form-group">
<label for="pubDevName">Name of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevName-update" id="pubDevName-update" class="form-control input-large">
</div>
<div class="form-group">
<label for="date-founded">Date Founded</label>
<input type="text" placeholder="Date founded" id="date-founded-update" name="date-founded-update" class="form-control date-picker input-large">
</div>
<div class="form-group">
<label>What type of company is this?</label>
<div class="checkbox-nice">
<input type="checkbox" name="isPub-update" id="isPub-update">
<label for="date-founded-update">
This company is a publisher
</label>
</div>
<div class="checkbox-nice">
<input type="checkbox" name="isDev-update" id="isDev-update">
<label for="isDev-update">
This company is a developer
</label>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="main-box clearfix main-box-frame" >
<header class="main-box-header clearfix">
<h2>Upload Publisher /Developer Logo</h2>
</header>
<div class="main-box-body clearfix imgcontainer center">
<img id="preview" src="" class="pointable" alt="No Image Available" style="max-height:100%; max-width: 100%; "/>
<div class="main-box-body clearfix">
<div id="dropzone" class="drop-zone-frame" >
<input type="file" name="image2" id="image2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="confirmUpdPubdev" class="btn btn-primary">Save Modifications.</button>
</div>
</form>
</div>
</div>
Here is the php code:
public function updatePubDev() {
$fields = array();
$fields[$this->pubdev->get_id_name()] = $this->input->post('pubDevId');
$fields['name'] = $this->input->post('pubDevName-update');
if ($this->input->post('date-founded'))
$fields['date_founded'] = stampa_data_formato_DATE($this->input->post('date-founded-update'), '/');
if ($this->input->post('isPub-update'))
$fields['publisher'] = 1;
else
$fields['publisher'] = 0;
if ($this->input->post('isDev-update'))
$fields['developer'] = 1;
else
$fields['developer'] = 0;
$row_count = $this->pubdev->update($fields,$this->pubdev->get_id_name());
$file = $_FILES['image2'];
//$idPubDev = $this->input->post("pubDevName");
$ds = DIRECTORY_SEPARATOR;
$path = dirname('../') . $ds . 'application' . $ds . 'assets' . $ds . 'img' . $ds . 'pub_devs' . $ds . 'logos' . $ds;
//print_r($file);
$info = new SplFileInfo($file['name']);
//var_dump($info->getExtension());
$filename = "logo_id_" . str_pad( $this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . "." . $info->getExtension();
$result = $this->upload->uploadfile($file, $path, $filename);
//echo "test";
if ($result['status'] === "OK") {
$logo = 'logo_id_' . str_pad($this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . '.' . $info->getExtension();
$this->pubdev->update(array('logo' => $logo, $this->pubdev->get_id_name() => $this->input->post('pubDevId')), $this->pubdev->get_id_name());
$result['message'] = "file saved successfully";
$result['query'] = $this->db->last_query();
}
$result['update_rows']= $row_count;
echo json_encode($result);
}
I tried the .ajax version, but the problem persist, here is the modified jquery:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = '/PubDev/updatePubDev';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false
})
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error!");
}
})
.fail(function (data) {
alert("ajax error!");
})
.always(function () {
});
});
It is not a duplicate question because the answer provide contained different properties necessary to uplaod both image and data inputs. these two properties in the $.ajax call are needed:
processData: false,
contentType: false
This way, it solved my problem.
Use FormData as data instead of $(this).serialize();, set processData and contentType to false
var data = new FormData();
data.append("file", $(":file", this)[0].files[0]);
$.ajax({
url: "/PubDev/updatePubDev",
type: "POST",
data: data,
processData: false,
contentType: false
})
Please try to use file_get_contents('php://input'); to get the upload content.
I have a registration form and want to check if registered user will try to register again to show a alert window already registered using ajax function.
i have used codeigniter framework.
my function is working properly but when alert popup and press ok page is reloaded. i want to disable
my form code:
<form class="modal-content" name="form2" action="<?= $this->config->base_url();?>home/register_user" method="post" onSubmit="return ValidateRegister()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Create your account</h4>
</div>
<div class="page-content vertical-align-middle" style="display:block;">
<div class="form-group has-error">
<label class="control-label" for="inputTokenfieldError-tokenfield"> <?php echo validation_errors(); ?></label>
</div>
<div class="form-group form-material floating">
<input type="text" class="form-control " id="inputName" name="username" value="<?php echo set_value('username'); ?>" autocomplete="off">
<label class="floating-label">Username</label>
</div>
<div class="form-group form-material floating">
<input type="email" class="form-control " id="my_email" name="email" value="<?php echo set_value('email'); ?>" autocomplete="off">
<label class="floating-label">Email</label>
</div>
<div class="form-group form-material floating">
<input type="password" class="form-control " id="inputPassword" name="password" autocomplete="off">
<label class="floating-label">Password</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Join Now - It's Free</button>
</div>
</form>
my javascript function:
function checkRegistrations()
{
var email = $('#my_email').val();
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
// alert(data);
if(data==1)
{
//event.preventDefault();
alert('Email already registered');
return false;
window.location.reload(false);
}
else{
return true;
}
}
})
}
Just add an id to the submit button, say #submitbutton.
and use the .prop() method of jQuery to set the disabled attribute of the button.
$("#submitbutton").prop("disabled", true);
IMP: This will only work if you are keeping the same page on ajax success, But if you are reloading the page then you need to check it on php side whether this form has been submitted in this current $_SESSION.
So inside your php ajax handler, you can do the check as follows.
session_start();
if(!empty($_POST) && empty($_SESSION['post'])) {
$_SESSION['post'] = true;
... do your code
unset($_SESSION['post']);
}else{
// send the json encoded error message
}
And on the html form just add a hidden input with the name post and set value to 1 or something whatever you deem fit, so once the form is submitted, the post key will be set inside the $_SESSION SuperGlobal Array, and if the same form is submitted twice by the same user then php wont accept it.
You are returning true/false from inside an annon. function i.e. success handler. But parent function is not returning true/false.
Modify your code like this :
function checkRegistrations()
{
var email = $('#my_email').val();
var isValid = true;
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
if(data==1)
{
alert('Email already registered');
isValid = false;
}
}
});
return isValid;
}
Here is my HTML Code:
<div class="form-horizontal row-border">
<div class="form-group">
<label class="col-md-2 control-label">Title:</label>
<div class="col-md-10"><input class="form-control" id="title" name="title" type="text"></div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Article:</label>
<div class="col-md-10">
<textarea name="editor1" id="editor" rows="10" cols="80">
Let's go...
</textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Tags:</label>
<div class="col-md-10"><input class="tags" id="tags" type="text" value="">
</div>
</div>
<div class="row" style="margin-left:92%;">
<input type="button" id="PostArticle" class="btn btn-success" value="Post Article"></input>
</div>
</div>
Here is my JavaScript code:
<script type="text/javascript">
$("#PostArticle").click(function() {
var title = $("#title").val();
var text = $("#editor").text();
var tags = $("#tags").val();
$.ajax({
url: 'post_new_article.php',
type: 'POST',
data: {
title: title,
tags: tags,
text: text
},
dataType: 'json',
success: function (data) {
noty({text: 'MySite.com:' + data.title + ' was successfully created!', type: 'success'});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
noty({text: 'Failure - The article was not created! Error is: ' + errorThrown + '', type: 'error'});
}
});
});
</script>
Here is the code from: post_new_article.php:
<?php
require "include/config.php";
require "include/functions.php";
ConnectWithMySQLDatabase();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$title = $_POST['title'];
$text = $_POST['text'];
$tags = $_POST['tags'];
$month = date('F');
$year = date('Y');
$day = date('d');
if(isset($_POST['title']))
{
mysql_query("INSERT INTO `Blog` (`id`, `Title`, `Article`, `Autor`, `Date`, `Month`,`Year`, `Tags`, `Image`) VALUES ('', '$title', '$text', 'Venelin Vasilev', '$day','$month', '$year', '$tags', '')");
}
$result['title'][0] = $title;
echo json_encode($result);
From all things it seems that only the MySQL insert function is not working. I can confirm that ConnectWithMySQLDatabase(); function is working as intended and this function is establishing the connection to MySQL.
Somehow it seems i can not insert the mysql query after i hit the Post Article button. I can confirm that i receive response from post_new_article.php because i receive a notification with the title of the article as a back response. So the json seems to read back the title of the article.
So can you help me out resolve this problem and make it insert the query to the MySQL database ?
Thanks in advance!
Try this
in your form submit button should be
<input type="submit" id="submit" class="btn btn-success" value="Post Article"></input>
And AJAX Should be
<script>
$(function(){
$( "#submit" ).click(function(event)
{
event.preventDefault();
var title = $("#title").val();
var text = $("#editor").text();
var tags = $("#tags").val();
$.ajax(
{
type:"post",
dataType: 'json',
url: "./post_new_article.php",
data:{ title:title, text:text,tags:tags},
success:function(data)
{
}
});
});
});
</script>
EDIT 01
Change this
mysql_query("INSERT INTO Blog (id, Title, Article, Autor, Date, Month,Year, Tags, Image) VALUES ('', '$title', '$text', 'Venelin Vasilev', '$day','$month', '$year', '$tags', '')");