How to send information to database without reloading the page - php

I've been trying to send information to the database using AJAX but nothing is working, each time i click the submit button, nothing works, the pages stays static somewhat. All JS files are referenced properly so i'm not sure what i'm doing wrong.
Here's what i've done so far;
Controller:
public function contact_us_ajax() {
//form validation rules and file upload config
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required');
$this->form_validation->set_rules('message', 'Message', 'trim|required');
$this->form_validation->set_rules('captcha_code', 'Captcha Code', 'trim');
$this->form_validation->set_rules('c_captcha_code', 'Captcha Code', 'trim|required|matches[captcha_code]',
array(
'required' => 'Captcha is required. Reload the page if you cannot see any code.',
'matches' => 'Invalid captcha code'
)
);
if ($this->form_validation->run()) {
$this->message_model->contact_us(); //insert the data into database
$res = ['status' => true, 'msg' => 'Message sent successfully!'];
echo json_encode($res);
} else {
$res = ['status' => false, 'msg' => validation_errors()];
echo json_encode($res);
}
}
Model:
public function contact_us() {
$name = ucwords($this->input->post('name', TRUE));
$email = $this->input->post('email', TRUE);
$subject = ucwords($this->input->post('subject', TRUE));
$message = ucfirst($this->input->post('message', TRUE));
$message = nl2br($message);
$data = array (
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message,
);
$this->db->insert('contact_messages', $data);
//email admins
//$this->notify_admins($name, $email, $subject, $message);
}
View:
<?php
$form_attributes = array("id" => "contact_us_form");
echo form_open('home/contact_us_ajax', $form_attributes); ?>
<!-- Contact Form -->
<div class="col-md-5">
<h4>Send Us a Message</h4>
<div class="form-group">
<label>Name:</label><input type="text" name="name" class="form-control input-field" required>
<label>Email:</label><input type="email" name="email" class="form-control input-field" required>
<label>Subject:</label><input type="text" name="subject" class="form-control input-field" required>
</div>
<label>Message:</label>
<textarea name="message" class="textarea-field form-control" rows="4" required></textarea>
<div class="col-md-6">
<input type="text" name="captcha_code" id="captcha_code" value="<?php echo $captcha_code; ?>" class="form-control" readonly />
</div>
<div class="col-md-6">
<input type="text" name="c_captcha_code" value="<?php echo set_value('c_captcha_code'); ?>" class="form-control" placeholder="Enter captcha code here*" required />
</div>
<div id="status_msg"></div>
<?php echo flash_message_success('status_msg'); ?>
<?php echo flash_message_danger('status_msg_error'); ?>
<button class="btn center-block">Send message</button>
</div>
<?php echo form_close(); ?>
AJAX:
//Contact Us
$('#contact_us_form').submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: base_url + 'home/contact_us_ajax',
type: 'POST',
data: form_data,
dataType: 'json',
success: function(res) {
if (res.status) {
$( '#status_msg' ).html('<div class="alert alert-success text-center" style="color: #000">'+res.msg+'</div>').fadeIn('fast');
$('#contact_us_form')[0].reset(); //reset form fields
$('#captcha_code').val(''); //clear captcha field
setTimeout(function() {
location.reload();
}, 5000);
} else {
$( '#status_msg' ).html('<div class="alert alert-danger text-center" style="color: #000">' + res.msg + '</div>').fadeIn('fast').delay( 30000 ).fadeOut( 'slow' );
}
}
});
});

base_url is defined in codeigniter's config.php, for example like:
$config['base_url'] = 'http://or.org/';
BUT! This doesn't mean you can simply name a variable in javascript base_url and hope to get any value.
To use it in your ajax call, you need to echo the php constant out like:
url: '<?php echo base_url()?>' + 'home/contact_us_ajax'
I normally just use the relative path
url: '/home/contact_us_ajax'
which works fine as well, if you use a "regular" CI configuration

Related

PHP form with response on same page

