Ajax form with codeigniter validation - php

I am trying to make ajax form validation work in codeigniter.
Form and ajax are both in views/products/addproducts,
<script type="text/javascript">
$(document).ready(function(){
$("#submitProducts").click(function(e){
e.preventDefault();
var dataString = $("#add-products-bulk-form").serialize();
var url="products/addproducts";
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+url,
dataType: 'json',
data:dataString,
success:function (res) {
res=$.parseJSON(res);
if($.isEmptyObject(res.error)){
alert(res.success);
}else{
console.log("hasn't run form yet");
}
},
})
})
});
</script>
here is my Products controller:
public function addproducts()
{
$data['title'] = "Add Products";
$this->load->view('templates/header', $data);
$this->load->view('products/addproducts');
$this->load->view('templates/footer');
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
if ($this->form_validation->run() === FALSE)
{
echo "did not pass validation";
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
echo "did pass validation";
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}
I don't get any response when I click submit button if I keep the code above way. But if I get rid of line dataType:'json', I will get error
VM1679:1 Uncaught SyntaxError: Unexpected token d in JSON at position 0
at Function.parse [as parseJSON] (<anonymous>)
at Object.success (addproducts:140)
at i (jquery-3.1.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2)
at A (jquery-3.1.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)
If I get rid of both dataType:'json' and res=$.parseJSON(res), when I enter a duplicated product and click submit, and console.log(res), I get the following in the console, It did return the res and the source code of the whole page addproducts.
did not pass validation{"error":"<p>The Part number field must contain a unique value.<\/p>\n"}<!DOCTYPE html>
<html lang="en">
<head>
I did not paste the whole source code here. and res.success will alert undefined.
I have been stuck for days, please help. I will provide more details if needed.
Thanks!

To clean up my earlier comment...
public function addproducts()
{
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
header('Content-Type: application/json');
if ($this->form_validation->run() === FALSE)
{
$this->output->set_status_header(400);
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
$this->output->set_status_header(200);
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}
Now you can use the success callback to listen for a successful response and the error callback to listen for an error response...
<script type="text/javascript">
$(document).ready(function(){
$("#submitProducts").click(function(e){
e.preventDefault();
var dataString = $("#add-products-bulk-form").serialize();
var url="products/addproducts";
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+url,
dataType: 'json',
data:dataString,
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseJSON.error);
},
success: function (data, textStatus, jqXHR) {
alert(jqXHR.responseJSON.success);
}
});
});
});
</script>

I realized that I make ajax call with the same controller function, I divided the addproducts function into two functions as follow,and use ajax to call ajax_add_products function. it works now.
public function addproducts()
{
$data['title'] = "Add Products";
$this->load->view('templates/header', $data);
$this->load->view('products/addproducts');
$this->load->view('templates/footer');
}
public function ajax_add_products(){
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
if ($this->form_validation->run() === FALSE)
{
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}

Related

user name and password login through ajax.. unable to login

Controller code below as show unable to login.
none of the error getting what is the problem i cannot understand how to call through ajax
public function loginn()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
//$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[40]');
if ($this->form_validation->run() && $this->Login_model->login($email, $password)) {
$this->welcome();
}
else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
$this->index();
}
}
Below code as shown View page send the post values through ajax.script as below.how to pass the post values to controller using ajax.
<script type="text/javascript">
$(document).ready(function(){
$("#fpassf").click(function(){
//e.preventDefault();
var email = $("#email").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>"+"Index.php/Login_cntrl/loginn",
data: {email:email,password:password},
success:function(data)
{
alert('Successfully login');
},
error:function()
{
alert('fail');
}
});
});
});
the image shown in below
enter image description here
on click on signin image shown in below
enter image description here
It seems that you are using Codeigniter Framework. And Hence I have a doubt with your Ajax URL Path.
You have given
url: "<?php echo base_url() ?>"+"Index.php/Login_cntrl/loginn",
But In codeigniter it should be like
url: "<?php echo base_url() ?>"+"/Login_cntrl/loginn",
OR
url: "<?php echo base_url('Login_cntrl/loginn') ?>",
It can also possible that you are calling this ajax from a script file. Which is not a php file. so the base_url() function will not work there. In that case you have to save base_url into a input variable in a hidden format. and then should be fetch in your ajax code.
<input type="hidden" name="myurl" value="<?php echo base_url();">
and then ajax one
var myurl = $("#myurl").val();
You have to separate your basic login action and ajax login action, because both send different response.
PHP Controller:
public function ajax_login()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[40]');
if ($this->form_validation->run() && $this->Login_model->login($email, $password)) {
return $this
->output
->set_status_header(200)
// here you tell to the ajax that the login is successful
->set_output(json_decode(array('status' => 'success', 'message' => 'PUT_YOUR_SUCCESS_MESSAGE_HERE')))
;
} else {
return $this
->output
->set_status_header(200)
// here you tell to the ajax that the login is failed
->set_output(json_decode(array('status' => 'error', 'message' => 'PUT_YOUR_ERROR_MESSAGE_HERE')))
;
}
}
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#fpassf").click(function(){
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "<?php echo base_url('Login_cntrl/ajax_login') ?>",
data: {email:email, password:password},
success: function(data) {
data = JSON.parse(data);
// success in ajax does not mean successfully login, so check again
if (data.status == 'success') {
alert(data.message]); // login success message defined in action
} else {
alert(data.message); // login failed message defined in action
}
},
error: function() {
// error in ajax means HTTP error, not login error
alert('Request failed!');
}
});
});
});
</script>

