I want to make some forms in a div, and in this form, there is requirement that some form can add some input text like add a row in a table and in this div can add another div to add form to write data too. I'm already success to add data but it only works in a form because my button only can submit the data if I put it in a form. I'm new in using PHP, HTML, and JavaScript, so when I was writing code, i'm still in learning too and search many website to solve this but i'm just get the answer to submit only a form.
please help me, i'm very thankful for your response
<div id="myproyek">
<div id="formtrigger" class="content">
<form id="tableToModify" name="code" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<td>Create Url</td>
<td>:</td>
<td><input type="text" name="nameURL" id="nameURL" placeholder="URL"></td>
<span class="error"><?php echo $nameURLErr;?></span>
</div>
<div class="form-group">
<td>Parameter</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="key" name="key" placeholder="Key">
<span><?php echo $keyErr ?></span>
<input type="text" id="value" name="value" placeholder="Value">
<span><?php echo $valueErr ?></span>
</div>
</form>
<input type="button" onclick="addRow()" value="Create Row" />
<div>
<label><input type="radio" name="colorRadio" value="asynchronous">Asynchronous</label>
<label><input type="radio" name="colorRadio" value="synchronous">Synchronous</label>
<div class="asynchronous box " style="display: none" >
<form id="tableAscyToModify" >
<div class="form-group">
<td>Callback Url</td>
<td>:</td>
<td><input type="text" name="createurl" placeholder="Callback URL" onfocus="this.placeholder = ''" onblur="this.placeholder = 'URL'" value="<?php echo $asyncValue?>"></td>
<span><?php echo $asyncURLErr ?></span>
</div>
<div class="form-group">
<td>Format Response</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="item-code" name="createurl" placeholder="Key">
<span><?php echo $asyncKeyErr ?></span>
<input type="text" id="item-code" name="createurl" placeholder="Value">
<span><?php echo $asyncValueErr ?></span>
</div>
</form>
<input type="button" onclick="createRowAsyc()" value="Create Row" />
</div>
<div class="synchronous box " style="display: none">
<form id="tableSyncToModify" >
<div class="form-group">
<td>Format Response</td>
<td></td>
<td></td>
</div>
<div class="form-group">
<td>Key</td>
<td>:</td>
<td>Value</td>
</div>
<div class="form-group">
<input type="text" id="item-code" name="createurl" placeholder="Key">
<input type="text" id="item-code" name="createurl" placeholder="Value">
</div>
</form>
<input type="button" onclick="createRowSync()" value="Create Row" />
</div>
</div>
</form>
</div>
<button name="submit" id="submit">Submit</button>
// i think button should be here because i want to submit all my form
</div>
Here is my PHP Code
<?php
// define variables and set to empty values
$nameURLErr = $keyErr = $valueErr = $asyncURLErr = $asyncKeyErr = $asyncValueErr = $syncURLErr = $syncKeyErr = $syncValueErr = "";
$nameURL = $key = $value = $asyncURL = $asyncKey = $asyncValue = $syncURL = $syncKey = $syncValue = "";
if (isset($_POST['value'])) {
if (empty($_POST["nameURL"])) {
$nameURLErr = "URL is required";
} else {
$nameURL = test_input($_POST["nameURL"]);
// check if name only contains letters and whitespace
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$nameURL)) {
$nameURLErr = "Only letters and white space allowed";
}
}
if (empty($_POST["key"])) {
$keyErr = "Key is required";
} else {
$key = test_input($_POST["key"]);
}
if (empty($_POST["value"])) {
$valueErr = "Value is required";
} else {
$value = test_input($_POST["value"]);
}
if (empty($_POST["asyncURL"])) {
$asyncURLErr = "URL is required";
} else {
$asyncURL = test_input($_POST["asyncURL"]);
// check if name only contains letters and whitespace
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$asyncURL)) {
$asyncURLErr = "Only letters and white space allowed";
}
}
if (empty($_POST["asyncKey"])) {
$asyncKeyErr = "Key is required";
} else {
$asyncKey = test_input($_POST["asyncKey"]);
}
if (empty($_POST["asyncValue"])) {
$asyncValueErr = "Value is required";
} else {
$asyncValue = test_input($_POST["asyncValue"]);
}
$fp = fopen('data.html', 'a');
$data = '<p> URL : '.$nameURL. '</p>'.
'<p>Key : ' . $key . '<br>Value : '. $value . '</p>' .
'<p>Async URL : ' . $asyncURL . '</p>' .
'<p>Key : ' . $asyncKey . '<br>Value : ' . $asyncValue . '</p>';
;
fwrite($fp, $data);
fclose($fp);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my Javascript code
function addRow () {
document.querySelector('#tableToModify').insertAdjacentHTML(
'beforeend',
`<form>
<div class="form-group">
<input type="text" name="name" value="" placeholder="Key" />
<input type="text" name="value" value="" placeholder="Value" />
<input type="button" value="-" onclick="removeRow(this)">
</div>
</form>`
)
}
function createRowAsyc() {
document.querySelector('#tableAscyToModify').insertAdjacentHTML(
'beforeend',
`<div class="form-group">
<input type="text" name="name" value="" placeholder="Key"/>
<input type="text" name="value" value="" placeholder="Value"/>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function createRowSync() {
document.querySelector('#tableSyncToModify').insertAdjacentHTML(
'beforeend',
`<div class="form-group">
<input type="text" name="name" value="" placeholder="Key"/>
<input type="text" name="value" value="" placeholder="Value"/>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function removeRow (input) {
input.parentNode.remove()
}
I expect the output is all the data is write in all the form, but if i put the button right in last div code, but there is nothing to change.
If i put button in
<form id="tableToModify">
</form>
data is submitted only in this data and successful submitted in text.html
Or do you have some suggestion, how i manage my form template
You can get your forms into one by using FormData()
Here we have a button element outside all forms, this will be our trigger to submit:
<div>
<form id="form-one">
<!-- the form -->
</form>
<form id="form-two">
<!-- the form -->
</form>
<button type="button" id="submit-data">
<span>Submit all forms!</span>
</button>
</div>
then in your JavaScript we collect all the FormData's into one "mothership" FormData by using loops, triggered by the button click
document.addEventListener('click', function()
{
let formData = new FormData(),
formOne = new FormData(document.getElementById('form-one')),
formTwo = new FormData(document.getElementById('form-two'));
for (let pair of formOne.entries())
{
formData.append(pair[0], pair[1])
}
for (let pair of formTwo.entries())
{
formData.append(pair[0], pair[1])
}
}, false)
Related
When i submit form it doesnot update value in database mysql.Its a form written in php.
here is my php and html. I want that the form should not reload and it must submit the changes in database without reloading the page and show preloader for 1 sec on submitting form.
HTML,PHP AND ACTION of form: Here action is the current page where this form is avalilable
detail_customer.php
<?php
$server = "localhost";
$username = "root";
$pass = "";
$dbname = "stinkspolitics_pl";
$conn = mysqli_connect($server, $username, $pass, $dbname);
if (isset($_GET['detail_customer'])) {
$quest_id = $_GET['detail_customer'];
$get_quest = "SELECT * FROM questions WHERE quest_id = '$quest_id'";
$getting_quest = mysqli_query($conn, $get_quest);
while ($row = mysqli_fetch_assoc($getting_quest)) {
$quest_title = $row['quest_title'];
$category_id = $row['category_id'];
}
}
if (isset($_POST['submit'])) {
$quest_t = $_POST['quest_t'];
$update = "UPDATE questions SET quest_title = '$quest_t' WHERE quest_id = '$quest_id'";
$run_update = mysqli_query($conn, $update);
if ($run_update) {
echo 'hello';
}
}
?>
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php
" method="POST" class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<?php echo $category_id ?>" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<?php echo $quest_title ?>" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
JS Code
index.js
$("#form-submit").on("submit", function () {
// e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: formData,
success: function (data) {
$(".alert-success").show();
$(".alert-success").fadeOut(4000);
console.log(data);
},
error: function (data) {
$(".alert-danger").show();
$(".alert-danger").fadeOut(4000);
console.log(data);
},
});
return false;
});
Ajax Success Response But not updating data in mySQL
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php" method="POST"
class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<br />
<b>Warning</b>: Undefined variable $category_id in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>62</b><br />
" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<br />
<b>Warning</b>: Undefined variable $quest_title in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>66</b><br />
" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
The condition if (isset($_POST['submit'])) { will never evaluate to true, since there is no input element in the form with name="submit" (the button with name='submit' does not send the attribute by default).
Either change the condition:
if (isset($_POST['quest_t'])) { ...
Or, include an input element with name='submit', for example:
<input name="submit" type="hidden" />
Also, make sure to move the $_POST check at the beginning of the file and ensure that no other code will be evaluated in the PHP file (e.g. the rest of the HTML code) if a POST request has been received.
Just return false after at the end of the method.
jQuery has its own way of ensuring "preventDefault()" and it is just returning false from the submit handler.
Full background on this here:
event.preventDefault() vs. return false
Issue has been solved. By changing path and then putting path of js file again.
In my app I want the user to mention how many columns he wants for the table and then enter the data for those columns and create a table with those values.
Here is what I have:
<form action="" method="post">
<label for="numOfCols">Enter Number of Fields</label>
<input name="numOfCols" type="number" id="numOfCols">
<button type="submit" class="btn btn-info" name="numOfColsSubmit" >Generate</button>
</form>
<?php if(isset($_POST["numOfCols"])): ?>
<form action="" method="post">
<label for="tbName">Enter Layout Name</label>
<input type="text" name="tbName" id="tbName" class="form-control">
<?php $numOfCols = $_POST["numOfCols"];
for ($colNum = 0 ; $colNum < $numOfCols ; $colNum++): ?>
<div class="row g-4">
<div class="col-sm">
<label for="col_name<?php $colNum ?>">Name</label><br>
<input class="form-control" id="col_name<?php $colNum ?>" type="text"
name="col_name<?php $colNum ?>" >
</div>
<div class="col-sm">
<label for="col_types<?php $colNum ?>">Type</label><br>
<select name="col_types<?php $colNum ?>" class="form-control" id="col_types<?php $colNum ?>">
<option value="int">INT</option>
<option value="varchar" >VARCHAR</option>
<option value="text">TEXT</option>
</select>
</div>
<div class="col-sm">
<label for="col_length<?php $colNum ?>">Length</label><br>
<input type="text" class="form-control" name="col_length<?php $colNum ?>" id="col_length<?php $colNum ?>">
</div>
<div class="col-sm">
<br><button type="submit" class="btn btn-success" name="submitaddcol<?php $colNum ?>">Submit</button>
</div>
</div>
<?php endfor; ?>
<button type="submit" name="createtb" class="btn">Create Layout</button>
</form>
<?php endif;?>
<?php if(isset($_POST["tbName"])){
$table->createTb($_POST['tbName']);
} ?>
and the function for creating the table :
function createTb($tb){
$arr = [];
if(isset($_POST['col_name'])){
$colName = $_POST['col_name'];
}
if(isset($_POST['col_types'])){
$colTypes = $_POST['col_types'];
}
if(isset($_POST['col_length'])){
$colLength = $_POST['col_length'];
}
echo $tb;
array_push($arr , $colName , $colTypes , $colLength);
$stmt = $this->pdo->prepare("CREATE TABLE $tb ($colName $colTypes($colLength)) ");
$stmt->execute([$_POST['name'], 29]);
$stmt->execute();
$stmt = null;
}
I was thinking of getting the data from the user, pass it to an array and then use that array in my query.
The problem is I cannot get all of the user data. If the user has 2 or more columns, it will always get the last column. Any insight?
(Putting the createTb($_POST['tbName']) inside the for loop for some reason results in now showing or calling the function at all)
You can name your input-fields as an array like:
<input type="text" name="col_name[]" value="foo" />
And get it with var_dump($_POST['col_name']);
In your example you could do like this:
<?php $numOfCols = $_POST["numOfCols"];
for ($colNum = 0 ; $colNum < $numOfCols ; $colNum++): ?>
<input class="form-control" id="col_name_<?=$colNum ?>" type="text" name="col_name[<?=$colNum ?>]" >
<input type="text" class="form-control" name="col_length[<?= $colNum ?>]" id="col_length_<?=$colNum ?>">
<?php endfor; ?>
And get the result:
if(isset($_POST['col_name']) && is_array($_POST['col_name'])) {
for($i = 0; $i < count($_POST['col_name']); $i++) {
var_dump($_POST['col_name'][$i]);
var_dump($_POST['col_length'][$i]);
}
}
I tried to create a sign up form where I need to validate if the the information entered is already exists in the database.
The code runs fine and can detect if the anything are already exists in the database.
The problem is it will clear all the form when it detects anything exists in database.
For example in below picture I try to input an email that already exists in database but in the second photo, all the form fields are clear out
Is there any ways to prevent the form from being cleared out? Its not convenience for user to re-fill the form again.
Below is my code.
<?php
include 'include/header.php';
include ('admin/include/dbcon.php');
?>
<script type="text/javascript">
$(document).ready(function() {
$("#inputState3").on('change', function() {
var val2 = $("#inputState3").val();
$.ajax({
url: "stdsec.php",
method: "post",
data: 'myvalue=' + val2
}).done(function(sec) {
$('#inputState1').html(sec);
})
})
});
</script>
<!-- STUDENT FORM SECTION START -->
<section class="Form-bg-image navbar-bottom-space fixNavColor" id="student-form">
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-sm-12 my-col">
<div class="outerdiv Signup-outerdiv">
<h1 class="Login-text">Sign Up</h1>
<div class="desc-text">New students on board are required to register to access the student
portal. <br> This only takes less than a minute. Already have an account? <a
href="studentlogin.php">Log
In</a> </div>
<hr>
<div class="InnerDiv InnerDiv2">
<form action="student_signup.php" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-12">
<input name="fname" title="Please enter your name as per IC." type="text"
class="form-control input-fields" placeholder="First Name" required
id="fullname">
<span class="text-danger" id="fname"></span>
</div>
<div class="form-group col-md-12">
<input name="fficnum" title="Enter IC Number without dashes ( - )." type="text"
class="form-control input-fields" placeholder="IC Number" required
id="std_ic">
<span class="text-danger" id="SICnum"></span>
</div>
<div class="form-group col-md-6">
<input name="pass" title="Please enter your password." type="password"
class="form-control input-fields" placeholder="Your Password" required
id="password">
<span class="text-danger" id="Spassword"></span>
</div>
<div class="form-group col-md-6">
<input name="Cpass" title="Please confirm your password." type="password"
class="form-control input-fields" placeholder="Confirm Password" required
id="cpassword">
<span class="text-danger" id="SCpassword"></span>
</div>
<div class="form-group col-md-6">
<input name="email" title="Please enter your email address." type="email"
class="form-control input-fields" placeholder="Email Address" required
id="email">
<span class="text-danger" id="Semail"></span>
</div>
<div class="form-group col-md-6">
<select name="gender" id="inputState2" class="form-control input-fields"
required="true">
<option value="">Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="form-group col-md-6">
<select name="dep" id="inputState3" class="form-control input-fields"
required="true">
<option value="">Department</option>
<?php
$data = mysqli_query($sql_con,"Select *from departments");
while ($row = mysqli_fetch_array($data)){
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['depname'] ?>
</option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-6">
<select name="session" id="inputState1" class="form-control input-fields"
required="true">
<option value="">Session</option>
</select>
</div>
<div class="form-group col-md-6">
<input name="number" type="text" class="form-control input-fields"
placeholder="Contact Number" required id="number">
<span class="text-danger" id="Snumber"></span>
</div>
<div class="form-group col-md-6">
<div class="upload-div">
<input name="img" type="file" class="form-control" id="real-input"
hidden="hidden" required id="img">
<button type="button" id="custom-button">Upload Profile Picture
</button><br class="Br-Hide">
<span id="custom-text">No file chosen</span>
</div>
<span class="text-danger" id="imgerror"></span>
</div>
</div>
<div class="form-group">
<input name="address" type="text" class="form-control input-fields"
id="inputAddress" placeholder="Enter Your Address" required>
<span class="text-danger" id="Saddress"></span>
</div>
<center>
<input name="submit" type="submit" class="btn btn-primary btn-login-form2"
value="Create New Account" onclick="return validate2();">
</center>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--
<p data-toggle="modal" data-target="#reg-success" class="forgot-para">Forgot
Password?</p>
-->
<!-- STUDENT FORM SECTION END -->
<!-- STUDENT SUCCESSFULL REGISTRATION MODAL DIALOG -->
<div class="modal fade" id="reg-success" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title forgot-heading" id="exampleModalLabel">Registration Success!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div><br>
<center><img src="../images/success-icon.svg" width="100" height="100"></center>
<div class="modal-body text-center">
<p class="password-errortxt">Congratulations, your account has been successfully created.</p>
<center>
<button name="submit" type="submit" class="btn btn-primary btn-login-form2"
onClick="parent.location='studentlogin.php'">Click Here to Login</button>
</center>
</div>
</div>
</div>
</div>
<?php
include('js/customUpload.js');
include('include/footer.php');
?>
<script type="text/javascript">
function validate2() {
var fname = document.getElementById('full_name').value;
var std_ic = document.getElementById('std_ic').value;
var email = document.getElementById('email').value;
var number = document.getElementById('number').value;
var address = document.getElementById('inputAddress').value;
var fnameCheck = /^([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){3,20}$/;
var std_icCheck = /^(([[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))([0-9]{2})([0-9]{4})$/;
var emailCheck = /^([\w-\.]+#([\w-]*\.)+[\w-]{2,4})?$/;
var numberCheck = /^(\+?6?01)[0-46-9]-*[0-9]{7,8}$/;
if (fnameCheck.test(fname)) {
document.getElementById('fname').innerHTML = " ";
} else {
document.getElementById('fname').innerHTML = "Invalid Name!";
return false;
}
if (std_icCheck.test(std_ic)) {
document.getElementById('SICnum').innerHTML = " ";
} else {
document.getElementById('SICnum').innerHTML = "Invalid IC Number - Enter IC without dashes (XXXXXXXXXXXX)";
return false;
}
if (emailCheck.test(email)) {
document.getElementById('Semail').innerHTML = " ";
} else {
document.getElementById('Semail').innerHTML = "Invalid Email Address";
return false;
}
if (!isNaN($("number").val())) {} else if (numberCheck.test(number)) {
document.getElementById('Snumber').innerHTML = " ";
} else {
document.getElementById('Snumber').innerHTML = "Invalid phone number.";
return false;
}
if ($('#inputAddress').val().length < 20 || $('#inputAddress').val() == "") {
document.getElementById('Saddress').innerHTML = "At least 20 characters";
return false;
} else {
document.getElementById('Saddress').innerHTML = " ";
}
}
</script>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$data = mysqli_query($sql_con,"select stdemail from students");
while ($row = mysqli_fetch_array($data)) {
$emaildb = $row['stdemail'];
if($emaildb == $email){
echo "<script>document.getElementById('Semail').innerHTML = '** Email already exist'; </script>";
exit();
}
}
$SICnum = $_POST['fficnum'];
$data = mysqli_query($sql_con,"select std_ic from students");
while ($row = mysqli_fetch_array($data)) {
$icnumdb = $row['std_ic'];
if($icnumdb == $SICnum){
echo "<script>document.getElementById('SICnum').innerHTML = '** IC already exist'; </script>"; //SICnum = the column ID
//exit();
return false;
}
}
$folder = "suploads/";
$filename = $_FILES['img']["name"];
$unique = uniqid().$filename;
$temname = $_FILES['img']["tmp_name"];
$size = $_FILES['img']["size"];
$target = $folder.basename($unique);
$filetype = strtolower(pathinfo($target,PATHINFO_EXTENSION));
if ($filetype !="jpg" && $filetype !="png" && $filetype !="jpeg") {
echo "<script>document.getElementById('imgerror').innerHTML = '** File is not an image'; </script>";
exit();
}
else if($size > 2097152){
echo "<script>document.getElementById('imgerror').innerHTML = '** File is larger than 2MP';</script>";
exit();
}
else {
move_uploaded_file($temname,$target);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$SICnum = $_POST['fficnum'];
$Cpass = $_POST['Cpass'];
$email = $_POST['email'];
$session = $_POST['session'];
$gender = $_POST['gender'];
$depart = $_POST['dep'];
$number = $_POST['number'];
$address = $_POST['address'];
mysqli_query($sql_con,"insert into students (full_name,std_ic,password,stdemail,session,gender,dep,snumber,img,address) values ('$fname','$SICnum','$Cpass','$email','$session','$gender','$depart','$number','$target','$address')");
echo "<script>$(document).ready(function(){ $('#reg-success').modal('show'); });</script>";
/* echo "<script>alert('You are successfully registered')</script>"; */
}
}
?>
Use the following code
<?php
include 'include/header.php';
include ('admin/include/dbcon.php');
$email = "";
?>
<script type="text/javascript">
$(document).ready(function() {
$("#inputState3").on('change', function() {
var val2 = $("#inputState3").val();
$.ajax({
url: "stdsec.php",
method: "post",
data: 'myvalue=' + val2
}).done(function(sec) {
$('#inputState1').html(sec);
})
})
});
</script>
<!-- STUDENT FORM SECTION START -->
<section class="Form-bg-image navbar-bottom-space fixNavColor" id="student-form">
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-sm-12 my-col">
<div class="outerdiv Signup-outerdiv">
<h1 class="Login-text">Sign Up</h1>
<div class="desc-text">New students on board are required to register to access the student
portal. <br> This only takes less than a minute. Already have an account? <a
href="studentlogin.php">Log
In</a> </div>
<hr>
<div class="InnerDiv InnerDiv2">
<form action="student_signup.php" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-12">
<input name="fname" title="Please enter your name as per IC." type="text" value="<?php echo #$_POST['fname']; ?>"
class="form-control input-fields" placeholder="First Name" required
id="fullname">
<span class="text-danger" id="fname"></span>
</div>
<div class="form-group col-md-12">
<input name="fficnum" title="Enter IC Number without dashes ( - )." type="text" value="<?php echo #$_POST['fficnum']; ?>"
class="form-control input-fields" placeholder="IC Number" required
id="std_ic">
<span class="text-danger" id="SICnum"></span>
</div>
<div class="form-group col-md-6">
<input name="pass" title="Please enter your password." type="password" value="<?php echo #$_POST['pass']; ?>"
class="form-control input-fields" placeholder="Your Password" required
id="password">
<span class="text-danger" id="Spassword"></span>
</div>
<div class="form-group col-md-6">
<input name="Cpass" title="Please confirm your password." type="password" value="<?php echo #$_POST['Cpass']; ?>"
class="form-control input-fields" placeholder="Confirm Password" required
id="cpassword">
<span class="text-danger" id="SCpassword"></span>
</div>
<div class="form-group col-md-6">
<input name="email" title="Please enter your email address." type="email" value="<?php echo #$_POST['email']; ?>"
class="form-control input-fields" placeholder="Email Address" required
id="email">
<span class="text-danger" id="Semail"></span>
</div>
<div class="form-group col-md-6">
<select name="gender" id="inputState2" class="form-control input-fields"
required="true">
<option value="">Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="form-group col-md-6">
<select name="dep" id="inputState3" class="form-control input-fields"
required="true">
<option value="">Department</option>
<?php
$data = mysqli_query($sql_con,"Select *from departments");
while ($row = mysqli_fetch_array($data)){
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['depname'] ?>
</option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-6">
<select name="session" id="inputState1" class="form-control input-fields"
required="true">
<option value="">Session</option>
</select>
</div>
<div class="form-group col-md-6">
<input name="number" type="text" value="<?php echo #$_POST['number']; ?>" class="form-control input-fields"
placeholder="Contact Number" required id="number">
<span class="text-danger" id="Snumber"></span>
</div>
<div class="form-group col-md-6">
<div class="upload-div">
<input name="img" type="file" class="form-control" id="real-input" value="<?php echo #$_POST['img']; ?>"
hidden="hidden" required id="img">
<button type="button" id="custom-button">Upload Profile Picture
</button><br class="Br-Hide">
<span id="custom-text">No file chosen</span>
</div>
<span class="text-danger" id="imgerror"></span>
</div>
</div>
<div class="form-group">
<input name="address" value="<?php echo #$_POST['address']; ?>" type="text" class="form-control input-fields"
id="inputAddress" placeholder="Enter Your Address" required>
<span class="text-danger" id="Saddress"></span>
</div>
<center>
<input name="submit" type="submit" class="btn btn-primary btn-login-form2"
value="Create New Account" onclick="return validate2();">
</center>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--
<p data-toggle="modal" data-target="#reg-success" class="forgot-para">Forgot
Password?</p>
-->
<!-- STUDENT FORM SECTION END -->
<!-- STUDENT SUCCESSFULL REGISTRATION MODAL DIALOG -->
<div class="modal fade" id="reg-success" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title forgot-heading" id="exampleModalLabel">Registration Success!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div><br>
<center><img src="../images/success-icon.svg" width="100" height="100"></center>
<div class="modal-body text-center">
<p class="password-errortxt">Congratulations, your account has been successfully created.</p>
<center>
<button name="submit" type="submit" class="btn btn-primary btn-login-form2"
onClick="parent.location='studentlogin.php'">Click Here to Login</button>
</center>
</div>
</div>
</div>
</div>
<?php
include('js/customUpload.js');
include('include/footer.php');
?>
<script type="text/javascript">
function validate2() {
var fname = document.getElementById('full_name').value;
var std_ic = document.getElementById('std_ic').value;
var email = document.getElementById('email').value;
var number = document.getElementById('number').value;
var address = document.getElementById('inputAddress').value;
var fnameCheck = /^([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){3,20}$/;
var std_icCheck = /^(([[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))([0-9]{2})([0-9]{4})$/;
var emailCheck = /^([\w-\.]+#([\w-]*\.)+[\w-]{2,4})?$/;
var numberCheck = /^(\+?6?01)[0-46-9]-*[0-9]{7,8}$/;
if (fnameCheck.test(fname)) {
document.getElementById('fname').innerHTML = " ";
} else {
document.getElementById('fname').innerHTML = "Invalid Name!";
return false;
}
if (std_icCheck.test(std_ic)) {
document.getElementById('SICnum').innerHTML = " ";
} else {
document.getElementById('SICnum').innerHTML = "Invalid IC Number - Enter IC without dashes (XXXXXXXXXXXX)";
return false;
}
if (emailCheck.test(email)) {
document.getElementById('Semail').innerHTML = " ";
} else {
document.getElementById('Semail').innerHTML = "Invalid Email Address";
return false;
}
if (!isNaN($("number").val())) {} else if (numberCheck.test(number)) {
document.getElementById('Snumber').innerHTML = " ";
} else {
document.getElementById('Snumber').innerHTML = "Invalid phone number.";
return false;
}
if ($('#inputAddress').val().length < 20 || $('#inputAddress').val() == "") {
document.getElementById('Saddress').innerHTML = "At least 20 characters";
return false;
} else {
document.getElementById('Saddress').innerHTML = " ";
}
}
</script>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$data = mysqli_query($sql_con,"select stdemail from students");
while ($row = mysqli_fetch_array($data)) {
$emaildb = $row['stdemail'];
if($emaildb == $email){
echo "<script>document.getElementById('Semail').innerHTML = '** Email already exist'; </script>";
exit();
}
}
$SICnum = $_POST['fficnum'];
$data = mysqli_query($sql_con,"select std_ic from students");
while ($row = mysqli_fetch_array($data)) {
$icnumdb = $row['std_ic'];
if($icnumdb == $SICnum){
echo "<script>document.getElementById('SICnum').innerHTML = '** IC already exist'; </script>"; //SICnum = the column ID
//exit();
return false;
}
}
$folder = "suploads/";
$filename = $_FILES['img']["name"];
$unique = uniqid().$filename;
$temname = $_FILES['img']["tmp_name"];
$size = $_FILES['img']["size"];
$target = $folder.basename($unique);
$filetype = strtolower(pathinfo($target,PATHINFO_EXTENSION));
if ($filetype !="jpg" && $filetype !="png" && $filetype !="jpeg") {
echo "<script>document.getElementById('imgerror').innerHTML = '** File is not an image'; </script>";
exit();
}
else if($size > 2097152){
echo "<script>document.getElementById('imgerror').innerHTML = '** File is larger than 2MP';</script>";
exit();
}
else {
move_uploaded_file($temname,$target);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$SICnum = $_POST['fficnum'];
$Cpass = $_POST['Cpass'];
$email = $_POST['email'];
$session = $_POST['session'];
$gender = $_POST['gender'];
$depart = $_POST['dep'];
$number = $_POST['number'];
$address = $_POST['address'];
mysqli_query($sql_con,"insert into students (full_name,std_ic,password,stdemail,session,gender,dep,snumber,img,address) values ('$fname','$SICnum','$Cpass','$email','$session','$gender','$depart','$number','$target','$address')");
echo "<script>$(document).ready(function(){ $('#reg-success').modal('show'); });</script>";
/* echo "<script>alert('You are successfully registered')</script>"; */
}
}
?>
I have a page with two registration forms individual and business type and individual type form is set as default the other form is hidden, it works fine. but when I switch it to second form and click on submit button it submits second form but returns to first form after submition even on errors it return to first form.
I want it to stay on second form on errors and after submition.
Here is my php :
if (isset($_POST["btnRegister"])) {
echo "Done";
}elseif (isset($_POST["btnbusiness"])) {
echo "Done";
}
HTML and js codes in my page:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<div class="col-10 clmiddle">
<label for="production"><b>Individual</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development"><b> Business</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</div>
First Form :
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second Form :
<div id="developmentSettings" style="display:none" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
EDIT: I changed JS to php, Here is the solution.
PHP codes (which get url):
$path = $_SERVER['REQUEST_URI'];
$Aurl = explode(",",$path);
for ($i=0; $i<count($Aurl);$i++){
$Burl = str_replace("?", "/", trim($Aurl[$i]));
}
$url = htmlspecialchars(basename($Burl));
$FormPostUrl = basename($path);
Html part :
Checkbox :
<div class="col-10 clmiddle" style="margin-top: 20px;">
<label for="production"><b>Individual</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php"); ?>" name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("register.php")){ echo 'checked="checked"';}?>>
<label for="development"><b>Business</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php?business");?>"
name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("business")){ echo 'checked="checked"';}?>>
</div>
First Form :
<?php if($url === htmlspecialchars("register.php")){?>
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second form:
<?php } elseif($url === htmlspecialchars("business")){ ?>
<div id="developmentSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
<?php } ?>
You can use PHP to control whether display:none is added to your divs or not. Use an if statement (or a ternary operator might be neater syntax in the context) to make the decision about what to echo. Since the default is to display the production settings form, we only need to check whether the other form has been submitted or not, in order to know whether to change that.
e.g. something like this (untested):
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" <?php echo (isset($_POST["btnRegister"]) ? "" : 'checked="checked"'); ?> />
and
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" <?php echo (isset($_POST["btnRegister"]) ? 'checked="checked"' : ""); ?> />
and
<div id="productionSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "style='display:none'" : ""); ?>>
and
<div id="developmentSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "" : "style='display:none'"); ?>>
P.S. Unless you've massively simplified these forms for the purpose of your example, they appear to be basically identical. It's questionable whether you actually need two separate forms at all. The only difference appears to be the choice between "individual" and "business" - that could be handled by a single form with a radio button to choose the type, which would then simplify how you handle the postback as well, and reduce the amount of duplicated code and HTML. Of course if you're actually capturing more distinct fields for these forms than you've shown, then these remarks don't really apply.
CS-Cart ajax is working fine, I am also getting response but how can I use this response with html/js on my view(checkout.tpl) file.
Controller (front-end) : send_sms.php
use Tygh\Registry;
use Services_Twilio;
use Tygh\Ajax;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($mode == 'send_sms') {
$status = 1;
$response = array(
'status' =>$status,
'data' =>'Hello World',
);
if($status == 1) {
fn_set_notification('N', fn_get_lang_var('success'), fn_get_lang_var('sms_sent'), true);
} else {
fn_set_notification('E', fn_get_lang_var('warning'), fn_get_lang_var('sms_failed'), true);
}
$val=json_encode($response);
Registry::get('ajax')->assign('result', $val);
}
exit;
}
View checkout.tpl (design/themes/responsive/templates/views/checkout/checkout.tpl)
<div id="result">
<!-- id="result" -->
<!-- result -->
</div>
<h2>Verify your number</h2>
<form class="cm-ajax" action="index.php" method="post" name="send_sms">
<input type="hidden" name="result_ids" value="result" />
<div class="form-control send_sms_block">
<input type="text" name="country_code" id="country_code" disabled value="+92"/>
<input type="text" name="carrier_code" id="carrier_code" disabled value="300"/>
<i class="ty-icon-down-micro open_cr"></i>
<input type="text" name="phone" id="phone"/>
<div class="carrier_list hidden">
<ul>
<li>301</li>
<li>302</li>
</ul>
</div>
</div>
<div class="clearfix"></div>
<input class="ty-btn ty-btn__big" id="send_sms" type="submit" value="Send Pin" name="dispatch[send_sms.send_sms]"/>
</form>
Please try the following solution:
php file:
use Tygh\Registry;
use Services_Twilio;
use Tygh\Ajax;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($mode == 'send_sms') {
$status = 1;
$response = array(
'status' =>$status,
'data' =>'Hello World',
);
if($status == 1) {
fn_set_notification('N', fn_get_lang_var('success'), fn_get_lang_var('sms_sent'), true);
} else {
fn_set_notification('E', fn_get_lang_var('warning'), fn_get_lang_var('sms_failed'), true);
}
$val=json_encode($response);
Registry::get('view')->assign('result', $val);
Registry::get('view')->display('views/path/to/tpl/file.tpl');
}
exit;
}
tpl file:
<div id="result">
{if $result}{$result}{/if}
<!--result--></div>
<h2>Verify your number</h2>
<form class="cm-ajax" action="index.php" method="post" name="send_sms">
<input type="hidden" name="result_ids" value="result" />
<div class="form-control send_sms_block">
<input type="text" name="country_code" id="country_code" disabled value="+92"/>
<input type="text" name="carrier_code" id="carrier_code" disabled value="300"/>
<i class="ty-icon-down-micro open_cr"></i>
<input type="text" name="phone" id="phone"/>
<div class="carrier_list hidden">
<ul>
<li>301</li>
<li>302</li>
</ul>
</div>
</div>
<div class="clearfix"></div>
<input class="ty-btn ty-btn__big" id="send_sms" type="submit" value="Send Pin" name="dispatch[send_sms.send_sms]"/>
</form>
Please replace on send_sms.php
$val=json_encode($response);
Registry::get('ajax')->assign('result', $val);
with
echo '<div id="result">'.json_encode($response).'</div>';