codeigniter ajax form validation with submit - javascript

i have this ajax form validation code igniter. my view is something like this
<?php
echo form_open('Provinces/create',array('id' => 'form-user'));
?>
<label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
</div>
<button class="btn btn-info fa fa-save" type="submit">&nbsp Save</button>
<a href = '<?php echo base_url().'Provinces/index'; ?>' class = 'btn btn-danger fa fa-times-circle'>&nbsp Cancel</a>
<?php
echo form_close();
?>
and i have this javascript
<script>
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
url = "<?php echo site_url('Provinces/ajax_add')?>";
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
alert('success');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
</script>
i have found this code on google and just customized it. but the problem is, i am not that familiar with ajax, the part where the form validation fails, work perfectly fine, but when it is succes, even though it shows alert('success'); it doesnt add the value in the database. i need to finish this projects in a few weeks. please help.
here is where i get the validations,
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
also here is my ajax_add
public function ajax_add()
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}
and here is my model,
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}

i have solved it. just did put
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
into my controller, which makes my controller
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
and my javascript
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});

You dont't need to use uppercase when accessing your controller
just use
url = "<?php echo site_url('provinces/ajax_add')?>";
Validation the request data before inserting
try
public function ajax_add()
{
$response = array(
'success' => false
) ;
$this->load->library('form_validation');
// add your validation
$this->form_validation->set_rules('PROVINCE', 'PROVINCE', 'required');
if ($this->form_validation->run() == FALSE)
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE')
);
$insert = $this->Provinces_Model->save($data);
if($insert){
$response['success'] = TRUE ;
$response['message'] = 'Record created successfully' ;
}
else{
$response['message'] = 'Unable to create record' ;
}
}
else
{
$response['message'] = 'Invalid data' ;
}
echo json_encode($response);
}
Then check for the 'message' index in your ajax response in the javascript code
This will give an idea of where there is problem, whether its from the
view or
controller or'
Model

Related

Unable to post the data from view to controller in Yii2

