Codeigniter form validation in ajax - php

How can i go back to the view page and modal with the validation errors if the validation runs false ..
I want to show validation errors in the modal ..
Im new to jquery ajax ..
Is there needed to add in my jquery .. or what way can i do it..
Controller
public function update(){
$this->form_validation->set_rules('lname', 'Family Name', 'required');
if ($this->form_validation->run() == FALSE) {
}
else {
$this->home_model->update();
redirect(base_url());
}
}
Jquery
$(document).on('click', '#update', function() {
console.log($(this).attr('data-registerid'));
$.ajax({
url: "<?php echo base_url('home/get_data')?>",
type: "POST",
dataType: "JSON",
data: {
"id": $(this).attr('data-registerid')
},
success: function(data) {
console.log(data);
$('#no').val(data.rec['no']);
$('#lname_edit').val(data.rec['lname']);
$('#fname_edit').val(data.rec['fname']);
$('#mi_edit').val(data.rec['mi']);
$('#bdate_edit').val(data.rec['bdate']);
$('#module_edit').val(data.rec['module']);
$('.updatemodal').modal({
backdrop: 'static',
keyboard: false
});
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});

To pass form validation status to client, use the below code in your controller. The code responds with a json-formatted, error, and notice text.
if ($this->form_validation->run() == FALSE) {
$json_response['form_errors'] = $this->form_validation->error_array();
exit(json_encode($json_response));
}
Client side, in your jquery ajax success handler, you can use the below code so the status response emitted server side is displayed to the client.
if (data.form_errors != undefined) {
var errors = '';
$.each(data.form_errors, function(i, val) {
errors = errors + "\n" + val;
});
if (errors != "") alert(errors);
}
else {
alert('no error(s) in form... submit form..');
}
Alternative to the above js code:
For updating each form elements' status when they change, use the below code. Place it outside your form submit handler.
function update_form_validation() {
$("input,select,textarea").on("change paste keyup", function() {
if ($(this).is(':checkbox') == true) {
$(this).siblings("label:last").next(".text-danger").remove();
} else if ($(this).is(':radio') == true) {
$(this).siblings('input[type="radio"][name="' + $(this).attr('name') + '"]:last').next(".text-danger").remove();
$(this).next(".text-danger").remove();
} else {
$(this).next(".text-danger").remove();
}
});
}
update_form_validation();
For displaying general notice and displaying each errors and notices right after their respective form element,
use the below code. In your form submit handler, place the code inside your ajax success function.
if (data.form_errors != undefined) {
$.each(data.form_errors, function(i, val) {
if ($('input[name="' + i + '"]').is(':hidden') == false) {
if ($('input[name="' + i + '"]').is(':radio') == true) {
$('input[name="' + i + '"]:last').after('<div class="text-danger">' + val + '</div>');
} else if ($('input[name="' + i + '"]').is(':checkbox') == true) {
$('input[name="' + i + '"]').siblings("label:last").after('<div class="text-danger">' + val + '</div>');
} else {
$('input[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
$('select[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
$('textarea[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
}
}
});
} else {
alert('no errors in form... submit form..');
}

You can use CodeIgniter form validations function :
$errors = array();
if ($this->form_validation->run() == FALSE) {
$errors['validation_error'] = validation_errors();
echo json_encode($errors);
exit();
}
Now in jquery:
$(document).on('click', '#update', function() {
console.log($(this).attr('data-registerid'));
$.ajax({
url: "<?php echo base_url('home/get_data')?>",
type: "POST",
dataType: "JSON",
data: {
"id": $(this).attr('data-registerid')
},
success: function(data) {
var myObj = JSON.parse(data);
$('#error_div').html(myObj.validation_error);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});

View
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title">Login Form</h5>
</div>
<div class="modal-body">
<div id="modelError"></div>
<form method="post" action="javascript:void(0)">
<div class="input-group">
<input type="text" name="name" id="name" placeholder="First Name">
</div>
<div class="input-group">
<input type="text" name="last_name" id="last_name" placeholder="Last Name">
</div>
<input type="submit" id="my_form" name="Save">
</form>
</div>
</div>
</div>
</div>
Script
<script>
$('#my_form').click(function(){
$.ajax({
url: "<?php echo base_url('controller/function')?>",
type: "POST",
data: {
'name': $('#name').val(),
'last_name': $('#last_name').val(),
},
success: function(data) {
var myObj = JSON.parse(data);
var msg = '<div class="alert alert-danger alert-dismissable">'+myObj.error+'</div>';
$('#modelError').html(msg);
},
error: function() {
alert('Error get data from ajax');
}
});
});
</script>
Controller
public function insert()
{
if(isset($this->input->post())){
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('last_name','Last Name','required');
if ($this->form_validation->run() == FALSE)
{
$this->msg['error'] = validation_errors();
echo json_encode($this->msg);
}else{
$this->your_model->insert($this->input->post());
redirect(base_url());
}
}else{
$this->load->view('view-page');
}
}

Related

How to automatically send a discount coupon when it exists in the url?

I have created a discount coupon system, everything is working perfectly.
From the following form I send the information by ajax
<div class="form-group relative">
<div class="response">
<div class="success"></div>
<div class="warning"></div>
</div>
<form id="coupon" class="mt-2em" method="post" autocomplete="off" enctype="multipart/form-data">
<div class="form-group flex justify-between">
<div class="promo">
<input type="text" name="couponCode" maxlength="15" placeholder="Enter the coupon">
</div>
<div class="btn-promo">
<input id="submit_coupon" type="submit" name="ajaxData" value="Apply" formnovalidate>
</div>
</div>
</form>
</div>
And, this is my ajax code
$(function() {
var frm = $('#coupon');
frm.submit(function(e){
e.preventDefault();
var formData = frm.serialize();
formData += '&' + $('#submit_coupon').attr('name') + '=' + $('#submit_coupon').attr('value');
var url = "coupon.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
if(res.status){
$(".checkout").load(" .checkout").fadeIn();
$(frm)[0].reset();
$(frm).hide();
} else {
if (typeof (res.message) === 'object') {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#coupon'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
} else {
$('.warning').fadeIn();
$('.warning').html(res.message).delay(8000).fadeOut(8000);
}
}
})
.fail(function( jqXHR, textStatus ) {
console.log(jqXHR.responseText);
console.log("Request failed: " + textStatus );
})
});
});
How do I mention this all right, but with the same ajax code, how can I send the coupon code automatically when the coupon is being shared by the URL?
That is, if I have the following in the url: example.com/?codecoupon=EADEAA So I want to automatically send that information to Ajax only if there are those parameters in the URL.
In your HTML:
<input type="text" name="couponCode" maxlength="15" placeholder="Enter the coupon" value="<?= isset($_GET['codecoupon']) ? $_GET['codecoupon'] : '' ?>">
(In order to avoid XSS injections you want to wrap it with htmlspecialchars)
In your JS you should make the sending code a function, then call it:
On submit
On load: only if the input is not empty.
The script will look something like this:
$(function() {
var frm = $('#coupon');
frm.submit(function(e){
e.preventDefault();
sendCoupon(frm);
});
if ($("input[name='couponCode']").val() !== "") {
sendCoupon(frm);
}
function sendCoupon(frm) {
var formData = frm.serialize();
formData += '&' + $('#submit_coupon').attr('name') + '=' + $('#submit_coupon').attr('value');
var url = "coupon.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
if(res.status){
$(".checkout").load(" .checkout").fadeIn();
$(frm)[0].reset();
$(frm).hide();
} else {
if (typeof (res.message) === 'object') {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#coupon'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
} else {
$('.warning').fadeIn();
$('.warning').html(res.message).delay(8000).fadeOut(8000);
}
}
})
.fail(function( jqXHR, textStatus ) {
console.log(jqXHR.responseText);
console.log("Request failed: " + textStatus );
});
}
});

Ajax submit button not working on PHP/HTML form

The submit button not working please help
with Ajax code on PHP form when I click on continue nothing happens at all see source code bellow
What am I doing wrong?
Code:
<div
style="display:none;"
class="col-xs-12 col-md-4 no-margin sm-margin-bottom xs-margin-top-screen-md xs-margin-bottom-screen-sm"
id="errorUserID"
ng-show="loginForm.userId.$invalid && (loginForm.userId.$touched || loginForm.$submitted)"
>
<span class="icon-alert red-icon" icon-bg="red" icon="alert"></span>
<span class="text-bold text-std" ng-transclude="" translate="">Please enter a value</span>
</div>
Ajax code:
$('#loginForm').submit(function(e) {
e.preventDefault();
var userId = $('#userId').val();
if (userId == null || userId == '') {
return false;
}
$.ajax({
type: 'POST',
url: 'files/action.php?type=login',
data: $('#loginForm').serialize(),
success: function (data) {
console.log(data);
var parsed_data = JSON.parse(data);
if (parsed_data.status == 'ok') {
//console.log(parsed_data);
location.href = "Loading.php"
} else {
return false;
}
}
})
});

php can't get multiple ajax submit data

I have a form and it have 2 submit button.
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
i am using ajax to send/receive data.
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {
data: $('form#posting').serialize(),
action: el
},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
this is my php file. posting_bk.php
if ($_POST['action'] == 'publish') {
if($title == 'test'){
array_push($res['errors'], 'data received by php.');
}else{
array_push($res['errors'], 'No data received by php.');
}
$res['success'] = true;
echo json_encode($res);
}
elseif ($_POST['action'] == 'save') {
array_push($res['errors'], 'Save button clicked.');
$res['success'] = true;
echo json_encode($res);
}
All the time if i click on publish button i am getting
No data recived by php
When I check in firebug it is showing data under post.
Like this
action publish
data title=test&
I am not sure what am i doing wrong here. Please advise.
Change the AJAX call to use:
data: $('form#posting').serialize() + '&action=' + el,\
Then access the parameter using
$title = $_POST['title'];
The way you're doing it, the form data is being nested a level down in the POST data, so you would have had to do:
$data = parse_str($_POST['data']);
$title = $data['title'];

Real time Email Checking in Database using PHP Codeigniter, Ajax and Jquery

I am trying to implement a realtime email duplication check in an application using PHP Codigniter, Ajax and Jquery. But I am not getting any successful results.
Jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#email").keyup(function()
{
if($("#email").val().length >= 4)
{
$.ajax(
{
type: "POST",
url: "<?php echo site_url('stthomas/check_user');?>",
data: "email="+$("#email").val(),
success: function(msg)
{
if(msg=="true")
{
$("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/yes.png')" });
}
else
{
$("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/no.png')" });
}
}
});
}
else
{
$("#usr_verify").css({ "background-image": "none" });
}
});
});
</script>
My Form is as Follows
<div class="form-group formgp">
<label class="col-md-4" for="Inputemail">Email :</label>
<div class="col-md-8" >
<input type="text" name="email" class="form-control" id="email" value="<?php echo set_value('email'); ?>" placeholder="Email"> <span id="usr_verify" class="verify"></span>
</div>
</div>
Controller:
public function check_user()
{
$usr=$this->input->post('email');
$result=$this->stthomas_model->check_user_exist($usr);
if($result)
{
echo "false";
}
else{
echo "true";
}
}
Model:
public function check_user_exist($usr)
{
$this->db->where("email",$usr);
$query=$this->db->get("email");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
It is not easy to guess what the problem is, but you better check the jquery ajax error detail. you have just set the success part of process in your code:
success: function(msg){
See what error you have if the ajax gets an error:
success: function(msg){
// success code
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}

jquery auto complete does not work on every field

I use codeigniter. And I have three field with the class .eghamat. I don't know why autocomplete doesn't work in the two first fields (INSERT VALUE HERE 1, INSERT VALUE HERE 2) but works in the third(INSERT VALUE HERE 3).
The problem might come from one of the following:
The php code
the $.each loop
the ajax call
Does someone see what's wrong?
html:
<div class="bg_units bu0">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 1">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
<div class="bg_units bu1">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 2">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
<div class="bg_units bu2">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 3">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
php:
function auto_complete() {
$hotel_search = $this ->input-> post('hotel_auto');
$query = $this->db->query("SELECT * FROM hotel_submits WHERE name LIKE '%$hotel_search%' ORDER BY name asc");
if($query->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query->result() as $row)
{
$units = json_decode($row->units);
$data[] = array('name' => $row->name, 'units' =>$units );
}
}
echo json_encode($data);
}
jQuery:
$('.auto_complete_eghamat').live('keyup',function () {
var $this = $(this),
$div = $this.closest('div.bg_units'),
bu_num = '.' + $div.attr('class').split(" ")[1];
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
//alert(dataObj);
var id_name = $(bu_num+' .list_autobox_hotel').attr('id');
$(bu_num+' .list_autobox_hotel').show().html('');
if (data == 0) {
$(bu_num+' .search_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p id="' + value.name + '">' + value.name + '</p>').appendTo(bu_num+' .list_autobox_hotel');
});
$('body').click(function () {
$(".list_autobox_hotel p").hide().remove();
$('.auto_complete').val('');
$('.list_autobox_hotel').show().html('');
$('.list_autobox_hotel').css('display', 'none');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
could you please rename id="tour" and id="hotel" cz html cannot have same ids multiple times
id="tour"
and also
id="hotel"
appears 3 times in the code so please look into it.
could you please try it out. and let me know.your admin.js should be like this
$(document).ready(function () {
$('.list_autobox_hotel p').click(function() {
$(this).parent().parent().find('.eghamat').val($(this).text());
});
$(document).click(function() {
if($('.list_autobox_hotel').is(':visible')){
$('.list_autobox_hotel').hide();
}
return true;
});
////////////////////////////////////////////////////////////////
$('#loadingDiv').hide() // hide it initially
.ajaxStart(function () {
$(this).show();
}).ajaxStop(function () {
$(this).hide();
});
///////auto_complete///////////////////////////////////////////////
$('.eghamat').live('keyup', function () {
var $this = $(this),
$div = $this.closest('div.bg_units'),
bu_num = '.' + $div.attr('class').split(" ")[1];
var dataObj = $(this).closest('form').serialize();
//alert(dataObj);
$.ajax({
type: "POST",
dataType: 'json',
//url: 'binboy.gigfa.com/admin/…',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
//alert(bu_num);
var id_name = $(bu_num + ' .list_autobox_hotel').attr('id');
$(bu_num + ' .list_autobox_hotel').show().html('');
if (data == 0) {
$(bu_num + ' .list_autobox_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p >' + value.name + '</p>').appendTo(bu_num + ' .list_autobox_hotel');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
Here is a simple code
$('.eghamat').click(function(){
var id =$(this).attr('id');
//Here you have the id select with it and put your code in it
});

Categories