Displaying table from PHP in HTML through AJAX - javascript

I am trying to display a table from my PHP file on a web page which is the index.html file using ajax. I am new to PHP and ajax so I currently do not know what is wrong with the codes. However what I do know is that there data is not getting through this line in the javascript file.
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
It works without ajax but of course I do need to go to database.php to display the table. I want it to display on index.html. Also, will my delete button in my PHP file still work?
P.S. I'm using vi editor as I'm currently coding this on a server. However it's just to test out. I am new to server stuff, ajax and PHP so do pardon my mistakes if any. And ignore the table formatting in my HTML file.
P.P.S I do not know any form of jQuery and what I have written is my current knowledge of AJAX.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="function.js" type="text/javascript"></script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit" onclick="checkFields()"/>
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>
This is my javascript file, function.js:
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
}
}
else{
return false;
}
}
This is my PHP file, database.php:
<?php
// Define database parameters //
DEFINE ('DB_USER' ,'iqwer222');
DEFINE ('DB_PASSWORD', 'wfwqr');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'aqwfvaqf');
$table_info = "info";
// Connect to database
$conn = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
#mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error());
// Delete Row
if(isset($_POST['delete'])){
$id = $_POST['deleteRow'];
$query_string = "delete from $table_info where user_id='$id'";
$result = #mysql_query($query_string);
}
//Check if phone no. is duplicate and if not, insert data
if(isset($_POST['result'])){
$phone = $_POST['phone'];
$query_string = "select phone from $table_info where phone='$phone'";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "A same phone number has been found. Please enter a different phone number.";
}else{
$query_string = "insert into $table_info(name, address, phone, gender, nation) values('".$_POST['name']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['gender']."','".$_POST['nation']."')";
$result = #mysql_query($query_string);
}
}
// Display table
$query_string = "select * from $table_info";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "<table border=1>";
echo "<tr><th>Name</th><th>Address</th><th>Phone no.</th><th>Gender</th><th>Nationality</th><th>Created</th><th>Modified</th><th>Action</th></tr>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>", $row['name'], "</td>";
echo "<td>", $row['address'], "</td>";
echo "<td>", $row['phone'], "</td>";
echo "<td>", $row['gender'], "</td>";
echo "<td>", $row['nation'], "</td>";
echo "<td>", $row['createdTime'], "</td>";
echo "<td>", $row['modifiedTime'], "</td>";
?>
<!--Delete button-->
<td><form id="delete" method="post" action="">
<input type="hidden" name="deleteRow" value="<?php echo $row['user_id'] ?>"/>
<input type="submit" name="delete" value="Delete" onclick="return confirm('Are you sure you want to delete this contact?')"/></td></form></tr>
<?php
}
echo "</table>";
}
else{
echo "0 results";
}
?>
<form method="post" action="index.html">
<input type="submit" name="goBack" value="Back"/>
</form>

Considering that you database.php file is giving out correct data back.
a) Error :-
You are not using return false on form submit handler , just add return false and things will work for you
b) Suggestion
1) You are attaching the checkFields() function 2 times, once on submit button click and other on form submit, remove one of them(use sumbit)
2) User below callback in onreadystatechange , the one you have done will work but it is not correct as this callback get called mulitple times
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
Example Code below :
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script >
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
}
}
return false;
}
</script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit" />
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>

Related

Am trying to parse data from a dynamic html form with javascript or jquery to php and insert the data into the database