I am working on Yii2. I have a gridview with checkbox and on a button click I am redirecting it to an action controller using ajax.
<?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'ref_no',
'dept_code:ntext',
'dept_name:ntext',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'diconnected_at',
'reconnected_at',
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
JS
<?php
$DCOurl = Url::toRoute(['/hecolog/dco']);
$script = <<< JS
$(document).ready(function () {
//DCO
$('#dco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: '$DCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
});
JS;
$this->registerJs($script, static::POS_END);
?>
But when I click on the disconnect button it doesn't redirect to my controller. In console it gives me Not Found (#404): Page not found.
Update 1
I have updated the ajax call like below
$.ajax({
url: $DCOurl, // removed the inverted commas ''
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
Controller
public function actionDco()
{
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
var_dump($data);
die();
}
else{
$this->redirect('index');
}
}
After updating the code as suggested I am able to go into my controller but still not able to get the data
In console I am getting error Uncaught SyntaxError: Invalid regular expression flags
Update 2
Below is the code for my view
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\web\JqueryAsset;
/* #var $this yii\web\View */
/* #var $searchModel common\models\HescologSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'DCO / RCO';
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="content-header">
<h1>DCO / RCO List</h1>
</section>
<section class="content">
<div class="box">
<div class="box-body">
<p>
<?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
<?= Html::a('Re-Disconnect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>
</p>
<?php Pjax::begin(); ?>
<div class="pre-scrollable">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'ref_no',
'dept_code:ntext',
'dept_name:ntext',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'diconnected_at',
'reconnected_at',
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<?php Pjax::end(); ?>
</div>
</div>
</section>
<?php
$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);
$script = <<< JS
$(document).ready(function () {
//DCO
$('#dco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: $DCOurl,
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
$('#rco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: '$RCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
});
JS;
$this->registerJs($script, static::POS_END);
?>
I must be doing something wrong which I am not understanding
Any help would be highly appreciated.
first of all url:'$DCOurl' is correct and url must be in single or
double quotation. so you have a not found problem:
is your project in htdocs or www followed by /inventory-web/backend/ or there are some more directories? you use relative url so the url would be for ex: localhost/inventory-web/backend/web/ ...
ajax type 'POST' should match with behaviors['verbs']['actions'] if you have set it
check controller file name, class name and namespace
First, if you're serving an Ajax request you cannot do a redirect:
public function actionDco()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$rv=[];
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
$rv["infos"]=$data;
$rv["status"]='gotData';
}
else{
$rv["url"]=Url::to('index');
$rv["status"]='redirect';
}
return $rv;
}
About the JS error, instead of:
$.ajax({
url: $DCOurl,
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
Add the quotes aroun the $DCOurl and to manage the return value from the ajax call
$.ajax({
url: "$DCOurl",
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
if(data.status=='gotData'){
alert(data.infos);
}
if(data.status=='redirect'){
window.location.href=data.url;
}
}
});

Call page PHP with Ajax

I have some difficulties to call PHP script with:
$("#tata").click(function(){
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
});
});
But my alert is empty... I am sure that the URL is correct, because if I add in my PHP file HTML code it appear on my alert!
I am sure that my PHP code works
PHP file:
echo "lalalala";
$getData = new mod_visitor();
$writeData = new writeData();
$urlPart1 = $_SERVER['HTTP_HOST'];
$urlPart2 = $_SERVER['REQUEST_URI'];
$pageEnCours = $urlPart1 .= $urlPart2;
$getData->get_ip();
$getData->LookupIP($GLOBALS['domain']);
$getData->ValidateIP($GLOBALS['domain']);
if ($GLOBALS['domain'] && $pageEnCours != preg_match("#localhost/joomla/$#", $pageEnCours)) {
$GLOBALS['domain'] = trim($GLOBALS['domain']);
if ($getData->ValidateIP($GLOBALS['domain'])) {
echo "cc";
$result = $getData->LookupIP($GLOBALS['domain']);
$writeData->write_domain($result);
} else {
echo "erreur";
$writeData->write_error();
};
} else {
echo "je ne rentre pas dans la boucle";
};
echo $pageEnCours;
echo $GLOBALS['domain'];
Parse the dataType to 'json'
Add dataType: 'json' to the javascript
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
dataType: 'json',
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
And echo back as JSON in your php
<?php
echo json_encode('lalala');
?>
If you want to return multiple items, you can return them as an array
<?php
$return = array(
'pageEnCours' => $urlPart1 . $urlPart2,
'domain' => $GLOBALS['domain']
);
echo json_encode($return);
?>
And get the items client-side
success: function(data) {
console.log(data.pageEnCours, data.domain);
}

check if email exist in database SQL using codeigniter and AJAX

modal screenshot
i have a form inside bootstrap modal, i want to validate if the email already exist in database. the result direct to the blank page with this thing '{"valid":false,"msg":"Email is already taken"}'. i want the msg appear just like i figure it in screenshot.
View
<?php echo form_open('KulinerControl/isEmailExist', 'id="myform"'); ?>
<div id="msg"> </div>
<input type="text" name="email" id="email" class="input-lg formcontrol">
<button type="submit">Submit</button>
</form>
JS
$(document).ready(function(){
$('#myform').on('submit', function(e) {
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
dataType: "json",
data: "email="+email,
success: function(data){
if(data.valid){
$('#msg').html(data.msg);
}else{
$('#msg').html(data.msg);
}
}
});
});
});
Controller
function isEmailExist(){
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
$msg = array(
'valid' => false,
'msg' => 'Email is already taken');
}else{
$msg = array(
'valid' => true,
'msg' => 'Username is available');
}
echo json_encode($msg);}
update controller
function isEmailExist(){
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
echo "Email is already taken !";
}else{
$data = array(
'nama' => $this->input->post('nama'),
'email' => $email,
'password' => md5($this->input->post('password'))
);
$query = $this->KulinerModel->addMember($data);
redirect('/KulinerControl/');
}
}
Thanks in advance
you need to stop submitting your form at first then start checking. then if checking find its ok then submit it. i would use the following
$(document).ready(function(){
$('#myform').on('submit', function(e) {
e.preventDefault(); //<---- stop submiting the forms
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
dataType: "json",
data: "email="+email,
success: function(data){
if(data.valid){
$('#msg').html(data.msg);
$("#myform").submit(); //<---- submit the forms
}else{
$('#msg').html(data.msg);
}
}
});
});
});
I think real time email checking is better for your situation
<script>
$(document).ready(function(){
$('#email').keyup(function(){
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
data: "email="+email,
success: function(response){
$('#msg').html(response);
}
});
});
});
</script>
In Your controller
function isEmailExist()
{
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
echo "Email is already taken";
}else{
echo "";
}
}
To prevent submitting an easy trick
$(document).ready(function(){
$('#myform').on('submit', function(e) {
if ($.trim($("#msg").val()) === "") {
alert('please choose a different email id');
return false;
}
});
});
change Your Form action controller to this
function dataInsert()
{
$data = array(
'nama' => $this->input->post('nama'),
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password'))
);
$query = $this->KulinerModel->addMember($data);
redirect('/KulinerControl/');
}

Second Wordpress Ajax not firing

Hi there I am trying use some wordpress ajax my first ajax request works fine but the second one does not. Can some one please tell me why this is happening
Works fine:
PHP
//Add Students Details to DB
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$diet = $_POST['diet'];
$current_id = get_current_user_id();
global $wpdb;
$result = $wpdb->insert(
'wp_students',
array(
'ID' => NULL,
'first_name' => $fName,
'last_name' => $lName,
'birthdate' => $dob,
'gender' => $gender,
'dietary_requirements' => $diet,
'user_id' => $current_id
)
);
echo json_encode($result);
wp_die();
}
JS
var data_value = {
action: 'my_action',
fName: $(acc[i]).find('input.fName').val(),
lName: $(acc[i]).find('input.lName').val(),
dob: $(acc[i]).find('input.dob').val(),
gender: $(acc[i]).find('select.gender').val(),
diet: $(acc[i]).find('textarea.diet_req').val()
};
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: data_value,
success: function(msg) {
if (msg == false) {
$('#insert_status').html('<strong><span style="color: red;">Error: </span></strong>Details Have Not Been Updated');
return false;
}
},
error: function(xhr, status, error) {
var i = JSON.parse(xhr.responseText)
alert(i.Message);
}
});
Does not work:
PHP
//Delete Students Details
add_action( 'wp_ajax_my_delete', 'my_action_callback_delete' );
function my_action_callback_delete() {
echo 'here';
global $wpdb;
$result = $wpdb->delete( 'wp_students', array( 'usesr_id' => get_current_user_id()) );
echo json_encode($result);
wp_die();
}
JS
var value = {
action: 'my_delete'
};
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: value,
success: function(msg) {
if (msg == false) {
$('#insert_status').html('<strong><span style="color: red;">Error: </span></strong>Details Have Not Been Updated');
return false;
}
},
error: function(xhr, status, error) {
var i = JSON.parse(xhr.responseText)
alert(i.Message);
}
});
If you could help me would be great. Wordpress Ajax is not a straight forward as normal ajax.
Could it be that you just have a typo in your delete function?
'usesr_id' => get_current_user_id()
should probably be
'user_id' => get_current_user_id()
//Delete Students Details
add_action( 'wp_ajax_my_delete', 'my_action_callback_delete' );
function my_action_callback_delete() {
echo 'here';
global $wpdb;
$result = $wpdb->delete( 'wp_students', array( 'usesr_id' => get_current_user_id()) );
echo json_encode($result);
wp_die();
}

"You did not select a file to upload. " get this error while uploading image using ajax

I am working with CodeIgniter and jQuery ajax. I want to upload image using ajax. But it shows an error like You did not select a file to upload.
Here,I have write jQuery :
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = jQuery(this).serialize();
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
<form id="signup_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-3">Upload Photo</div>
<div class="col-md-4">
<input type="file" name="pic" accept="image/*">
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
And My function looks like this :
function ajax_register()
{
if($this->input->post())
{
$this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
$this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
if($this->form_validation->run() == true)
{
$img = "";
$config['upload_path'] = './uploads/user/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('pic'))
{
$data['error'] = array('error' => $this->upload->display_errors());
print_r($data['error']);exit;
$data['flash_message'] = "Record is not inserted";
}
else
{
$upload = $this->upload->data();
//print_r($upload);exit;
$data = array(
'ip_address' =>$this->input->ip_address(),
'first_name' =>$this->input->post('firstname'),
'last_name' =>$this->input->post('lastname'),
'phone' =>$this->input->post('phone'),
'email' =>$this->input->post('email'),
'group_id' =>$this->input->post('role'),
'password' =>$this->input->post('password'),
'image' =>$upload['file_name'],
'date_of_registration' =>date('Y-m-d')
);
print_r($data);exit;
$user_id = $this->admin_model->insert_user($data);
$user_group = array(
'user_id' => $user_id,
'group_id' => $this->input->post('role')
);
$this->admin_model->insert_group_user($user_group);
echo "<p style='color:red;'>You are successfully registerd.</p>";
}
}
else
{
echo "<p style='color:red;'>".validation_errors()."</p>";
}
}
}
So how to resolve this issue?What should I have to change in my code?
As I said, the problem is probably in the data you send to backend. If you want to submit AJAX with input file, use FormData.
Try this:
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = new FormData($('#signup_form')[0]);
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
processData: false,
contentType: false,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
Try this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php :
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload the file.
P.S.: Change the code as per CI method.
var data = jQuery(this).serialize();
this refers to document

Categories