Codeigniter form validation in AJAX form submission - ajax

please help me.
I've been working recently in Codeigniter form validation without using AJAX and working fine, i just need to add $form_error to each field and everything just put on there. So, i am not good in javascript and really confusing how to show the errors response to each input field because when i am using AJAX the only idea i have is putting the response in a selector like $(#error-info)
This is my work so far
in my controller
$this->_rules();
if($this->form_validation->run() == FALSE)
$msg = array(
'name' => form_error('name'),
'phone' => form_error('phone'),
'email' => form_error('email')
);
echo json_encode($msg);
and my ajax :
<script type="text/javascript">
$(document).ready(function() {
$('#frm').submit(function(){
$.post($('#frm').attr('action'), $('#frm').serialize(), function( data ) {
console.log(data);
}, 'json');
return false;
});
});
</script>
the response look like this
{"name":"<small class=\"text-danger\">The name field is required.<\/small>","phone":"<small class=\"text-danger\">The phone field is required.<\/small>","email":"<small class=\"text-danger\">The email field is required.<\/small>"}
Please give me a hint. What a possible ways to do this?

Something like this should work (haven't tested):
PHP
$msg = array(
'name' => form_error('name'),
'phone' => form_error('phone'),
'email' => form_error('email')
);
echo json_encode(array('status' => 'error', 'response' => $msg));
AJAX
We assume that the indexes of the $msg array matches an actual id e.g. id='email' so we can propagate the error messages after the field.
$(document).ready(function () {
$('#frm').submit(function () {
$.post($('#frm').attr('action'), $('#frm').serialize(), function (res) {
var data = JSON.parse(res);
if (data.status == 'error') {
$.each(data.response, function(item_id, item_error_msg) {
$('#'+item_id).after().html(item_error_msg);
});
} else {
alert(data.response);
}
}, 'json');
return false;
});
});

Related

How to store validator errors into an object with Laravel and Vue.js

I am using Laravel 7 and Vue.js 2.
I made a form that should show a table if every field has been inserted.
I made also a server-side validation to check if all fields are correctly inserted.
This is the function that creates a call to the server with Axios:
runReport: function() {
const url = "api/get_report?room="+this.formReport['room']+"&participant="+this.formReport['participant']+"&start="+this.formReport['start']+"&end="+this.formReport['end'];
axios.get(url)
.then((response) => {
console.log(response.data.data);
this.meetingsReport = response.data.data;
alert('viva');
this.$emit('passMeetings', this.meetingsReport);
this.$emit('success');
})
.catch(function(error) {
console.log(error.response.data);
this.errors = error.response.data; //problem
alert('noviva');
});
}
This is the validator in the controller:
$validator = Validator::make($request->all(), [
'room' => 'required',
'start' => 'required',
'end' => 'required',
'participant' => 'required',
]);
if ($validator->fails()) {
return response($validator->errors(), 422);
}
If everthing has been correctly inserted in the form I have no problems, but if I missed a field I am unable to store the errors in an empty object that I created called errors.
UPDATED: This is the response from the validation failed (status 422):
{
"room": [
"The room field is required."
],
"participant": [
"The participant field is required."
]
}
I suppose the problem is that I am unable to access to this.errors from the catch block of Axios.
this in the context of an anonymous function doesn't point to the vue instance, so you may need to bind this to the function or use arrow function within the catch block
.catch(error => {
console.log(error.response.data);
this.errors = error.response.data; //should not be any - problem
alert('noviva');
});
At the end I solved using the keyword self in the axios call. In this way I was able to connect the catch block with Vue.js component.
This is the code:
runReport: function() {
let self = this;
const url = "api/get_report?room="+this.formReport['room']+"&participant="+this.formReport['participant']+"&start="+this.formReport['start']+"&end="+this.formReport['end'];
axios.get(url)
.then((response) => {
console.log(response.data.data);
this.meetingsReport = response.data.data;
alert('viva');
this.$emit('passMeetings', this.meetingsReport);
this.$emit('success');
this.errors = {};
})
.catch(function(error) {
console.log(error.response.data);
self.errors = error.response.data;
self.$emit('failure');
});
}

Laravel controller validation of request with nested parameters

I am trying to validate in my controller a request of nested parameters but I can't get it working. I did find a few resources online and tried different things with no success.
This is the script that sends the data to the controller:
var fieldsValuePair = {
type: this.history.type
};
axios.get('/app/admin/cms/clients/processActivity', {
params: {
fieldsValuePair: fieldsValuePair,
hid: this.history.hid
}
})
.then((response) => {})
.catch(error => {
this.errors = [];
this.errors = error.response.data;
console.log(this.errors);
});
This is my validation in my controller:
$this->validate($request, ['type' => 'required'] , ['activity-type.required']);
I want to say that if i add: type: this.history.type in my axios request just after hid: this.history.hid then the validation works correctly.
What I want to achieve is to have the type: this.history.type in the fieldsValuePair object and have this validate correctly in the controller.
I did find a solution but not sure if this would be the best one. At least it's working for me.
$rulesArray = [];
$fieldsValuePairArray = json_decode($request['fieldsValuePair'], true);
foreach ($fieldsValuePairArray as $key => $value) {
if($value == '')
$rulesArray[$key] = 'required';
}
$this->validate($request, $rulesArray , ['activity-type.required']);

Yii1: CGridView link ajax request shows 400 Bad Request

I am working on Yii 1 application. In my application, there is a CGridView where there is a link, which also fires an ajax request on onclick event. I am sending id as parameter. But the ajax return 400 Bad Request error. Please help me in this matter.
Here is the Gridview:
<h3>Civil Cases</h3>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'notifications-grid',
'dataProvider'=>$dataProvider_civil,
'summaryText' => false,
'columns'=>array(
array(
'name' => 'case_id',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->case_id),array("civilcases/view","id"=>$data->case_id), array("onclick"=>"js:readNotification($data->id)"))'
),
array(
'name' => 'caseno',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->caseno),array("civilcases/view","id"=>$data->case_id), array("onclick"=>"js:readNotification($data->id)"))'
),
'date_filing',
'next_date',
'panel_lawyer_id',
),
));
?>
here is the script:
<script>
var readNotification = function(id) {
console.log("button clicked with ID: "+id); //getting id here
$.ajax({
type:'POST',
url:'<?php echo Yii::app()->createUrl("notifications/readNotification");?>',
data: {id: id}
});
};
</script>
here is the controller:
public function actionReadNotification(){
echo $_POST['id'];
}
added readNotification function to the accessRules. When clicking on the link new page is loading but ajax request shows error.
Try adding the csrf token inside your data with your ajax request.
<script>
var readNotification = function(id) {
console.log("button clicked with ID: "+id); //getting id here
$.ajax({
type:'POST',
url:'<?php echo Yii::app()->createUrl("notifications/readNotification");?>',
data: {id: id,<?=
Yii::app()->request->csrfTokenName?>:<?=Yii::app()->request->csrfToken?>,}
});
};
</script>
You can also disable the csrftoken by adding the below in the beforeAction()
public function beforeAction($action) {
if($action->id=='readnotification'){
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
but this is not recommended way of doing the work.
EDIT
i mistakenly added Yii::$app->request instead of Yii::app()->request as the first one is for Yii2 and not for Yii1 please change it to
<?=Yii::app()->request->csrfTokenName?>:<?=Yii::app()->request->csrfToken?>
and make sure you have the request component with the following configurations
'components'=>array(
.
.
.
'request'=>array(
'enableCookieValidation'=>true,
'enableCsrfValidation'=>true,
'csrfTokenName'=>'_my-token',
),
Note : you can change the _my-token to any other name you like

How to validate input when submit without refreshing the page in Laravel?

if I have a unique column it will send a validate notif that indicates that this email already exists When I submit my input. I want to implement it in Laravel. Please, help me to start with this. Thanks
I am using axios for the example but you can you use jQuery Ajax as well
axios.post('/login', loginParams).then(function (r) {
//Do in case of success
}).catch(function () {
new Noty({
type: 'Danger',
text: '<b>' + r.data.success.name + '</b>',
}).show();
});
And in laravel
public function validator(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255|unique:users',
]);
}

Laravel form validation in image upload with ajax

I am working in laravel 5. and using blade and ajax for upload image.
Every thing was working fine unless I inserted validation code in store function inside controller. Getting server error:
POST http://localhost:8000/imgC 500 (Internal Server Error)
I guess there is something wrong with url inside ajax or in routes, I am using Restfull Controller.
image.blade.php
{{Form::open(array('url' => 'imgC', 'method' => 'post','files'=>true, 'id'=>'upload_form'))}}
Title: {{Form::text('title')}}
Image: {{Form::file('image')}}
{{Form::submit('submit',['id' => 'btnAddProduct'])}}
{{Form::close()}}
ImageController.php:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
return "error";
}
$destinationpath = public_path() . '/img/';
$image=$request->input('image');
$filename=$request->file('image')->getClientOriginalName();
$request->file('image')->move( $destinationpath,$filename );
$img= new Image;
$img->name= $request->input('title');
$img->picture_path=$filename;
$saveflag=$img->save();
if($saveflag){
return Response::json(['success' => $saveflag, 'file' => asset($destinationpath.$filename)]);
}
}
AJAX function:
$(document).ready(function() {
$('#upload_form').submit(function (event) {
event.preventDefault();
$.ajax({
url: '/imgC',
data: new FormData($(this)[0]),
type: "POST",
processData: false,
contentType: false
}).done(function (response) {
console.log(response);
$("#success").show();
setTimeout(function() { $("#success").hide(); }, 5000);
});
});
});
route.php:
Route::resource('imgC', 'ImageController');
What am I doing wrong here?
I looked into the server log files and figured it out.
There was error with validation after adding Use Validator; in Image controller, problem solved

Resources