I'm new to the CakePhp framework and currently i'm testing out a project. Issue i have is, i can populate the dropdown option but when i want to select an option it won't get saved on the database. Did i miss something?
Using this code i can populate the drop down - bookings.js
$("#contact_submit").click(function () {
var name = $("#name").val();
var contact_email = $("#contact_email").val();
var subject = $("#subject").val();
var message = $("#txtmessage").val();
var service = $("#sel1").val();
console.log(name+contact_email+subject+message+service);
$.post("/inquiries/inquiry", //Required URL of the page on server
{// Data Sending With Request To Server
name: name,
email: contact_email,
subject: subject,
txt: message,
service_id: service,
},
function (response) { // Required Callback Function
if (jQuery.parseJSON(response).status == 'success') {
if ($("#available").hasClass("hide")) {
$("#available").removeClass("hide");
}
if (!$("#available").hasClass("hide")) {
$("#notavailable").addClass("hide");
}
}else{
if ($("#notavailable").hasClass("hide")) {
$("#notavailable").removeClass("hide");
}
if (!$("#available").hasClass("hide")) {
$("#available").addClass("hide");
}
}
});
});
InquriesController.php
public function inquiry()
{
$inquiry = $this->Inquiries->newEntity();
if ($this->request->is('post')) {
$emailaddress = $this->request->data['email'];
$subject = $this->request->data['subject'];
$txt = $this->request->data['txt'];
$services = $this->request->data['service_id'];
$message = "this is a message";
$inquiry = $this->Inquiries->patchEntity($inquiry, $this->request->data);
if ($this->Inquiries->save($inquiry)) {
$email = new Email('default');
$email->from(['myemail#gmail.com' => 'Testing Hotel'])
->to($emailaddress)
->subject('Inquiry Mail')
->emailFormat('html')
->send($message);
echo json_encode(['status' => 'success']);
exit;
} else {
echo json_encode(['status' => 'failed']);
exit;
}
}
}
HTML CODE SNIPPET
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" name="contact_email" id="contact_email" class="form-control" placeholder="Email *">
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="subject" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<input class="form-control" name="txtmessage" id="txtmessage" rows="8" placeholder="Messages goes here.."></input>
<div class="form-group">
<select class="form-control" id="sel1">
<option>Select a service</option>
<?php
if (!empty($ServicesInfo)) {
foreach ($ServicesInfo as $Services):
?>
<option value="<?= h($Services->name)?>"><?= h($Services->name)?></option>
<?php endforeach; } ?>
</select>
</div>
As i told you, your int field in the table cannot save the varchar of service name. So, you need to send the service id as value from the select option. Like so :
<option value="<?= h($Services->id)?>"><?= h($Services->name)?></option>
Related
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);
}
I'm working on a form validation with jQuery and PHP, currently using the AJAX jquery method. PHP file doesn't show up in the Networks tab in the browser developer console. I debugged my code and couldn't see where it went wrong.
Can you guys please give me a few pointers to where I missed out in my code?
HTML
<form action="process.php" method="POST">
<h1 class="display-4 form-heading col-md-9">Now's the time to adopt a <span class="highlight">better</span> email security solution</h1>
<p class="form-copy col-md-9">Let us help you migrate and enhance your email security.</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputFirstName">First Name:</label>
<input type="text" class="form-control" id="inputFirstName" name="FirstName" placeholder="333333" required>
</div>
<div class="form-group col-md-6">
<label for="inputLastName">Last Name:</label>
<input type="text" class="form-control" id="inputLastName" name="LastName" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail">Email Address:</label>
<input type="email" class="form-control" id="inputEmail" name="Email" placeholder="aaa" required>
<div class="form-valid-feedback" id="email-error"></div>
</div>
</form>
Javascript
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
//beginning AJAX
function checkEmail(email){
var re = /\S+#\S+\.\S+/;
return re.test(email);
}
function checkPhoneNumber(phone){
var phonePattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
return phonePattern.test(phone);
}
var FirstName = $("#inputFirstName").val();
var LastName = $("#nputLastName").val();
var email = $("#inputEmail").val();
var companyName = $("#inputCompanyName").val();
var phone = $("#inputPhone").val();
var submit = $("#inputsubmit").val();
var formData = {
FirstName : $("#inputFirstName").val(),
LastName : $("#nputLastName").val(),
email : $("#inputEmail").val(),
companyName : $("#inputCompanyName").val(),
phone : $("#inputPhone").val(),
submit: $("#inputsubmit").val()
};
$.ajax({
type: 'POST',
url : 'process.php',
data:formData
})
if(!data.success){
if(data.errors.firstName){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.firstName);
}
if(data.errors.LastName){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.LastName);
}
if(data.errors.email){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.email);
}
if(data.errors.CompanyName){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.CompanyName);
}
if(data.errors.Phone){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html(data.errors.Phone);
}
}
else if(!checkEmail(email)){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html('Please enter a vlid email address: example#example.com');
}
else if (!checkPhoneNumber(phone)){
$(".form-valid-feedback").show();
$(".form-valid-feedback").html('Please enter a vlid Phone Number: 333-333-3333');
}
else{
$('form').append('<div class="alert alert-success" id="success">' + data.message + '</div>');
}
})
.fail(function(data){
console.log(data)
});
});
//end of submit event handling
});
PHP
<?php
$errors = array();
$data = array();
//starting the validation of variables
if (empty($_POST['FirstName']))
$errors['FirstName'] = "First Name is required.";
if (empty($_POST['LastName']))
$errors['LastName'] = "Last Name is required.";
if (empty($_POST['Email']))
$errors['Email'] = 'Email is required.';
if (empty($_POST['CompanyName']))
$errors['CompanyName'] = 'Company Name is required.';
if (empty($_POST['Phone']))
$errors['Phone'] = 'Phone Number is required.';
if(! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
}
else{
//when everything is free of errors
$data['success'] = true;
$data['message'] = 'Success!';
}
echo json_encode($data);
?>
Is there a way i can verify if my php script for sending form to emails worked? I tried running the php website in localhost and tested to submit a message but when I checked my email, nothing has been sent. How do I kno if my form has been received? Is it instantly received when you sent a message from php form via email? How do I know if the email script was wrong or it just didnt send? heres my html:
<div class="container">
<div class="row">
<div class="inquiry2 col-xs-12 col-sm-12 col-md-12 col-lg-12">
<br></br>
<br></br>
<h1>Message Us</h1>
<form action="send.php" id="frmBox" method="post" onsubmit="return formSubmit();">
<div class="form-group">
<label for="InputName">Name*</label>
<input class="form-control" type="text" placeholder="Name" name="customer_name" id="CustomerName">
</div>
<div class="form-group">
<label for="InputEmail">Email Address*</label>
<input class="form-control" type="text" placeholder="email" name="customer_email" id="CustomerEmail">
</div>
<div class="form-group">
<label for="InputPhone">Phone*</label>
<input class="form-control" type="text" placeholder="phone" name="customer_phone" id="CustomerPhone">
</div>
<div class="form-group">
<label for="InputMessage">Message*</label>
<textarea class="form-control" type="text" placeholder="" name="customer_message" id="CustomerMessage"></textarea>
</div>
<input class="btn btn-default" type="submit" value="submit">
</form>
</div>
</div>
</div>
<!--SCRIPT-->
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function formSubmit(){
$.ajax({
type:'POST',
url:'send.php',
data:$('#frmBox').serialize(),
success:function(response){
$('#success').html(response);
}
});
var form=document.getElementById('frmBox').reset();
return false;
}
</script>
heres the php send:
<?php
$customer_name_error = $customer_email_error = $customer_phone_error = "";
$customer_name = $customer_email = $customer_phone = $customer_message= $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["customer_name"])) {
$customer_name_error = "Name is required";
} else {
$customer_name = test_input($_POST["customer_name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$customer_name_)) {
$customer_name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["customer_email"])) {
$customer_email_error = "Email is required";
} else {
$customer_email = test_input($_POST["customer_email"]);
if (!filter_var($customer_email, FILTER_VALIDATE_EMAIL)) {
$customer_email_error = "Invalid email format";
}
}
if (empty($_POST["customer_phone"])) {
$customer_phone_error = "Phone is required";
} else {
$customer_phone = test_input($_POST["customer_phone"]);
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$customer_phone)) {
$customer_phone_error = "Invalid phone number";
}
}
if (empty($_POST["customer_message"])) {
$customer_message = "";
} else {
$customer_message = test_input($_POST["customer_message"]);
}
if ($customer_name_error == '' and $customer_email_error == '' and $customer_phone_error == '' ){
$customer_message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$customer_message_body .= "$key: $value\n";
}
$to = 'gorilyawarfare#gmail.com';
$subject = 'Messages';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$customer_name = $customer_email = $customer_phone = $customer_message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I have never created an AngularJs contact form, and have tried a couple different examples on the web. In none of the examples is the error: Unexpected request: POST contact-form.php (or whatever the php file is named) mentioned (although there are a couple posts regarding "unexpected request", but these seem to be about $httpBackend or other topics), or any additional dependencies that needs to be injected etc.
Note: I am using a regular, out-of-the-box web hosting service.
I would appreciate if you could give me some input as to why I am getting this error, and perhaps what I am doing wrong, and any other useful tips.
Here is my controller code:
(function () {
"use strict";
angular
.module("impi-app")
.controller("ContactController",
["$scope", "$filter", "$http", '$location',
ContactController]);
function ContactController($scope, $filter, $http, $location) {
$scope.title = "Contact";
$scope.formData = {};
$scope.submit = function (contactForm) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function (contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method: 'POST',
url: 'contact-form.php',
data: $.param($scope.formData), //param method from jQuery
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function (data) {
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result = 'bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result = 'bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed :( Please fill out all the fields.';
$scope.result = 'bg-danger';
}
}
}
}
}());
here is my contact view:
<div class="vertical-middle">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Contact Form</h2>
</div>
<div ng-controller="ContactController" class="panel-body">
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<label for="inputName" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Your Name" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<label for="inputSubject" class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">
Send Message
</button>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
</div>
</div>
</div>
here is my contact-form.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('onmyway.whatever#outlook.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
Much appreciated.
Try to add slash before contact-form.php
$http({
method: 'POST',
url: '/contact-form.php',
data: $.param($scope.formData), //param method from jQuery
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
})
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;
});