How to submit a form data using Jquery ajax and php - 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...

Related

AJAX Contact form unable to find API Route, throwing 404 Error in console in Codeigniter 4

i have a user profile page (index.php | View) where any user can fill the contact form and send a message to particular user(whose profile is open). when i am trying to submit from it give me 404 Error and unable to find the route for contact_user Controller function.
here is my code for the same
here is the contact form code from profile view
<!-- Contact -->
<section class="resume-section" id="contact">
<div class="resume-section-content">
<h2 class="mb-5">Contact</h2>
<form method="POST" name="contact_us_form" id="contact_us_form">
<?php
foreach ($user_data as $key) {
?>
<input type="hidden" id="user_id" name="id" value="<?= $key->user_id ?>">
<?php
}
?>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_name" name="contact_form_name"
placeholder="Your Name">
<span class="text-danger" id="error_name"></span>
</div>
<br>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_mobile" name="contact_form_mobile"
placeholder="Your Mobile" pattern="[1-9]{1}[0-9]{9}">
<span class="text-danger" id="error_mobile"></span>
</div>
<br>
<div class="form-group">
<input type="email" class="form-control" id="contact_form_email" name="contact_form_email"
placeholder="Your Email">
<span class="text-danger" id="error_email"></span>
</div>
<br>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_subject" name="contact_form_subject"
placeholder="Message Subject">
<span class="text-danger" id="error_subject"></span>
</div>
<br>
<div class="form-group">
<textarea class="form-control" id="contact_form_message" name="contact_form_message"
placeholder="Message" rows="3"></textarea>
<span class="text-danger" id="error_message"></span>
</div>
<br>
<div class="form-group">
<div class="thankyou-message" id="thankyou-message" style="color:green"></div>
</div>
<br>
<input type="submit" class="btn btn-primary btn-block" id="contact_us" name="contact_us" value="SUBMIT">
</form>
</div>
</section>
here is my javascript Ajax code
jQuery('#contact_us_form').on('submit', function(e){
// alert('hello');
e.preventDefault();
// Name Validation
if ($.trim($('#contact_form_name').val()).length == 0) {
error_name = 'Please enter your name';
$('#error_name').text(error_name);
} else {
error_name = '';
$('#error_name').text(error_name);
}
// Mobile Validation
if ($.trim($('#contact_form_mobile').val()).length == 0) {
error_mobile = 'Please enter your Mobile';
$('#error_mobile').text(error_mobile);
} else {
error_mobile = '';
$('#error_mobile').text(error_mobile);
}
// Email Validation
if ($.trim($('#contact_form_email').val()).length == 0) {
error_email = 'Please enter your Email';
$('#error_email').text(error_email);
} else {
error_email = '';
$('#error_email').text(error_email);
}
// Subject Validation
if ($.trim($('#contact_form_subject').val()).length == 0) {
error_subject = 'Please enter Message Subject';
$('#error_subject').text(error_subject);
} else {
error_subject = '';
$('#error_subject').text(error_subject);
}
// Message Validation
if ($.trim($('#contact_form_message').val()).length == 0) {
error_message = 'Please enter Your Message';
$('#error_message').text(error_message);
} else {
error_message = '';
$('#error_message').text(error_message);
}
if (error_name != '' || error_mobile != '' || error_email != '' || error_subject != '' ||
error_message != '') {
return false;
}else{
var data = {
'user_id': $('#user_id').val(),
'contact_name': $('#contact_form_name').val(),
'contact_mobile': $('#contact_form_mobile').val(),
'contact_email': $('#contact_form_email').val(),
'contact_subject': $('#contact_form_subject').val(),
'contact_message': $('#contact_form_message').val(),
};
$.ajax({
method: "post",
url: "/Home/contact_user",
// headers: {'X-Requested-With': 'XMLHttpRequest'}
data: data,
success: function(response){
jQuery('#contact_us_form')['0'].reset();
jQuery('#contact_us').val('SUBMIT');
jQuery('#contact_us').attr('disabled', false);
alertify.set('notifier','position', 'top-right');
alertify.success("Done");
// response.preventDefault();
}
});
}
});
here are my Routes
$routes->get('/', 'Home::index'); // Default route, if no username redirect to welcome view
$routes->post('/Home/contact_user', 'Home::contact_user'); //contact form API Route, submit form data to this route
$routes->get('/(:any)', 'Home::user/$1'); // User Profile, if username found, show user profile
and here is my contact_user function from Home Controller
public function contact_user(){
$Home_Model = new \App\Models\Home_model();
$data = [
'user_id' => $this->request->getPost('user_id'),
'contact_name' => $this->request->getPost('contact_name'),
'contact_mobile' => $this->request->getPost('contact_mobile'),
'contact_email' => $this->request->getPost('contact_email'),
'contact_subject' => $this->request->getPost('contact_subject'),
'contact_message' => $this->request->getPost('contact_message')
];
$Home_Model->save($data);
$data = ['status' => 'successful'];
return $this->response->setJSON($data);
}