Hi I created a PHP form - I am getting the email but the the response message opens in the same window with plain text. If someone could point me in the right direction that would be great.
This is the output once submitted:
{"status":"success","message":"Thank you for your interest in Nature's Apprentice.
A representative will be in contact with you shortly","email_sent":true}
This is the contact form code:
<form name="formContact" id="formContact" action="contact-submit.php" method="post" novalidate="novalidate">
<label for="name">Name <span class="required" >*</span></label>
<input name="name" id="name" class="form-control " placeholder="First and Last Name" type="text">
<label for="email">Email <span class="required" >*</span></label>
<input name="email" id="email" class="form-control" placeholder="email#domain.com" type="text">
<label for="phone">Phone</label>
<input name="phone" id="phone" class="form-control" placeholder="(xxx) xxx-xxxx" type="text">
<label for="address">Area of Interest </label>
<input name="address" id="address" class="form-control" placeholder="Location" type="text">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" placeholder=""></textarea>
<input name="submit" id="submit" class="submit_btn" value="Submit" type="submit">
<img src="images/loader.gif" alt="Loader" class="loader">
<div class="info_msg">
<p><span class="required">*</span> indicates required field.</p>
</div>
<div class="response_msg">
<p></p>
</div>
</form>
This is the js:
jQuery(document).ready(function ($) {
$("#formContact").validate({
ignore: ".ignore",
rules: {
name: "required",
email: {
required: true,
email: true
}
},
invalidHandler: function (form, validator) {
$('#formContact').find('#response_msg p').removeClass().addClass('error').html('Please fill all the required fields.');
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: $(form).attr('action'),
data: $(form).serialize(), // serializes the form's elements.
beforeSend: function(){
$('img.loader').fadeIn();
},
success: function (data) {
var json = $.parseJSON(data);
//alert(json.status , json.message);
$('#formContact').find('#response_msg p').removeClass().html('');
if(json.status !='') {
if(json.status == 'success') {
$('#formContact').trigger('reset');
}
setTimeout(function(){
$('#formContact').find('#response_msg p').removeClass().addClass(json.status).html(json.message).fadeIn();
}, 1000);
}
},
error:function (xhr, ajaxOptions, thrownError){
$('#formContact').find('#response_msg p').removeClass().addClass('error').html('Some error occured. Please try again.').fadeIn();
},
complete: function(){
$('img.loader').fadeOut();
}
});
}
});
});
</script>
This is the contact-submit.php:
//session_start();
require 'include/include.php';
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$address = trim($_POST['address']);
$comments = trim($_POST['comments']);
$errors = array();
if($name == '' or $email == '' ) {
$response = array('status' => 'error', 'message' => 'Please fill all the required fields.');
echo json_encode($response);
exit;
}
else {
if(strlen($name) < 3) {
$errors[] = 'Name should be 3 characters long.';
}
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter valid email.';
}
$errors = array_filter($errors);
if (!empty($errors)) {
$message = implode("<br>", $errors);
$response = array('status' => 'error', 'message' => $message );
echo json_encode($response);
exit;
}
else {
$mailsubject = "Contact Us Form Details - ".$site_name;
$sendmessage = "Dear Administrator,<br /><br />
<b>Name:</b> $name<br /><br />
<b>Email:</b> $email<br /><br />
<b>Phone:</b> $phone <br /><br />
<b>Address:</b> $address <br /><br />
<b>Comments:</b> $comments <br /><br />";
$mail_str = "";
$mail_str = '<html><head><link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css"></head><body style="max-width: 600px; margin: 0 auto; font-family: Open Sans, sans-serif; font-size: 15px; line-height: 20px;"> <table style="border:1px solid #000000" width="95%" align="center" cellspacing="0" cellpadding="0"> <tbody><tr style="background-color:#365744"><td style="padding: 10px; ">'.$site_name.'</td></tr><tr style="background-color:#ffffff"><td style="padding: 10px; ">'.$sendmessage.' </td></tr><tr style="background-color:#383634; color: #fff;"><td style="padding: 10px; ">Thanks! - '.$site_name.'</td></tr></tbody></table></body></html>';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = sprintf('From: %s <%s>', $name, $email);
$headers = implode("\r\n", $headers);
#echo "<hr/>"; echo $to_mail;echo "<hr/>";echo $mailsubject;echo $mail_str; echo $headers; exit;
$emailsend = mail($admin_email, $mailsubject, $mail_str, $headers);
if($emailsend) {
$response = array('status' => 'success', 'message' => sprintf('Thank you for your interest in %s. <br /> A representative will be in contact with you shortly', $site_name), 'email_sent' => $emailsend);
echo json_encode($response);
exit;
}
else {
$response = array('status' => 'error', 'message' => 'Some error occured. Please try again.', 'email_sent' => $emailsend);
echo json_encode($response);
exit;
}
}
}
#---------------Mail For Admin (Ends)--------------------------------------------------
//header("Location:thank-you.html");
exit;
?>```
According to your code class="response_msg" should be id="response_msg" in your form.
You should be setting the header when returning json.
header('Content-Type: application/json');
Try adding a preventDefault call. Otherwise, the form is probably being submitted via the normal form POST process after your Ajax is finished and thus is redirecting to the contact-submit.php page and you see the echo out of the response on a blank page.
Try this edit:
...
submitHandler: function (form, e) {
e.preventDefault();
$.ajax({
type: "POST"
...
I've debugged your code and tested it as working. You need to add the following 4 changes:
Specify the data type to jQuery. Add the dataType line as below.
data: $(form).serialize(), // serializes the form's elements.
dataType: 'json',
beforeSend: function(){
Let jQuery do the JSON parsing. Change this:
success: function (data) {
To this:
success: function (json) {
Get rid of this line:
var json = $.parseJSON(data);
Your #response_msg selector is off, because you've given the container a .response_msg class, instead of an id. Change this:
<div id="response_msg">
To this:
<div class="response_msg">
Or change the selectors to refer to the class instead.
And things should then work as expected.

Getting null response to Recaptcha V3 with ajax

I'm having a problem with getting a problem when submitting captcha v3 to ajax. I get a null response to Google. I have tried multiple tutorials but I think it does not fix to ajax request.
I think the problem is with google or my php, or ajax request. I understand my codes but I am not familiar with using google's code like this captcha v3. I have use captcha v2 before. And now I am trying v3 I can't run it with my code.
Here is my Ajax and HTML code :
// when form is submit
$('.contact-form').submit(function (event) {
// we stoped it
event.preventDefault();
var url = $(this).prop('action');
var contact_data = $(this).serialize();
$('.btn-contact').html('<em class="fas fa-spinner fa-pulse"></em> Sending...');
$('.alert').fadeOut('slow');
// needs for recaptacha ready
grecaptcha.ready(function () {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6Ldjp6Q[--my site key---]8H5bxI1', { action: 'create_contact' }).then(function (token) {
// add token to form
$('.contact-form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
var contact = function () {
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: contact_data, token: token ,
success: function (response) {
$('.message').html(response.message);
$('.btn-contact').html('<em class="fas fa-paper-plane"></em> Send');
if (response.error) {
$('.status').removeClass('alert-success').addClass('alert-danger').show();
}
else {
$('.status').removeClass('alert-danger').addClass('alert-success').show();
$('.contact-form')[0].reset();
}
}
});
};
setTimeout(contact, 3000);
});;
});
});
<?=form_open('Contact/Send_Contact', array('class' => 'contact-form'))?>
<div class="row top-2">
<div class="col-md-12">
<div class="status alert text-center" style="display:none;">
<button type="button" class="close clearMsg"><span aria-hidden="true">×</span></button>
<span class="message"></span>
</div>
</div>
<div class="form-group col-md-6">
<input type="text" placeholder="Your Name" name="name" class="form-control name">
<div class="invalid-feedback invalid-name"></div>
</div>
<div class="form-group col-md-6">
<input type="email" placeholder="Your Email" name="email" class="form-control email">
<div class="invalid-feedback invalid-email"></div>
</div>
<div class="form-group col-md-12">
<input type="text" placeholder="Subject" name="subject" class="form-control subject">
<div class="invalid-feedback invalid-subject"></div>
</div>
<div class="form-group col-md-12">
<textarea placeholder="Message" class="form-control message_text" name="message" rows="4"></textarea>
<div class="invalid-feedback invalid-message"></div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-info btn-contact float-right"><em class="fas fa-paper-plane"></em> Send</button>
</div>
</div>
</from>
<script src="https://www.google.com/recaptcha/api.js?render=6Ldj[--My site key--]5bxI1"></script>
And I also copied some PHP code and I don't know where is the problem here because this is my first time using CodeIgniter and I also haven't used captcha v3 too.
Please review my PHP code here :
public function Send_Contact() {
$output['error'] = true;
$output['message'] = 'Please fill up the error field(s).';
$name = $this->input->post('name');
$email = $this->input->post('email');
$subject = $this->input->post('subject');
$message = $this->input->post('message');
$captcha = $this->input->post('token');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if($this->form_validation->run() === false) {
//some codes here I remove because it has nothing to do with the question.
die(json_encode($output));
}
if(!$captcha){
$output['message'] = "Invalid catpcha";
die(json_encode($output));
}
$secretKey = "6Ldjp[--My secret key--]YQL_";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array('secret' => $secretKey, 'response' => $captcha);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$responseKeys = json_decode($response,true);
if($responseKeys["success"]) {
if($this->contact_model->create_contact()) {
$output['error'] = false;
$output['message'] = 'Thank you for sending message! <em class="far fa-check-circle"></em>';
echo json_encode($output);
} else {
$output['error'] = true;
$output['message'] = 'Error in database model.';
echo json_encode($output);
}
} else {
$output['message'] = "Invalid catpcha";
die(json_encode($output));
}
}
I'm using codeigniter 3. and this public function is in the contact controller.

how to validate form input field if form value inserted through jquery?

view:
<script>
$(function(){
$( "#insert" ).click(function(event)
{
event.preventDefault();
var name= $("#name").val();
var email= $("#email").val();
var phone= $("#phone").val();
var message= $("#message").val();
$.ajax(
{
type:"post",
url: "<?php echo base_url('index.php/'); ?>test/register",
data:{"name": name, "email":email, "phone":phone, "message":message},
success:function(data)
{
console.log(data);
$('#msd').text('Your Enquiry Has Been Sent. We Will Inform You Soon.');
$('#name,#email,#message,#phone').val('');
}
});
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Header</h4>
</div>
<div class="modal-body" id="bg-image">
<div class="row">
<div class="col-md-6">
<form method="post" enctype="multipart/form-data">
<input type="text" class="form-control1" id="name" name="name" placeholder="Enter Your Name" required>
<input type="text" class="form-control1" id="email" name="email" placeholder="Enter Your Email Id" required>
<input type="text" class="form-control1" id="phone" name="phone" placeholder="Enter Your Phone" required>
<textarea class="form-control1" name="message" id="message" placeholder="Enter Your Message" required></textarea>
<input type="submit" name="insert" id="insert" value="Submit">
</form>
</div>
<div class="col-md-6">
<h4>Features</h4>
</div>
</div>
</div>
<div class="modal-footer">
<h4>Fotter</h4>
</div>
</div>
</div>
</div>
controller:
public function register()
{
$register = $this->Fetch_data->contact();
if(!empty($register_user))
{
return true;
}
else
{
return false;
}
}
models:
public function contact()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'message' => $this->input->post('message'),
's_date' => date('Y-m-d')
);
$this->db->insert('contact', $data);
}
In this code I have create a form inside the modal where I am inserting form value into database table name contact. Here, form value are inserting successfully but the validation are not working properly. If input field empty they show nothing like field is mandatory. So, How can we give validation to all field please help me ?
Thank You
Try This
Replace <script> To
<script>
$(function(){
$( "#insert").click(function(event)
{
event.preventDefault();
var name= $("#name").val();
var email= $("#email").val();
var phone= $("#phone").val();
var message= $("#message").val();
$.ajax(
{
type:"post",
url: "<?php echo base_url('index.php/'); ?>test/register",
dataType:'JSON',
data:{"name": name, "email":email, "phone":phone, "message":message},
success:function(data)
{
console.log(data);
$('#msd').text(data.message);
}
});
});
});
</script>
Controller
public function register()
{
$this->load->library('form_validation');
$post = $this->input->post();
if (!empty($post)) {
//validate form input
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'E-mail', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if ($this->form_validation->run() == true) {
$register = $this->Fetch_data->contact($post);
if (!empty($register)) {
echo json_encode(array("status" => false, "message" => "Inserted Successfully"));
exit(0);
} else {
echo json_encode(array("status" => false, "message" => "Unable to insert Try later"));
exit(0);
}
} else {
echo json_encode(array("status" => false, "message" => validation_errors()));
exit(0);
}
} else {
echo json_encode(array("status" => false, "message" => "Invalid Request"));
exit(0);
}
}
Model
public function contact($post)
{
$data = array(
'name' => $post['name'],
'email' => $post['email'],
'phone' => $post['phone'],
'message' => $post['message'],
's_date' => date('Y-m-d', time())
);
$this->db->insert('contact', $data);
return $this->db->insert_id();
}
If You got any error then let me know
Note
Note : Enable Form_validation library

Validation in AJAX Form Codeigniter

I've made a form in Ci which submits the data to the Db. I've been trying to implement validation in the form, For eg Name : more than 3+ Letters, email '#' Etc.
I never could seem to make it work, tried using Jquery validation with different sources , the form basically submits without Validation, Any pointers to where i'm going wrong?
The code below is just a snippet without any validation codes attached to it.
<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Enquire About "<?php echo $row_company->company_name; ?> "</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#click_form').click(function () {
var url = "<?php echo site_url('enquiry/ajax_post_form') ?>";
var data = $("#reg_form").serialize();
$.post(url, data, function (data) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}, "json");
});
});
</script>
</div>
</div>
</div>
</div>
Controller
public function ajax_post_form() {
$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags');
$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);
$this->insert_model->form_insert($user_data);
$data['message'] = 'Data Inserted Successfully';
echo json_encode($user_data);
}
Model
function form_insert($user_data){
$this->db->insert('pp_enquiry', $user_data);
}
**Validation **
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var name = document.getElementById("username1").value;
var email = document.getElementById("email1").value;
var mobile = document.getElementById("mobile").value;
//Check input Fields Should not be blanks.
if (name == '' || email == '' || mobile == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var username1 = document.getElementById("username");
var email1 = document.getElementById("email");
var mobile = document.getElementById("mobile");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (username1.innerHTML == 'Must be 3+ letters' || email1.innerHTML == 'Invalid email' || mobile.innerHTML == 'Invalid website') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
Please check here is the working example of your above code. I think you missed something in your code.
$(document).ready(function() {
var $validator = $("#reg_form").validate({
rules: {
name: {required: true, minlength: 3, maxlength: 25},
email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
mobile: {required: true, minlength: 10, maxlength: 12, number: true}
},
messages: {
email: {required: "Please enter valid Email Address"},
mobile: {required: "Please provide valid Phone or Mobile number!"}
}
});
jQuery.validator.addMethod("regex", function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
}, "Please provide valid email address.");
$('#click_form').click(function(e) {
e.preventDefault();
var $valid = $("#reg_form").valid();
if (!$valid) {
$validator.focusInvalid();
return false;
} else {
var url = 'https://www.example.com';
var data = $("#reg_form").serialize();
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
console.log(data);
},
success: function(returnData) {
if (returnData.status) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Enquire About "Company Name"</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
</div>
</div>
</div>
</div>
You need to run the validation process as explained in the manual: https://www.codeigniter.com/user_guide/libraries/form_validation.html#the-controller
if ($this->form_validation->run() == FALSE)
You can find below mentioned solution.
PHP Validation
$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags|valid_email|min_length[3]');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags|min_length[10]|max_length[12]');
if ($this->form_validation->run() == FALSE) {
$data['status'] = false;
$data['error'] = validation_errors();
} else {
$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);
$this->insert_model->form_insert($user_data);
$data['status'] = true;
$data['message'] = 'Data Inserted Successfully';
}
echo json_encode($data);
jQuery Validation
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
$(document).ready(function() {
var $validator = $("#reg_form").validate({
rules: {
name: {required: true, minlength: 3, maxlength: 25},
email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
mobile: {required: true, minlength: 10, maxlength: 12, number: true}
},
messages: {
email: {required: "Please enter valid Email Address"},
mobile: {required: "Please provide valid Phone or Mobile number!"}
}
});
jQuery.validator.addMethod("regex", function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
}, "Please provide valid email address.");
$('#click_form').click(function(e) {
e.preventDefault();
var $valid = $("#reg_form").valid();
if (!$valid) {
$validator.focusInvalid();
return false;
} else {
var url = '<?php echo site_url('enquiry/ajax_post_form') ?>';
var data = $("#reg_form").serialize();
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
// Code if required before Send
},
success: function(returnData) {
if (returnData.status) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}
}
});
}
});
});
Let me know if it not works.

In codeigniter How to redirect after login using ajax

I have a login popup Modal. and i am logging through ajax
Modal
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
I am trying to redirect after successful login using ajax. If email and password is correct then redirect to any page. If not then it will show the Error.
Controller
function index() {
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
echo validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
echo "Yes";
}else {
echo "No";
}
}
}
This is my controller in which i am checking login user email and password correct/incorrect.
This is my script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(msg) {
if (msg == "Yes")
window.location.href = "<?php echo current_url(); ?>";
else if (msg == "No")
$('#error-msg').html('<div class="alert alert-danger text-center">Incorrect Email & Password. Please try again ...</div>');
else
$('#error-msg').html('<div class="alert alert-danger">' + msg + '</div>');
}
});
return false;
});
</script>
As you can see in the success part, when i entered the correct email/password. It is showing Yes. But i want to redirect another page, Why this is showing YES on correct email/password.and On incorrect email/password This is showing NO.
Where i am Doing Wrong???
You need to change few lines of codes in jQuery and Controller function. Here I am attaching updated version of your code. Please refer below:
View (Bootstrap Modal)
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
This is your view file. It will remain same. On clicking on button you have written a script which need to be modified. Will attact after attaching controller's function:
Controller
function index() {
if (!$this->input->is_ajax_request()) {
echo 'No direct script is allowed';
die;
}
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
$result['status'] = 'error';
$result['message'] = validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
$result['status'] = 'success';
$result['message'] = 'Yeah! You have successfully logged in.';
$result['redirect_url'] = base_url();
}else {
$result['status'] = 'error';
$result['message'] = 'Whoops! Incorrect Email & Password. Please try again';
}
}
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($result));
$string = $this->output->get_output();
echo $string;
exit();
}
Script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(resp) {
if (resp.status == "success")
window.location.href = resp.redirect_url;
else
$('#error-msg').html('<div class="alert alert-danger">' + resp.message + '</div>');
}
});
return false;
});
This is the correct answer. Let me know if you face any issue.
You can use a simple redirect() (comes in the url helper) in your code if you want to jump to another controller/method from the script. However, this will not alert the user that the login was successful: it's just a plain redirect.
The proper way to do it would be returning a json file, so instead of echoing a yes or no, use this:
$response['type'] = 'error';
$response['msg'] = 'Login Succesful';
$response['redirect'] = 'http://your-url.com/controller/method';
echo json_encode($response);
die;
Then, you handle the answer in your ajax call, and some good alerting (in my case, Sweet Alert) kinda like this:
success: function(data) {
if (data.redirect) {
swal({
title: '¡Success!',
text: data.msg,
timer: 2000,
type: data.type,
showConfirmButton: false
}, function() {
window.location.href = data.redirect;
});
} else {
swal('¡Error!', data.msg, data.type);
}
}
So what this code does is that if your json response has a redirect field, will trigger the redirection after a while. But if your json response does not have the field redirect, will just show an alert.
Check your return data type. May be you can use in datatype in Ajax code. Return data can't read if condition. I am facing same problem or use this
if($.trim(msg) == 'Yes') {
Change echo "Yes"; to die("Yes");. This will make sure nothing will be sent after "Yes" or "No" and then the JS code will work as expected.
Their is also a way to redirect from your controller after success.
In this case you just need to follow these two steps to redirect
This line in your controller where you get true condition and want to redirect
if($result){
echo base_url()."welcome/";
}
else{
echo 0;
}
on your html page where you applied your ajax, on true condition you try this to redirect page
success: function(result){
if(result!=0){
// On success redirect.
window.location.replace(result);
}
else
alert('wrong');
}

Categories