Laravel form validation in image upload with ajax - 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

Related

CSRF TOKEN MISTATCH LARAVEL

I am facing CSRF token mismatch problem in laravel. I have checked all notes from stackflow and other sites also but not able to clear this problem.
https://mybestlife.mg-wellness.com/admin/login
user : admin#gmail.com
pass : 1234
you can check the error in console.
Ajax
$("#loginform").on('submit', function(e){
e.preventDefault();
$('button.submit-btn').prop('disabled', true);
$('.alert-info').show();
$('.alert-info p').html('Authenticating...');
$.ajax({
type:"POST",
url:$(this).prop('action'),
data:new FormData(this),
headers: headers,
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log(data);
if ((data.errors)) {
$('.alert-success').hide();
$('.alert-info').hide();
$('.alert-danger').show();
$('.alert-danger ul').html('');
for(var error in data.errors) {
$('.alert-danger p').html(data.errors[error]);
}
} else {
// console.log(data)
$('.alert-info').hide();
$('.alert-danger').hide();
$('.alert-success').show();
$('.alert-success p').html('Success !');
window.location.href = data;
}
$('button.submit-btn').prop('disabled',false);
}
});
});
Login function
public function doLogin(Request $request)
{
// print_r($request->all());
$rules = [
'email' => 'required|email',
'password' => 'required'
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
}
//--- Validation Section Ends
// Attempt to log the user in
if (Auth::guard('web')->attempt([
'email' => $request->email,
'password' => $request->password,
'status' => 1,
'role' => 1,
'level' => 0
], $request->remember)) {
// if successful, then redirect to their intended location
return response()->json(route('dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return response()->json(array('errors' => [
0 => 'Credentials Doesn\'t Match !'
]));
}
Code is working perfectly on localhost and my testing server. But not on the server, i shared above.
Please help me to over come this problem.
Thanks
I think you're missing a header. That's how I've always passed the CSRF token when I use ajax.
The following should be in your resources/js/bootstrap.js file.
window.$ = window.jQuery = require('jquery');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
});
When trying to login using your site, I couldn't see the X-CSRF-TOKEN header in the request.
I think you didn't set the APP_URL's value correctly. It should be
APP_URL=https://mybestlife.mg-wellness.com instead of what you currently have. (APP_URL=http://localhost/mybestlife_mg_wellness/)
(run php artisan config:clear after changing .env file)
Your site has debug mode on and an unrelated error about the route 'user_login' not existing, this exposes your whole configuration. Please take care to update your database credentials, they are compromised.
This is very important.
Also, rerun the command php artisan key:generate to update the APP_KEY as well.
you have to add #csrf in your form
<form method="post" action="javascript:void(0)" enctype="multipart/form-data">
#csrf
</form>
also add header in jquery
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
also add this meta tag in head of page
<meta name="csrf-token" content="{{ csrf_token() }}">
then you will never get token error .
Add a below line in data array
data:{
_token : {{csrf_field()}},
name:name
}

Laravel API call goes through even with session expired

I have a SPA based on Laravel 5.8 and Vue 2.0.
Everything is working fine, a little bit too much to be honest, because if I delete the session and I try to save the content afterward or keep navigating the private pages, every ajax call that I'm doing with Axios is going through without returning any error. Only if I forcefully refresh the page I get the error page I setup but if I don't, I can keep doing everything even if the session no longer exist.
This is my setup.
web.php is where I have the only php route that points to a singlePageController:
Auth::routes();
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
Then in the singlePageController I return the view:
class SinglePageController extends Controller
{
public function index() {
return view('app', ['loggedUser' => auth()->user()]);
}
}
Then I have the api.php where I have the API routes. As you can see at the end I have the middleware to make it private. Just to make an example this is the one I use for updating the content:
Route::put('event/update/{slug}', 'EventController#update')->middleware('auth:api');
Then the related controller of that API route:
public function update(Request $request, $slug)
{
$event = Event::where('slug', $slug)->first();
$event->title = $request->input('title');
return new EventResource($event);
}
And in the end this is the Resource I use to define what and how the API data is going to be displayed:
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'curator' => $this->curator,
'featured_image' => $this->featured_image,
'body' => $this->body,
'date' => $this->date
];
}
So this above is the flow I have. Then when I do an axios call to update the content, I'm doing something like:
axios({
method: 'PUT',
url: '/api/event/update/' + this.$route.params.slug + '?api_token=' + this.isLogged.apiToken,
data: dataToSave,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
.then((response) => {
this.getNotification('Success: The Event has been saved');
})
.catch((error) => {
this.getNotification('Error: Impossible saving the event');
console.log(error);
})
Thanks in advance for the help
In Laravel routes in api.php ignore the session data.
If you want to authenticate with session data you could move your api routes to web.php and you should see the results you expect.

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

Codeigniter form validation in AJAX form submission

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;
});
});