PHP not return value without exit function

I need help. I am getting problem in returning value from Codeigniter. Whenever, I use exit; after echo it work fine but whenever i try return true it's dosen't work.
Same as i have comment code in PHP code. if i use exit after echo it works but if i don't do that it returns nothing
Ajax Request
$('#social-form').on('submit', function(e){
e.preventDefault();
var str = $( "#social-form" ).serialize();
if (str === '') {
swal("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: baseUrl + "/admin/social/",
data: str
})
.done(function (data) {
console.log(data);
swal("Information", data, "info");
})
.error(function () {
swal("Oops", "We couldn't connect to the server!", "error");
});
}
});
Codeigniter-3
public function social(){
$name = $this->input->post('name');
$profile = $this->input->post('profile');
$this->form_validation->set_rules('name', 'name', 'required|trim');
$this->form_validation->set_rules('profile', 'profile', 'required|trim');
if ($this->input->post() && $this->form_validation->run() != FALSE) {
$this->load->model('Social_model','social');
$this->social->update($name,$profile);
echo 1;
//exit;
//return true;
}
else
{
echo 0;
//exit;
//return false;
}
}
CodeIgniter has a layout, so after outputting a response there could be views that are outputted after your response, such as a footer or a debug bar.
Try using your console to see the status code of the response. Also note that it isn't bad practice in CodeIgniter to exit after AJAX calls, so perhaps you should just write a AJAX response helper which does all that for you (like setting the header and adding the exit).
You probably need to be more specific about what you echo. This is one of several possible solutions.
controller
public function social(){
$name = $this->input->post('name');
$profile = $this->input->post('profile');
$this->form_validation->set_rules('name', 'name', 'required|trim');
$this->form_validation->set_rules('profile', 'profile', 'required|trim');
if ($name && $this->form_validation->run() != FALSE) {
$this->load->model('Social_model','social');
$this->social->update($name,$profile);
$out = json_encode(array('result' => 'success'));
}
else
{
$out = json_encode(array('result' => 'failed'));
}
echo $out;
}
javascript
$('#social-form').on('submit', function (e) {
e.preventDefault();
var str = $("#social-form").serialize();
if (str === '') {
swal("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: baseUrl + "/admin/social/",
data: str,
dataType: 'json'
})
.done(function (data) {
console.log(data);
if (data.result === 'success') {
swal("Information", "Success", "info");
} else {
swal("Information", "Failed", "info");
}
})
.error(function () {
swal("Oops", "We couldn't connect to the server!", "error");
});
}
});

Codeigniter ajax form validation in modal not working

I want to validate my form which is in bootstrap modal. But all time validation_errors() returning empty string. I am using Codeigniter 3 and HMVC.
here is my ajax code
$('#add_unload').on('click', function (e) {
e.preventDefault();
var carrier_type = $.trim($('#carrier').val());
var truck_plateno = $.trim($('#truck_plateno').val());
$.ajax({
url: site_url + 'pre_unload/add',
type: 'get',
dataType: 'json',
data: {
carrier_type : carrier_type,
truck_plateno:truck_plateno
}
}).done(function (response) {
console.log(response);
});
});
and here is my controller's add method
public function add() {
if (!$this->input->is_ajax_request()) {
die('wrong');
}
$carrier_type = $this->input->get('carrier_type', TRUE);
$this->form_validation->set_rules('truck_plateno', 'Truck Plate', 'required');
if ($carrier_type == 'O') {
$this->form_validation->set_rules('another_filed', 'XXXX', 'required');
} else {
$this->form_validation->set_rules('another_filed', 'XXXX', 'required');
}
if ($this->form_validation->run() === FALSE) {
$this->load->helper('form');
echo json_encode(array('err' => validation_errors()));
return;
}
}
var_dump($this->form_validation->run());return; always return false and validation_errors() return empty string. I have tried this too $this->form_validation->run($this) still no luck. My_form_validation.php also ok in library
** I have loaded form_validation library in construct
Any IDEA?

ajax loader login issue