I have an html form with three input fields which I increment dynamically with javascript. I have to parse the data to PHP which I have done but I can't access the data and insert it into the database as this is an array data. I have tried but it's not working.
Here is my code:
html and Javascript
<body>
<div class="container">
<div class="form-group">
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="othername[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="lastName[]" placeholder="Enter your Name" class="form-control name_last" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><input type="text" name="otherName[]" placeholder="Enter your Name" class="form-control name_last" /></td><td><input type="text" name="lastName[]" placeholder="Enter your Name" class="form-control name_last" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
PHP
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
$numberx = count($_POST["othername"]);
$numbers = count($_POST["lastname"]);
if($number > 1 && $numbers > 1){
for(($i=0; $i<$number; $i++) && ($x=0; $x<$numberx; $x++) && ($w=0; $w<$numbers; $w++)){
if(trim($_POST["name"][$i] != '') && trim($_POST["othername"][$x] != '') &&
trim($_POST["lastname"][$w] != '')){
$namex = mysqli_real_escape_string($connect, $_POST["name"][$i]);
$othernamex = mysqli_real_escape_string($connect, $_POST["othername"][$x]);
$lastnamex = mysqli_real_escape_string($connect, $_POST["lastname"][$w]);
$check = "INSERT INTO bl_name (name, othername, lastname) VALUES ('$namex', '$othernamex', '$lastnamex')";
mysqli_query($connect, $check);
}
}
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
I need help as I have been on this for two days now. Is there any way I can do this?
Simplify your input names, change them to:
user[][name]
user[][othername]
user[][lastname]
Run a simple foreach() loop on $_POST['user']:
foreach($_POST['user'] as $user){
$namex = mysqli_real_escape_string($connect, $user["name"]);
$othernamex = mysqli_real_escape_string($connect, $user["othername"]);
$lastnamex = mysqli_real_escape_string($connect, $user["lastname"]);
$check = "INSERT INTO bl_name (name, othername, lastname) VALUES ('{$namex}', '{$othernamex}', '{$lastnamex}')";
mysqli_query($connect, $check);
}
Keep in mind that form field names are case sensitive. You're also not testing if the mysqli_query() function returns successfully. You should probably do that. And yes, prepared statements are safer.

Cannot pass form data to database (PHP, Jquery)

EDIT
I have implemented the changes suggested and I still cant get this to work:
Form Page Follows (login.php)
<?php
$mac=$_POST['mac'];
$ip=$_POST['ip'];
$username=$_POST['username'];
$linklogin=$_POST['link-login'];
$linkorig=$_POST['link-orig'];
$error=$_POST['error'];
$chapid=$_POST['chap-id'];
$chapchallenge=$_POST['chap-challenge'];
$linkloginonly=$_POST['link-login-only'];
$linkorigesc=$_POST['link-orig-esc'];
$macesc=$_POST['mac-esc'];
if (isset($_POST['postcode'])) {
$postcode = $_POST['postcode'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
?>
**SOME HTML HERE**
<script src="jquery-3.2.1.min.js"></script>
<script>
var js-postcode = document.login.getElementsByName("postcode").value;
var js-email = document.login.getElementsByName("email").value;
var formdata = {postcode:js-postcode,email:js-email};
$("button").click(function(){
$.ajax(
{
type: "POST",
url: "database.php", //Should probably echo true or false depending if it could do it
data : formdata,
success: function(feed) {
if (feed!="true") {
// DO STUFF
} else {
console.log(feed);
// WARNING THAT IT WASN'T DONE
}
}}}
</script>
</head>
<body>
<table width="100%" style="margin-top: 10%;">
<tr>
<td align="center" valign="middle">
<table width="240" height="240" style="border: 1px solid #cccccc; padding: 0px;" cellpadding="0" cellspacing="0">
<tr>
<td align="center" valign="bottom" height="175" colspan="2">
<!-- removed $(if chap-id) $(endif) around OnSubmit -->
<form name="login" action="<?php echo $linkloginonly; ?>" method="post" onSubmit="return doLogin()" >
<input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
<input type="hidden" name="popup" value="true" />
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php echo $username; ?>"/></td>
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><button><input type="submit" value="OK" /></button></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
document.login.username.focus();
//-->
</script>
</body>
</html>
and called file database.php is as follows:
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
$connect= new mysqli_connect('xx','xx','xx','xx');
if ($conn->connect_errno) {
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(postcode,email)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
//NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.
if (!$sql->bind_param("ss", $postcode, $email)) {
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
}
if (!$sql->execute()) {
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
}
} else {
echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.
}
?>
Still I get nothing fed through from the form to the database. Even if I swap the variables for strings I get nothing through to the database however if I run database.php separately it works. Surely Im close to getting this working now .. any help appreciated and thanks so much for the assistance provided so far.
*************************** ORIGINAL QUESTION FOLLOWS *******************
I have a simple form as follows:
<form name="login" action="somethingelse.php" method="post" onSubmit="return doLogin()" >
<input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
<input type="hidden" name="popup" value="true" />
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php e$
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><button><input type="submit" value="OK" /></button></td>
</tr>
</table>
</form>
Because I need to use the form action to do something else, I need to use jQuery on the click of the button to send data to a database. Specifically the postcode and email address taken from the form. The part of the code relating to the jQuery is shown below:
<script language="JavaScript" >
$(document).ready(function(){
$("button").click(function(){
mysqli_query();
});
});
</script>
The called function mysqli_query is declared via an include statement and therefore lives in a different file. The function called is shown below:
mysqli_query( $connect, "INSERT INTO visitors(postcode,email) VALUES(postcode,email)");
I have been going round in circles for days with this. I know Im close to making it work but cant quite cross the finish line. Could somebody please point out what I'm doing wrong here?
WARNING: Never ever trust user input, always sanitize the input first AND use prepared statements otherwise, you're leaving youself vulnerable to SQL INJECTION ATTACKS
You're mixing up, Javascript is a clientside language, and mysqli is a PHP based function on the serverside of things.
What you should be doing is an ajax call with the values to a different PHP file that will make the database connection and insert the data.
var dataString = "postcode="+ postcode+"&email="+email;
$.ajax({
type: "POST",
url: "file_that_does_the_work.php", //Should probably echo true or false depending if it could do it
data: dataString,
success: function(feed) {
if (feed=="true") {
// DO STUFF
} else {
console.log(feed);
// WARNING THAT IT WASN'T DONE
}
}
file_that_does_the_work.php
<?
include("config.php"); // your thing that configures the connection
$postcode = sanitizationfunction($_POST["postcode"]);
$email = sanitizationfunction($_POST["email"]);
$query = $connection->prepare('INSERT INTO visitors(postcode,email) VALUES(?,?)');
$query->bindParam(1, $postcode);
$query->bindParam(2, $email);
if ($query->execute()) {
echo "true";
} else {
echo "false";
}
?>
form.php
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php echo $username?>"/>
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><input type="submit" value="OK" /></td>
</tr>
</table>
</form>
`
somethingelse.php
<?php
foreach ($_POST as $key => $value) {
echo $key."=".$value."<br/>";
}
?>
I leave connectivity part to you :D
So, as others have pointed out, you are mixing up your client-side code and your server-side code. You need to send all the form data to a php file. The jquery ajax will send the data over to the script, and determine if this call was successful or not. If the call is not successful, you can run test logic. If it is, than you can do other logic, such as alert the user of a successful form submit.
Below is an example of the process:
ajax:
<script>
var formData = 'some data' // Get your form values and save here - postcode and email
$("button").click(function(){
$.ajax ({
method: 'POST',// you can do either post or get...
url: "page_to_handle_mysql_code.php",
data: formData
success: function( response ) {
//do something like alert("Submitted Successfully!");
}
fail: function( response) {
//Do testing such as console.log(response); NOTE: Response will be what ever your php page sends back.
}
});
)};
</script>
On your php page: page_to_handle_mysql_code.php
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
//connect to mysql - I prefer prepared statements as the variables are prepared for safety when sent to MySQL
$conn = new mysqli($servername, $username, $password, $dbname);//you can either put the actually values in, or I include another php page in this one that sets my variables so I can resuse my code easily.
if ($conn->connect_errno) {
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(?,?)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
//NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.
if (!$sql->bind_param("ss", $postcode, $email)) {
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
}
if (!$sql->execute()) {
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
}
} else {
echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.
}
?>
This should help you get your values entered to MySQL. I hope it helps!
You can submit a form with jquery
mysqli_query is a function in your PHP, your javascript doesn't have access to the function. You have to make an http call from your javascript, which your PHP will receive and run mysqli_query on its end

javascript phone validataion

<?php
//include the DB connection
include("includes/config.php");
//include the header
include("includes/header.php");
?>
<?php
//checks if the form was submitted
if(isset($_POST['submit']))
{
//get form values when submitted
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$password=$_POST['password'];
$subject=$_POST['subject'];
$target_dir = "uploads/";
$target_file = $target_dir . time() . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{
mysql_query("INSERT INTO `login`(`name`,`email`,`phone`,`password`,`file`,`subject`)VALUES('$name','$email','$phone','$password',
'$target_file','$subject')");
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
<div class="form">
<form action="" method="post" name="registration" enctype="multipart/form-data" onSubmit="return formValidation();">
<table width="500" border="1" cellspacing="0" cellpadding="0" class="table">
<tr>
<td>Name</td>
<td><input name="name" type="text" class="input" placeholder="Please Enter Your Name" value="<?php //echo $userName ;?>" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" type="email" class="input" placeholder="Please Enter Your Email ID "value=" <?php //echo $userEmail ;?>" /></td>
</tr>
<tr>
<td>Phone</td>
<td><input name="phone" type="text" class="input" placeholder="Please Enter Your Phone Number" value="<?php //echo $userPhone;?>" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name="password" type="password" class="input" value="" /></td>
</tr>
<tr>
<td>Upload file</td>
<td><input name="file" type="file" class="input" value="" </td>
</tr>
<tr>
<td>Subject</td>
<td><textarea name="subject" cols="" rows="" class="input" placeholder="Please Enter Your Query "/> <?php //echo $userSubject;?></textarea></td>
</tr>
<tr>
<td></td>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</div>
<?php
//include the footer
include("includes/footer.php");
?>
<script type="text/javascript">
function formValidation()
{
var uname = document.registration.name;
var uphone= document.registration.phone;
if(allLetter(uname))
{
if(phonenumber(uphone))
{
}
}
return false;
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
</script>
for the user name the code for validation works but for the phone validation it's not working,i want phone validation for empty field check and format check and email check.help me out as i'm new to javascript
Try this code.
function formValidation()
{
var phone=document.forms["registration"]["phone"].value;
var phone_num = /^\d{10}$/;
if (phone=="")
{
alert("enter your phone number");
return false;
}
else if(phone)
{
if(!phone_num.test(phone))
{
alert("Not a valid Phone Number");
return false;
}
}
var email = document.forms["registration"]["email"].value;
if (email=="")
{
alert("enter your email id");
return false;
}
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
}
you have a typo in your phone function an extra (:
try:
if(inputtxt.value.match(phoneno))
instead of if((inputtxt.value.match(phoneno))
PS: Tip do look and use console tools while working with JS

After click reset button, the company text field will be disable and change the background color

Database
I - Internal staff
E - External staff
updatestaff.php
<html>
<head>
<link rel="stylesheet" href="js/jquery-ui-themes-1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.11.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
//---CLICK STAFF TYPE RADIO BUTTON---
$(".stafftype").click(function()
{
if($(this).val() === 'I')
{
$("#staffcompanyname").val('');
$("#staffcompanyname").attr('disabled', true);
$("#staffcompanyname").css("background-color", "#CCCCCC");
}
else
{
$("#staffcompanyname").attr('disabled', false);
$("#staffcompanyname").css("background-color", "#D7E5F2");
}
});
//---CLICK RESET BUTTON---
$('#reset').click(function(){
//[HERE]
});
});
</script>
</head>
<?php
//---DB Connection---
$query = "SELECT *
FROM staff
WHERE staff_ID = 1";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
?>
<body>
<form method="post" action="staff.php">
<table>
<tr>
<td>Staff Type : </td>
<td>
<input type="radio" name="stafftype" class="stafftype" value="I"
<?php if($row['staff_type'] == 'I') echo 'checked'; ?> />Internal
<input type="radio" name="stafftype" class="stafftype" value="E"
<?php if($row['staff_type'] == 'E') echo 'checked'; ?> />External
</td>
</tr>
<tr>
<td>Company Name : </td>
<td>
<input type="text" name="staffcompanyname" id="staffcompanyname" value="<?php echo $row['staff_company']; ?>"
maxlength="120" size="40" <?php echo ($row['staff_type'] == 'I') ? 'class="staffcompanydisablefieldcellinput" disabled' :
'class="staffcompanyfieldcellinput"'; ?> />
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Update Staff" ></td>
<td><input type="reset" name="reset" id="reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
From above code and above image:
(1) Initial
- Staff type radio button will set to Internal (Refer to database with staff_ID = 1)
- Staff company text field will be disabled (background color : #CCCCCC)
(2) Click External Type
- Staff type radio button will set to External
- Staff company text field will be enabled (background color : #D7EF52)
(3) Click Reset Button
- Staff type radio button will set to Internal
- Staff company text field will be disabled (background color : #CCCCCC)
However, when I click reset button, the staff company field was not disabled and the text field background color was not set to #CCCCCC.
How should I modify it on [HERE] section in order to get my expected output? Can someone help me?
The problem is your radio button doesnt have ID, assing ID='Internal'
Your [HERE] should be
$("#Internal").prop("checked", true).triggerHandler('click');
OR
$("#Internal").trigger('click').prop("checked", true);

Multiple checkbox delete javascript

I have this code which delete from database rows.But it removes one by one when pressing delete, checkbox not working.I want to multiple delete by checking checkbox.
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
function check() {
document.getElementById("myCheck").checked = true;
}
function uncheck() {
document.getElementById("myCheck").checked = false;
}
HTML
<a href="javascript:confirmDelete('?action=deleteurl&id=<?php echo $row[0]; ?>')">
<input type="checkbox" id="myCheck[]">delete</td>
PHP
<?php
if($_GET['action'] == "deletelink" && !empty($_GET['id']) && is_numeric($_GET['id'])) {
$result = mysql_query("SELECT * FROM books WHERE id='".intval($_GET['id']);
while ($row = mysql_fetch_array ($result) )
unlink("/home/me/public_html/upload/image/{$row['image']}");
}
Your logic is not for multiple delete
this should be html
<input type="checkbox" id="myCheck[]" class="multicheck" name="<?php echo $row[0]; ?>" value="<?php echo $row[0]; ?>">delete</td>
Multiple Delete</td>
and this should be javascript
function confirmMultiDelete() {
if (confirm("Are you sure you want to delete")) {
var str = [];
$.each(".multicheck:checked",function(){
str.push($(this).val());
});
ids = str.join(",");
document.location = '?action=deleteurl&id='+ids;
}
}
here is my approach.
You need some modification to do multiple delete as my approach.
First you have to put value in checkbox so you can get its value to
delete.
Second you have to add another button or action to delete multiple
record.
Your Code ( with Modification ):
HTML + PHP CODE
<a href="javascript:confirmDelete('?action=deleteurl&id=value="<?php echo $row[0]; ?>"')">delete
</a>
<input type="checkbox" class="delCheck" id="myCheck[]" value="<?php echo $row[0]; ?>">
</td>
<!-- This will generate html code like below -->
<!--
<td>
delete
<input type="checkbox" class="delCheck" value="1" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="2" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="3" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="4" id="myCheck[]" class="delCheck">
</td>
<td>
<input type="button" value="Delete" name="delete_value" id="delete_value" class="delCheck">
</td>
-->
<!-- Multiple Delete Button -->
<input type="button" id="delete_value" name="delete_value" value="Delete" />
Javascript + Jquery
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
$( document ).ready(function() {
$("#delete_value").on("click", function (e){
var ids = '';
$('.delCheck:checked').each(function(i){
ids += $(this).val() + ',';
});
// go to delete url with action delete_all_ur
confirmDelete('?action=delete_all_url&id='+ids)
});
});
PHP Delete Code:
if( #$_GET['action'] == "delete_all_url" )
{
$all_ids = $_GET['id'];
// Remove trailing ',' from IDs
$all_ids = trim($all_ids, ",");
// Temporary variable to check only integer value passes
$tempId = str_replace(",", "", $all_ids);
// Check id numeric or not
if ( is_numeric($tempId) ) {
$sql_query = "SELECT * FROM books WHERE id in (".intval($_GET['id'].")";
$result = mysql_query($sql_query);
while ($row = mysql_fetch_array ($result) )
unlink("/home/me/public_html/upload/image/{$row['image']}");
} else {
//echo 'errors';
}
}

Categories