Wanted to add some edit/delete button on my comment system reply part

INDEX.PHP
<body>
<br />
<h2 align="center">Comment System using PHP and Ajax</h2>
<br />
<div class="container">
<form method="POST" id="comment_form" >
<div class="form-group w-50">
<input type="text" name="comment_name" id="comment_name" class="form-control" value="<?php echo $_SESSION['username'];?>" readonly/>
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-inline ">
<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="Comment" />
</div>
<input type="reset" value="Cancel" class="btn btn-primary" style="margin-left: 5px;">
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();//CONVERTS/STORES THE FORM INTO URL IN CODE
$.ajax({
url:"add_comment.php",//WHERE WILL THE INFO GO ---- OR ---- SENDS REQUEST/GOES TO ADD_COMMENT.PHP and records the info
method:"POST",//FOUND IN THE FORM METHOD, telss what kind of method to use to send the data to server so we use ---POST---
data:form_data,//data: it is the variable/code we used to convert/store the form into url in code
dataType:"JSON",
success:function(data)//Will be called if the sending of data to the comment.php is successful
{ //and success will receive the same data/the form_data from server OR DATA WAS RECEIVED BY SUCCESS
if(data.error != '')//check if there is no error in the process and DISPLAYS THE DATA BELOW
{
$('#comment_form')[0].reset();//as Array, it starts with 0 and the .reset() JUST RESETS THE FORM FIELD/OFF THE AUTO COMPLETE
$('#comment_message').html(data.error);//outputs if there is an error or not
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()//loads all the comment
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)//DISPLAYS DATA BELOW if success
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();// if click it will focus on the comment name
});
});
</script>
ADD_COMMENT.php
<?php
session_start();
//add_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$error = '';
$comment_name = $_SESSION['username'];
$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 == '')//if this condition runs then there is no validation error or whatsoever
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $connect->prepare($query);
$statement->execute(
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);
?>
FETCH_COMMENT.php
where the reply part is
<?php
session_start();
//fetch_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
$delete = '';
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>';
$output .= get_reply_comment($connect, $row["comment_id"]);
}
echo $output;
function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
$output .= '
<div class="panel panel-default" style="margin-left:'.$marginleft.'px">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"], $marginleft);
}
}
return $output;
}
?>

How can I display the comment of the specific row that I want to edit?