I would like to show a loader.gif to my user. If the user inputs valid username and password, would display an image progress bar for let's say 5 seconds and then redirect to the main page, otherwise, would display a loader.gif for 5 seconds and then display username or password incorrect.
This is what I've tried so far:
<script language="javascript">
$(document).ready(function(){
$("#loginForm").submit(function(){
$("#report").removeClass().addClass('loader').html('<img src="images/ajax-loader.gif">').fadeIn(1000);
$.post("checklogin.php",{ username:$('#username').val(),password:$('#password').val()},function(data){
if(data=='yes'){
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="images/loader-bar.gif">').addClass('log').fadeTo(900,1,function(){
document.location='main.php';
});
});
}
else {
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="images/icon_error.gif"> Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
});
</script>
But I'm trying to change this to be conform to CodeIgniter.
v_login.php view
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
var form_data = {
username : $('.username').val(),
password : $('.password').val() };
e.preventDefault();
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'ajax-loader'
});
//loader.insertAfter($('#cancel'));
$.ajax({ //
url: "<?php echo site_url('login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#message').html(msg);
if(form_data == 'unknown user'){
$("#message").fadeTo(2000,1,function(){
$(this).html('<img src="assets/img/icon_error.gif"> Username or password error.').addClass('error').fadeTo(900,1);
});
}
}
});
return false;
});
});
</script>
c_login.php controller
function ajax_check() {
//if($this->input->post('ajax') == '1') {
if($this->input->is_ajax_request()){
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user) {
echo 'login successful';
//$this->load->view('welcome');
} else {
echo 'unknown user'; //
//echo ' <img src="assets/img/icon_error.gif"> Username or password not valid';
}
}
}
}
But the problem is it's not showing the working as I want it to be. Any ideas? I'd really love to finish this problem and I'm new to Ajax and CI so I beg your pardon. Help will be truly appreciated by me. Thanks.

codeigniter and ajax contact form

I'm trying to use ajax within my contact form in a codeigniter app. I have it to where the ajax call is made, but no post data is being sent to the server. I can't figure out why. Please help.
I do have some returns in there, but they do nothing. Also, $this->input->post('name') is null.
Form view
<?php
echo form_open('welcome/submit_contact');
echo form_error('name');
echo form_label('Name', 'name'"');
echo form_input('name', set_value('name'), 'id="name);
echo form_error('email');
echo form_label('Email', 'email');
echo form_input('email', set_value('email'), 'id="email"');
echo form_error('phone');
echo form_label('Phone', 'phone');
echo form_input('phone', set_value('phone'), 'id="phone"');
#echo '<h5>Do not start with "1" and no dashes.</h5>';
echo form_error('message');
echo form_label('Message', 'message');
echo form_textarea('message', set_value('message'), 'id="message"');
$submitData = array(
'name' => 'submit',
'value' => 'Submit',
'id' => 'button'
);
echo form_submit($submitData);
echo form_close();
?>
<script type="text/javascript">
$(function() {
$('form').click(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('welcome/submit_contact'); ?>",
type: "post",
data: form_data,
success: function(msg) {
$('form').prepend('<h5 class="good">Message sent!</h5>');
$('h5.good').delay(3000).fadeOut(500);
alert(msg);
}
});
// prevents from refreshing the page
return false;
});
});
</script>
Controller function
function submit_contact()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h4 class="bad">', '</h4>');
$name = $this->input->post('name');
echo "name = ".$name;
$this->form_validation->set_rules('name', 'Name', 'trim|required|alpha_dash|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('phone', 'Phone' , 'trim|integer|exact_length[10]|xss_clean');
$this->form_validation->set_rules('message', 'Message', 'trim|required|max_length[1000]|xss_clean');
// there are validation errors
if($this->form_validation->run() == FALSE)
{
return "error";
}
else // there are no validation errors
{
/*************************
need to actually send the email
*************************/
return null;
}
}
EDIT: I've updated the code in my question. Basically now if there are validation errors, how would I get them to display on the form? I'm assuming I would return a value from my controller and then have a statement in my ajax success that if msg == "error" display the errors elseif msg == null, display success message. But how would i tell my view to display those errors based on an ajax success variable?
i think you should put id on input and textarea not on label i.e.
$data = array
(
"name"=>'message',
"value"=>'message',
"id"=>'message'
)
form_textarea($data);
if you set the id on the label then jquery will pick up nothing from what the user inserted and also codeigniter validation won't work correctly. This is why your post result to be NULL
the same for other input field
EDIT
you are asking data via ajax so return a nice json object (remove all your debug prints first):
// there are validation errors
if($this->form_validation->run() == FALSE)
{
echo(json_encode("validate"=>FALSE));
}
else // there are no validation errors
{
/*************************
need to actually send the email, then send you mail
*************************/
echo(json_encode("validate"=>TRUE));
}
then test it on your ajax success function to display positive or negative message
<script type="text/javascript">
$(function() {
$('form').click(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('welcome/submit_contact'); ?>",
type: "post",
data: form_data,
dataType: "json"
success: function(msg)
{
if(msg.validate)
{
$('form').prepend('<h5 class="good">Message sent!</h5>');
$('h5.good').delay(3000).fadeOut(500);
}
else
//display error
}
});
// prevents from refreshing the page
return false;
});
});
</script>

Categories