Laravel ajax 422 Unprocessable Entity even when token is matching

I'm getting 422 Unprocessable Entity error even when I'm submitting my form via Ajax.
My javascript file
$.ajaxSetup({
headers: {
'X-XSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.keywords-plan-form').submit(function(event) {
event.preventDefault();
$.ajax({
url: '/laravel/public/keywordsplans',
type: 'POST',
data: $(this).serialize(),
success: function(data){
alert(data);
// success logic
},
error: function(data){
// Error...
var errors = $.parseJSON(data.responseText);
console.log(errors);
$.each(errors, function(index, value) {
});
}
});
});
as you can see I added X-XSRF-TOKEN****strong text to ajax header.
This is my '' tag
<meta name="csrf-token" content="{{ csrf_token() }}">
my Form Data in chrome debuger
_token:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
date:
keyword[0]:Lorem ipsum
keyword[1]:Is dolor amet
keyword[2]:plumber tampa
Request Headers
X-XSRF-TOKEN:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
.....
am I doing something wrong or forgetting something?
I don't think that csrf token is the issue here. If it were you would get TokenMissmatchException and not Unprocessable Entity.
Do you happen to have a request validator in your Controller like this?
$validator = Validator::make($request->all(), [
'username' => 'required|max:30|min:6|unique:users',
'email' => 'required|email|max:50|unique:users',
'password' => 'required|confirmed|min:6',
]);
If so maybe you can do something like this:
if ($validator->fails()) {
if($request->ajax())
{
return response()->json(array(
'success' => false,
'message' => 'There are incorect values in the form!',
'errors' => $validator->getMessageBag()->toArray()
), 422);
}
$this->throwValidationException(
$request, $validator
);
}
After that you can catch validation errors in your ajax error handler like this:
$('.keywords-plan-form').submit(function(event) {
event.preventDefault();
$.ajax({
url: '/laravel/public/keywordsplans',
type: 'POST',
data: $(this).serialize(),
success: function(data){
alert(data);
// success logic
},
error: function(jqXhr, json, errorThrown){// this are default for ajax errors
var errors = jqXhr.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
});
//I use SweetAlert2 for this
swal({
title: "Error " + jqXhr.status + ': ' + errorThrown,// this will output "Error 422: Unprocessable Entity"
html: errorsHtml,
width: 'auto',
confirmButtonText: 'Try again',
cancelButtonText: 'Cancel',
confirmButtonClass: 'btn',
cancelButtonClass: 'cancel-class',
showCancelButton: true,
closeOnConfirm: true,
closeOnCancel: true,
type: 'error'
}, function(isConfirm) {
if (isConfirm) {
$('#openModal').click();//this is when the form is in a modal
}
});
}
});
});
And see the messages in the
modal message
Maybe someone will come in handy.
422 Unprocessable Entity
is default error by validator laravel
vendor/laravel/framework/src/Illuminate/Validation/Validator.php
If fails validate params, then throught Exception ValidationException
vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php
where default status = 422
And therethore all your ajax responses with non validate forms will be with status = 422
I have solved this issue :
public function register(\Illuminate\Http\Request $request) {
if ($this->validator($request->all())->fails()) {
$errors = $this->validator($request->all())->errors()->getMessages();
$clientErrors = array();
foreach ($errors as $key => $value) {
$clientErrors[$key] = $value[0];
}
$response = array(
'status' => 'error',
'response_code' => 201,
'errors' => $clientErrors
);
} else {
$this->validator($request->all())->validate();
$user = $this->create($request->all());
$response = array(
'status' => 'success',
'response_code' => 200
);
}
echo json_encode($response);
}
Whoever is still looking for the answer, if you are using Lumen make sure the Request object is a type of Illuminate\Http\Request and not the default one from Lumen.
```function create(Request $request){

Resources