This is a commenting system using jQuery, Ajax, PHP, MySQL, and HTML. When I click the Edit button, it displays the comment of the first row of the table of MySQL instead of the row that I selected. However, once I edit it, it does correct the correct row. I can’t figure out a way to display the comment of the row that I want to edit.
I can display the correct comment_id of the row into the textarea, but it displays the comment of the first row into the textarea.
Here is the test case code:
MySQL table has two rows: comment_id as primary row and comment for text. I named the database: testcaseedit_db, and the table: tbl_comment.
index.php
<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>
<div id="display_comment"></div>
<div id="comment_message"></div>
<div id="display_edit"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let count = 0;
$(document).on('click change', '.edit, .submit', function(e) {
if ($(this).is('.edit')) {
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
var closestDiv = $('button').closest('div.panel');
$('.div.panel').not(closestDiv.next('.div.panel')).hide();
closestDiv.next('div.panel').slideToggle(100);
var commentEdit = $('#display_comment').find('#editable').html();
++count;
const htmlString =
`<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">
<div class="input-group-prepend">
<textarea name="comment" id="comment${count}" class="form-control" rows="30" cols="160">
${commentEdit} ${comment_id}
</textarea>
</div>
<div class="input-group-prepend">
<input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
<input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
</div>
</form>`;
$('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);
} else if ($(this).is('.submit')) {
$.ajax({
url:"edit.php",
method:"POST",
data: new FormData(this),
contentType: false,
processData: false,
success:function(data)
{
if(data.error != '') {
$('#comment_form')[0].reset();
$('#comment_id').val(comment_id);
$('#comment').val(comment);
}
}
});
location.reload();
$(this).closest('form').submit();
e.stopPropagation();
} else {
return false;
}
});
// Fetch comment
function load_comment(){
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
$('#display_comment').html(data);
}
})
};
load_comment();
// End of (document).ready(function){}
});
</script>
</body>
</html>
fetch.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row) {
$output .= '
<div class="panel panel-default">
<div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
<div class="panel-body"><b> Comment: </b> <br> <span id="editable"> '.$row["comment"].' </span> </div>
<div class="panel-footer" align="right">
<button type="button" class="btn btn-default edit" id="'.$row["comment_id"].'">Edit</button>
</div>
</div>
';
}
echo $output;
?>
edit.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$comment_id = $_POST["comment_id"];
$comment = $_POST["comment"];
if ( $error == '' && !empty($_POST["comment"]) ) {
$query = "UPDATE tbl_comment SET comment = :comment WHERE comment_id = :comment_id ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':comment_id' => $comment_id,
':comment' => $comment
)
);
header("Location: index.php");
}
$data = array(
'error' => $error
);
echo $error;
?>
Here is the solution:
In fetch.php file, I made the id for each variable into an array as follows:
<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'" id[2]="'.$row["comment"].'">Edit</button>
And in index.php file, I grabbed the value of each variable as follows:
var comment_id = $(this).attr("id[1]");
$('#comment_id').val(comment_id);
var comment = $(this).attr("id[2]");
$('#comment').val(comment);
Then I displayed the comment variable inside the textarea as follows:
<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">${comment}</textarea>
Here is the full code for index.php and fetch.php. I left edit.php untouched:
index.php
<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>
<div id="display_comment"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let count = 0;
$(document).on('click change', '.edit, .submit', function(e) {
if ($(this).is('.edit')) {
var comment_id = $(this).attr("id[1]");
$('#comment_id').val(comment_id);
var comment = $(this).attr("id[2]");
$('#comment').val(comment);
var closestDiv = $('button').closest('div.panel');
$('div.panel').not(closestDiv.next('div.panel')).hide();
closestDiv.next('div.panel').slideToggle(100);
++count;
const htmlString =
`<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">
<div class="input-group-prepend">
<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">
${comment}
</textarea>
</div>
<div class="input-group-prepend">
<input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
<input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
</div>
</form>`;
$('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);
} else if ($(this).is('.submit')) {
$.ajax({
url:"edit.php",
method:"POST",
data: new FormData(this),
contentType: false,
processData: false,
success:function(data)
{
if(data.error != '') {
$('#comment_form')[0].reset();
$('#comment_id').val(comment_id);
$('#comment').val(comment);
}
}
});
location.reload();
$(this).closest('form').submit();
e.stopPropagation();
} else {
return false;
}
});
// Fetch comment
function load_comment(){
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
$('#display_comment').html(data);
}
})
};
load_comment();
// End of (document).ready(function){}
});
</script>
</body>
</html>
fetch.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row) {
$output .= '
<div class="panel panel-default">
<div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
<div class="panel-body"><b> Comment: </b> <br> '.$row["comment"].' </div>
<div class="panel-footer" align="right">
<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'" id[2]="'.$row["comment"].'">Edit</button>
</div>
</div>
';
}
echo $output;
?>

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.

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