php form with database embed in wordpress - php

I am creating custom form in php and using database. I want to integrate that form in wordpress; for this i create one template(customform.php) and adding in page. My php code is smoothly running on xampp but not in wordpress.
Please help me to integrate code in wordpress.
/*CustomForm php*/
<?php /* Template Name: CustomForm */ ?>
<?php require_once("conn.php");?>
<?php get_header(); ?>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<div id="content" class="full-width">
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<body>
<form name="course_information" id="course_information" method="post" action="course_information_action.php" >
<div>
<h1 class="heading">Product Details</h1>
<h3>Product Type</h3>
<?php
$sql = "select id,course from course_master";
$result = mysqli_query($con,$sql);
$selectbox = '';
$selectbox .= '<select id="course_master" name="course_master" class="select_style"><option value="0"> -- select --</option>';
while($data = mysqli_fetch_assoc($result))
{
$selectbox .= "<option value=".$data['id'].">".$data['course']."</option>";
}
$selectbox .= '</select>';
echo $selectbox;
?>
<h3>Product</h3>
<div><select class="select_style" id="course_details" name="course_details" >
<option value="0"> -- select --</option>
</select></div>
<p></p>
<div id="ex_data">
<input type="checkbox" name="check" id="check" value="" /> I need a product demonstration, installation assistance and for other queries at no additional cost</div>
<p></p>
<div id="after_check">
<div><textarea rows="5" cols="50" name="requirements" id="requirements" placeholder="Please provide your requirement here"></textarea></div>
<h3>Address</h3>
<div><textarea rows="5" cols="50" name="address" id="address" placeholder="Please provide your address for visit purpose"></textarea></div>
</div>
<span id="key_val">
<h3>Please enter existing serial for extend subscription: </h3>
<div><input type="text" name="key" id="key" value="" /></div>
</span>
<h3>No. of licenses<span class="star_require">*</span> : </h3>
<div><input type="text" name="licenses" id="licenses" value="" required /></div>
<h3>Sub Total : </h3>
<span id="sub_total"></span>
<div><input type="hidden" name="price" id="hidden_subtotal" value="" /></div>
<div><input class="form_btn" type="submit" id="continue_first" value="continue" /></div>
</div>
<div id="contact_details">
h1 class="heading">Contact Details</h1>
<h3>Email Address<span class="star_require">*</span>:</h3>
<div><input type="text" id="email" name="email" value="" required /></div>
<h3>Mobile <span class="star_require">*</span>: </h3>
<div><input type="text" id="mobile" name="mobile" value="" maxlength="10" required /></div>
<div><input class="form_btn" type="submit" id="continue" value="continue" /></div>
</div>
<div id="billing_details">
h1 class="heading">Billing Details</h1>
<h3>Your Name/Organisation Name<span class="star_require">*</span>:</h3>
<div><input type="text" id="name" name="name" value="" required /></div>
<h3>Your Area PIN code <span class="star_require">*</span>: </h3>
<div><input type="text" id="pincode" name="pincode" value="" maxlength="10" required /></div>
<div><input class="form_btn" type="submit" id="submit" value="submit" /></div>
</div>
</form>
</div>
<?php endwhile; ?>
</div>
<?php get_footer();
/*contact form.js*/
// JavaScript Document
$(document).ready(function(){
$("#key_val").hide();
$("div#ex_data").hide();
$("div#after_check").hide();
$no = $("#licenses").val();
$("#licenses").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
$("#course_master").change(function(){
var cid = $(this).val();
if(cid == 2)
{
$("#key_val").show();
$('#licenses').attr('disabled', 'disabled');
$("div#ex_data").css("display","none");
}
else{
$("#key_val").hide();
$("div#ex_data").show(1000);
$("#licenses").removeAttr("disabled");
}
$.ajax({
type:"POST",
url:"get_course_details.php",
data:"cid="+cid,
success:function(msg)
{
$("#course_details").html(msg);
}
});
});
$("#course_details").change(function(){
var id = $(this).val();
$.ajax({
type:"POST",
url:"get_course_info.php",
data:"id="+id,
success:function(msg)
{
$("#hidden_subtotal").val(msg);
if($no == '')
{
var total = msg * 1;
$("#sub_total").text(total);
}
else
{
var total = msg * $no;
$("#sub_total").text(total);
}
}
});
});
$("#check").click(function(){
if($(this).is(":checked")){
$("div#after_check").show(1000);
$("div#after_check #address").attr("required","true");
$("div#after_check h3").append("<span class='star_require'>*</span>");
}
else
{
$("div#after_check").hide(1000);
$("div#after_check #address").attr("required","false");
}
});
$("#key").blur(function(){
var key = $("#key").val();
$.ajax({
type:"POST",
url:"validate_key.php",
data:"key="+key,
success:function(msg)
{
if(msg ==1)
{
$("#licenses").removeAttr("disabled");
}
else
{
$('#licenses').attr('disabled', 'disabled');
}
}
});
});
$("#licenses").blur(function(){
var subtotal = $("#hidden_subtotal").val();
if(!isNaN(subtotal) && subtotal != '' && subtotal != 0)
{
subtotal = subtotal * $("#licenses").val();
$("#sub_total").text(subtotal);
}
});
$("#continue_first").click(function(){
$("div#contact_details").css("display","block");
});
$("#continue").click(function(){
$("div#billing_details").css("display","block");
});
$("#submit").click(function(){
var email = $("#email").val();
var mobile = $("#mobile").val();
var pincode = $("#pincode").val();
if( !isValidEmailAddress( email ) ) {
alert("invalid email address!"); return false;
}
else if(isNaN(mobile) || (mobile.length < 10) )
{
alert("invalid mobile no!"); return false;
}
else if(isNaN(pincode))
{
alert("Invalid Pincode!");return false;
}
else{
alert("success");
$( "#course_information" ).submit();
return true;
}
});
});
//if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
};

Firstly for integrating from in wordpress you don't need to create config file and include. Just create template in theme which you are using and create page in wordpress admin and call this template.

Related

jQuery AJAX Update and Show/Hide Div

Need some help doing my update Ajax call. What I want my code to do is to show when on click my update form and pass the data from the form to my update via AJAX. So far the form isn't showing on click nor is the update working. Everything else seems to be working right except for that.
index.php
<?php include 'includes/header.php' ?>
<div class="main" id="maincontent">
<div class="main-section">
<div class="add-section">
<form action="app/add.php" method="POST" autocomplete="off">
<?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title"
style="border-color: #ff6666"
placeholder="This is required" aria-label="You need to create a to do!"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Month Not Required" aria-label="Enter a month if needed"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Year Not Required" aria-label="Enter a year if needed"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php }else{ ?>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title" placeholder="Enter a To Do" aria-label="Enter a To Do"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Enter Month [1-12]" aria-label="Enter month if needed for your to do"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Enter Year [yyyy]" aria-label="Enter a year if needed for your to do"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php } ?>
</form>
</div>
<?php
$todos = $conn->query("SELECT * FROM todos ORDER BY id DESC");
?>
<div class="show-todo-section">
<?php if($todos->rowCount() <= 0){?>
<div class="todo-item">
<div class="empty">
<p>Enter a To Do!</p>
<img src="img/f.jpg" alt="Notebook" width="100%" height="175px" />
</div>
</div>
<?php } ?>
<?php while($todo = $todos->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="todo-item">
<span id="<?php echo $todo['id']; ?>" class="remove-to-do" aria-label="Delete"><i class="fa fa-trash" style="font-size:18px"></i></span>
<span id="<?php echo $todo['id']; ?>" class="update-to-do" aria-label="Edit">
<i class="fa fa-pencil" style="font-size:18px"></i></span>
<?php if($todo['checked']) { ?>
<input type="checkbox" data-todo-id="<?php echo $todo['id']; ?>" class="check-box" checked />
<h2 class="checked"><?php echo $todo['title'] ?></h2>
<?php }else{ ?>
<input type="checkbox" data-todo-id="<?php echo $todo['id']; ?>" class="check-box">
<h2><?php echo $todo['title'] ?></h2>
<?php } ?>
<br>
<small>Created: <?php echo $todo['date_time'] ?> </small>
<div style="display:none;" class="update"><?php include 'updateForm.php'?></div>
<!---->
</div>
<?php } ?>
jQuery
<script>
$(document).ready(function(){
$('.remove-to-do').click(function(){
const id = $(this).attr('id');
$.post("app/remove.php",
{
id: id
},
(data) =>{
if(data){
$(this).parent().hide(600);
}
}
);
});
$(".check-box").click(function(e){
const id = $(this).attr('data-todo-id');
$.post("app/check.php",
{
id: id
},
(data) =>{
if(data != 'error')
{
const h2 = $(this).next();
if(data === '1'){
h2.removeClass('checked');
}else{
h2.addClass('checked');
}
}
}
);
}); /* */
$(".update-to-do").click(function(e){
const id = $(this).attr('id');
var title = $(this).attr('id'); //find
var month = $(this).attr('id');
var year = $(this).attr('id');
$.post("app/update.php",
{
id: id,
title: title,
month: month,
year : year
},
(data) =>{
//alert(id);
if(data != 'error')
{
var x = document.getElementsByClassName(".update");
if(form.hide()){
form.show();
}else{
form.hide();
}
}
}
);
});
});
updateForm.php
<div class="add-section">
<form action="app/update.php" method="POST" autocomplete="off">
<?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
<label for="id" style="display:none;"></label>
<input type="hidden" id= "id" name="id" value="<?php echo $_GET['id']; ?>" aria-label=""/>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title"
style="border-color: #ff6666"
placeholder="This is required" aria-label="You need to create a to do!"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Month Not Required" aria-label="Enter a month if needed"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Year Not Required" aria-label="Enter a year if needed"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php }else{ ?>
<label for="id" style="display:none;"></label>
<!--<input type="hidden" id= "id" name="id" value="<?php //echo $_GET['id']; ?>" aria-label="id"/> -->
<label for="title">To Do*</label>
<input type="text" id= "title" name="title" placeholder="Enter a To Do" aria-label="Enter a To Do"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Enter Month [1-12]" aria-label="Enter month if needed for your to do"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Enter Year [yyyy]" aria-label="Enter a year if needed for your to do"/>
<div class="pad"></div>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php } ?>
</form>
</div>
update.php
<?php
if(isset($_POST['id'])){
require '../includes/conn.php';
include 'func.php';
$id = $_POST['id'];
echo $id;
$title = $_POST['titleUp'];
$month = $_POST['monthUp'];
$year = $_POST['yearUp'];
$dateMonth;
$futureDate;
if(empty($id))
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
else
{
if( (!empty($title)) && (empty($month)) && (empty($year)) )
{ //need to filter 0 so its registered as not empty
$title = validTitle($title);
$stmt = $conn->prepare("UPDATE todos(title) VALUE(?) WHERE id=?");
$res = $stmt->execute([$title, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else if( (!empty($title)) && (!empty($month)) && (empty($year)) )
{
$title = validTitle($title);
$month = validMonth($month);
$dateMonth = dateMonth($month);
$year = date("Y");
$futureDate = futureDate($dateMonth, $year);
$stmt = $conn->prepare("UPDATE todos (title, future_datetime) VALUES (?,?) WHERE id=?");
$res = $stmt->execute([$title ,$futureDate, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else if( (!empty($title)) && (!empty($month)) && (!(empty($year))))
{
$title = validTitle($title);
$month = validMonth($month);
$dateMonth = dateMonth($month);
$year = validYear($year);
$futureDate = futureDate($dateMonth, $year);
$stmt = $conn->prepare("UPDATE todos (title, future_datetime) VALUES (?,?) WHERE id=?");
$res = $stmt->execute([$title ,$futureDate, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
}
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
?>
You are POSTing to the page but checking for GET.
Good manual pages to read:
Handling external variables
Example:
$.post("app/update.php",
{
id: id
alert(id);
},
That will send a POST to the app/update.php script you have which contains the following:
<?php
// $GET is not the same as $_GET
if(isset($GET['id'])){
require '../includes/conn.php';
include 'func.php';
$id = $GET['id'];
echo $id;
This will not work given that you are POSTing but looking incorrectly at $GET (which should be $_GET).
To fix change the following lines to:
<?php
if($_POST['id']){
require '../includes/conn.php';
include 'func.php';
$id = $_POST['id'];
echo $id;
Please note that $GET and $_GET aren't the same things, nor are $POST and $_POST.

How to submit a form data using Jquery ajax and php

This Jquery code isn't displaying my error message atleast... Each time i submit the form i expect a success or error message but it doesn't seem like it is responding...
<form method="POST" id="comment_form">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name">
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter your comment" cols="30" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0">
<input type="submit" name="submit" id="submit" class="btn btn-info" value="submit">
</div>
</form>
<span id="comment_message"></span>
//add_comment.php page
<?php require_once("../include/database.php"); ?>
<?php
$error = $comment_name = $comment_content = "";
if(empty($_POST["comment_name"])){
$error .= '<p class="text-danger">Name is required</p>';
}else{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"])){
$error .= '<p class="text-danger">Comment is required</p>';
}else{
$comment_content = $_POST["comment_content"];
}
if($error == ''){
// $comments = new Comment();
// $comments->parent_comment_id = $_POST["comment_id"];
// $comments->comment = $comments;
// $comments->comment_sender_name = $comment_name;
// $comments->save();
$sql = "INSERT INTO comments (parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)";
$statement = $database->query($sql = array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
//Jquery code
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:{form_data:form_data},
dataType:"json",
success:function(data){
if(data.error != ''){
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
}
}
});
});
});
Please i need to know why the submit button isn't responding...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
The necessary bootstrap and jquery libraries were added...

What's wrong with my AJAX and PHP whern I call it to login?

I have some trouble with my login form using ajax and php, could somebody con solve this??
This is code html:
login.html
<div id="id01" class="modal">
<form class="modal-content animate" action="" method="POST" id="login-form">
<div class="container">
<label for="login-email"><b>Username</b></label>
<input type="text" placeholder="Enter Email" id="login-email" name="login-email" required>
<label for="login-password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="login-password" name="login-password" required>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label><br>
<span id="showError"></span>
<button type="submit" id="btn-login" name="btn-login">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancel-btn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#btn-submit").click(function{
var login-email = $("#login-email").val();
var login-password = $("#login-password").val();
var error = $("#showError");
if(login-email != "" && login-password != ""){
$.ajax({
url: "checkLogin.php",
type: "POST",
data: { login-email: login-email, login-password: login-password},
success: function(response){
var msg = "";
if(response == "success"){
window.location = 'profile.php';
} else {
msg = "Tên đăng nhập hoặc mật khẩu không chính xác.";
}
$('#id01').css({"display": "block"});
error.html(msg);
}
});
} else {
error.html("Email đăng nhập hoặc mật khẩu không được bỏ trống.");
return false;
}
});
});
</script>
and this is code php
login.php
if(isset($_POST["btn-login"])){
$email = trim($_POST["login-email"]);
$password = trim($_POST["login-password"]);
$sql_login = "SELECT email, password, permission FROM users where email='$email' and password='$password'";
$db->query($sql_login);
$rows = $db->findOne();
$permission = $rows['permission'];
if($rows['email'] == $email && $rows['password'] == $password){
echo "success";
} else {
echo "fail";
}
exit();
}
It seem to be not to load into ajax and php code cause i've try so many time but i didn't know the bugs in here.
you call checkLogin.php but the code php is in login.php
In the login.php code, you check the btn-login but the post data from client have no btn-login
{ login-email: login-email, login-password: login-password}
so the if block will never work.
if(isset($_POST["btn-login"])){
...
}
you can change like this
if(isset($_POST["login-email"]) && isset($_POST["login-password"])){
...
}
It appears at first glance that your jQuery is referencing btn-submit but your html defines this as btn-login instead.

My php vairables are not working properly beacuse of jQuery

Whenever I hit submit button my first name, last name and email are empty even when they are filled up properly so they return red color fonts.
Here is the PHP code:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$college = mysqli_real_escape_string($conn, $_POST['college']);
$pwd = mysqli_real_escape_string($conn, $_POST['password']);
// Error handlers
$errorfirst=false;
$erroremail=false;
$errorlast=false;
$errorpwd=false;
// Check for empty fields
if (empty($first) || empty($email) || empty($pwd)) {
echo "
<span class='form-error'>*Please check one of the fields before submitting<br></span>
<span class='form-error'>*Please check first name <br></span>
<span class='form-error'>*Please check last name <br></span>
<span class='form-error'>*Please check email <br></span>
";
$errorfirst=true;
$erroremail=true;
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
echo "<span class='form-error'>*write properly</span>";
$errorfirst=true;
$errorlast=true;
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>*write a proper email</span>";
} else {
$sql = "SELECT * FROM name WHERE user_email='$email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo "<span class='form-error'>This E-mail ID is already existed</span>";
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO name (id,user_first, user_last, user_email, user_uid, user_pwd) VALUES (NULL,'$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
}
}
}
}
} else {
header("Location: ../signupform.php");
exit();
}
?>
<script type="text/javascript">
$('.first-input,.last-input,.email-input').removeClass('input-error');
var errorfirst="<?php echo '$errorfirst'; ?>";
var errorlast="<?php echo '$errorlast'; ?>";
var erroremail="<?php echo '$erroremail'; ?>";
if (errorfirst==true) {
$('.first-input').addClass('input-error');
}
if (errorlast==true) {
$('.last-input').addClass('input-error');
}
if (erroremail==true) {
$('.email-input').addClass('input-error');
}
if (erroremail==false && errorfirst==false && errorlast==false) {
$('.first-input,last-input,.email-input').val('');
}
</script>
It is not sending any value to the database. I used jQuery to validate form without refreshing but I think because of jQuery my form is not working
Here is my jQuery code
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$(".first-input").val();
var last=$(".last-input").val();
var email=$(".email-input").val();
var college=$(".college-input").val();
var password=$(".password-input").val();
var submit=$(".signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>
And here is my HTML form
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button type="submit" name="button">sign-up</button>
</div>
</form>
Help me over this issue and I also don't know about security in PHP forms so you can aslo suggest me some tips over that, I will really appreciate because I am want to be a professional back-end developer and now I am a newbie
Your jQuery uses $(".first-input").val(), but you have class="first-input" on the DIV, not the input.
Either move the class attribute to the inputs, or change the selector to $(".first-input input").val() (and similarly for all the other inputs).
You need to grab the input, not the container
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input id="first-input" type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input id="last-input" type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input id="email-input" type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input id="college-input" type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input id="password-input" type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button id="signup-btn" type="submit" name="button">sign-up</button>
</div>
</form>
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$("#first-input").val();
var last=$("#last-input").val();
var email=$("#email-input").val();
var college=$("#college-input").val();
var password=$("#password-input").val();
var submit=$("#signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>

AJAX Can't be Executed in CodeIgniter Form Submission

I'm new in AJAX programming and working on a project that should use AJAX.
I'm using PHP with CodeIgniter framework, and I want to create forms that when submitted, it will return a success message without reloading the page, that's why I chose ajax. But from the code that I have made, it works without reading the AJAX, it move to another page and of course, no success message to be displayed
So my main problem is my AJAX form submission can't be executed and I don't understand why.
Any help would be appreciated.
Here is my controller.php
public function index()
{
$this->form_validation->set_rules('advice', 'Advice', 'required');
$data["CatId"]=$this->viewbook_model->getCategory();
$this->ckeditor->basePath = base_url().'assets/ckeditor/';
$this->ckeditor->config['toolbar'] = array(
array( 'Source', '-', 'Bold', 'Italic', 'Underline', '-','Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo','-','NumberedList','BulletedList' )
);
$this->ckeditor->config['language'] = 'it';
$this->ckeditor->config['width'] = '730px';
$this->ckeditor->config['height'] = '300px';
//Add Ckfinder to Ckeditor
$this->ckfinder->SetupCKEditor($this->ckeditor,'../../assets/ckfinder/');
if($this->session->userdata('is_logged_in')){
$this->load->model('feedback_model');
$data['feedback'] = $this->feedback_model->get_subject();
$advice_list = $this->feedback_model->get_subject();
$x = 0;
foreach($advice_list AS $al)
{
$data['feedback'][$x] = array(
'CategoryAdviceId' => $al['CategoryAdviceId'],
'CategoryAdviceName' => $al['CategoryAdviceName']
);
$x++;
}
$data['booklist'] = $this->feedback_model->find($this->session->userdata('username'));
$book_list = $this->feedback_model->find('username');
$y = 0;
foreach($book_list AS $bl)
{
$data['booklist'][$y] = array(
'AssetTitle' => $bl['AssetTitle'],
'bi' => $bl['bi']
);
$y++;
}
$data['adviceid'] = $this->feedback_model->get_adviceId();
$adviceid_list = $this->feedback_model->get_adviceId();
$x = 0;
foreach($adviceid_list AS $adv)
{
$data['adviceid'][$x] = array(
'AdviceId' => $adv['AdviceId']
);
$x++;
}
$page_content["page_title"] = "Send Feedback";
$page_content["title"] = "Suggestion and Feedback";
$page_content["icon_title"] = "home";
$menu_params["current_navigable"] = "Feedback";
$menu_params["sub_current_navigable"] = "";
$page_content["menu"] = $this->load->view("main_menu", $menu_params, true);
$page_content["content"] = $this->load->view("feedback", $data, true);
$page_content["navmenu"] = $this->load->view("nav_menu", $data, true);
$this->load->view("template/main_template", $page_content);
}else{
redirect('login/restricted');
}
}
//this is the function that sent data to model and return json to view for display success message
function insert_to_db()
{
$this->feedback_model->insert_into_db();
echo json_encode('true');
}
this is my form code in view.php
<form id="feedback_form" name="feedback_form" action="<?php echo base_url();?>feedback/feedback/insert_to_db" method="post" class="form-horizontal" novalidate="novalidate">
<div class="control-group">
<!--FEEDBACK TYPE-->
<label class="span2 control-label" >Feedback for</label>
<div class="controls with-tooltip">
<select class="input-tooltip span5" tabindex="2" id="CategoryAdviceSelect" name="CategoryAdviceSelect" onchange="showhidebook();" >
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($x = 0 ; $x < count($feedback) ; $x++)
{ ?>
<option value="<?php echo $feedback[$x]['CategoryAdviceId']?>"><?php echo $feedback[$x]['CategoryAdviceName'] ?></option>
<?php
} ?>
</select>
</div>
</div>
<!--SUBJECT-->
<div class="control-group">
<label for="limiter" class="control-label">Subject</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="Subject" name="Subject" placeholder="Type Your Feedback Subject.." />
<p class="help-block"></p>
</div>
</div>
<div id="emptybox"></div>
<!--CHOOSE BOOK-->
<div id="showupbox" style="display: none;">
<div class="control-group">
<label class="control-label">Choose Book</label>
<div class="controls">
<select class="chzn-select span5" tabindex="2" id="BookSelect" name="BookSelect">
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($y = 0 ; $y < count($booklist) ; $y++)
{ ?>
<option value="<?php echo $booklist[$y]['bi']?> - <?php echo $booklist[$y]['AssetTitle']?>"><?php echo $booklist[$y]['AssetTitle']?></option>
<?php
} ?>
</select>
</div>
</div>
</div>
<!--ADVICE-->
<div class="control-group">
<label for="limiter" class="control-label" >Suggestion</label>
<div class="controls">
<?php echo $this->ckeditor->editor("Advice",""); ?>
</div>
</div>
<!--Type Advice ID-->
<div class="control-group hidden">
<label for="limiter" class="control-label" >Sugg</label>
<div class="controls">
<?php
for($x = 0 ; $x < count($adviceid) ; $x++)
{ ?>
<input type="text" class="span5" maxlength="50" id="TypeAdviceId" name="TypeAdviceId" value="<?php echo $adviceid[$x]['AdviceId']?>"/>
<?php
} ?>
<p class="help-block"></p>
</div>
</div>
<div class="control-group hidden">
<label for="limiter" class="control-label" >Sugg</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="NoBook" name="NoBook" value="-"/>
<p class="help-block"></p>
</div>
</div>
<!--div class="alert alert-success">
<a class="close" data-dismiss="alert">×</a>
<strong>Success!</strong> Thanks for your feedback!
</div-->
<div class="bton1">
<button class="btn btn-primary round" type="submit" id="btnSubmit">Submit</button>
<button class="btn btn-primary round" type="refresh">Reset</button>
</div>
</form>
this is my script and AJAX code:
$(document).ready(function() {
//this is for CKEDITOR validation
for(var name in CKEDITOR.instances) {
CKEDITOR.instances["Advice"].on("instanceReady", function() {
// Set keyup event
this.document.on("keyup", updateValue);
// Set paste event
this.document.on("paste", updateValue);
});
function updateValue() {
CKEDITOR.instances["Advice"].updateElement();
$('textarea').trigger('keyup');
}
}
//this is my form validation
$("#feedback_form").validate({
ignore: 'input:hidden:not(input:hidden.required)',
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:{
required: function(element){
return $("#CategoryAdviceSelect").val()==1;
}
}
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required",
},
errorElement: "span",
errorPlacement: function (error, element) {
if ($(element).attr('name') == 'Advice') {
$('#cke_Advice').after(error);
} else {
element.after(error);
}
},
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
//this is my ajax submission
$("#btnSubmit").click(function() {
var formURL = $(this).attr("action");
var methodtype = $(this).attr("method");
$.ajax({
url : formURL,
type: methodtype,
data : {
CategoryAdviceSelect:CategoryAdviceSelect,
Subject:Subject,
Advice:Advice,
BookSelect:BookSelect,
TypeAdviceId:TypeAdviceId,
NoBook:NoBook
},
ajaxOptions: {
dataType: 'json'
},
success : function(data){
setTimeout(function() {location.reload(true)}, 1700);
$('#success .success-content span').html('Thankyou for your <b>feedback</b>');
$('#success').fadeIn();
setTimeout(fade_out, 1200);
}
});
return false;
});
});
instead of form tag just use: (in codeigniter)
<?php $attr = array('id'=>'feedback_form', 'name'=>'feedback_form', 'class'='form-horizontal', 'novalidate'=>'novalidate');?>
<?php echo form_open('feedback/feedback/insert_to_db', $attr);?>
change in ajaxfunction (change button click event to form submit event)
$("#feedback_form").submit(function(e) {
e.preventDefault();
var formURL = $(this).attr("action");
var methodtype = $(this).attr("method");
$.ajax({
url : formURL,
type: methodtype,
data : {
CategoryAdviceSelect:CategoryAdviceSelect,
Subject:Subject,
Advice:Advice,
BookSelect:BookSelect,
TypeAdviceId:TypeAdviceId,
NoBook:NoBook
},
ajaxOptions: {
dataType: 'json'
},
success : function(data){
setTimeout(function() {location.reload(true)}, 1700);
$('#success .success-content span').html('Thankyou for your <b>feedback</b>');
$('#success').fadeIn();
setTimeout(fade_out, 1200);
}
});
return false;
});

Categories