iam try to upload image by ajax in laravel.
here is my js code :
$('#profile_picture').on('submit', function(event){
event.preventDefault();
$.ajax
({
type: "POST",
url: "{{url('all/update-profile-picture')}}",
data:new FormData(this),
dataType:'json',
type:'post',
processData: false,
contentType: false,
cache:false,
}).done( function(data){
//swal("Good job!", "Your information has been successfully updated!", "success")
console.log('Ajax was Successful!')
console.log(data)
}).fail(function(xhr, textStatus, error){
console.log(textStatus)
console.log(error)
});
});
here is controller code :
$validation = Validator::make($request->all(), [
'profile_photo'=> 'required|image|mimies:jpeg,png,jpg,gif|max:2048'
]);
if ($validation->passes()) {
//$image = $request->file('profile_photo');
$new_name = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path("photo"),$new_name);
return response()->json([
'message' => 'Image uploaded successfully'
]);
} else {
return response()->json([
'message' => $validation->errors()->all(),
'profile_photo' => '',
'class_name' => 'danger'
]);
}
I hope its my controller's problem . when click submit with blank , its seen error message in console.
I don't understand whats the problem ??
you need to use file() method for get your request file.
$validation = Validator::make($request->all(), [
'profile_photo'=> 'required|image|mimies:jpeg,png,jpg,gif|max:2048'
]);
if ($validation->passes()) {
$new_name = time().'.'.$request->file('profile_photo')->getClientOriginalExtension();
$request->file('profile_photo')->move(public_path("photo"),$new_name);
return response()->json([
'message' => 'Image uploaded successfully'
]);
}
return response()->json([
'message' => $validation->errors()->all(),
'profile_photo' => '',
'class_name' => 'danger'
]);
Related
I have a page with GridView and I want to make it possible to edit data without reloading the page. The GridView structure is basic. When I click on the button, I upload the form to the modal window and then track the form submission event. The data changes correctly, but ajax validation does not work.
ActiveForm
<?php $form = ActiveForm::begin([
'id' => 'update-form',
'action' => Url::to(['/product/ajax-update', 'wbId' => $model->wbId]),
'validationUrl' => Url::to(['/product/ajax-validate', 'wbId' => $model->wbId]),
'enableAjaxValidation' => true,
'validateOnChange' => true,
'method' => 'post',
]); ?>
<?= $form->field($model, 'wbId') ?>
<?= $form->field($model, 'supplierArticle') ?>
<?= $form->field($model, 'costPrice') ?>
<?= $form->field($model, 'accountName') ?>
<?php ActiveForm::end(); ?>
Validation rules
public function rules()
{
return [
[['wbId', 'supplierArticle', 'costPrice', 'createDate'], 'required'],
[['wbId'], 'integer'],
[['costPrice'], 'number'],
[['createDate', 'updateDate'], 'safe'],
[['supplierArticle'], 'string', 'max' => 100],
[['accountName'], 'string', 'max' => 50],
[['wbId'], 'unique'],
];
}
Load modal form function
public function actionLoadForm()
{
Yii::$app->response->format = Response::FORMAT_JSON;
if (Yii::$app->request->isAjax)
{
$wbId = Yii::$app->request->post('wbId');
if ($wbId)
{
$product = Product::find()->where(['wbId' => $wbId])->one();
if ($product)
{
return [
'success' => true,
'render' => $this->renderPartial('parts/form', [
'model' => $product
])
];
}
}
}
return false;
}
Ajax update function
public function actionAjaxUpdate($wbId)
{
Yii::$app->response->format = Response::FORMAT_JSON;
if (Yii::$app->request->isAjax)
{
/* #var $model Product */
$model = Product::find()->where(['wbId' => $wbId])->one();
if ($model)
{
if ($model->load(Yii::$app->request->post()) && $model->validate())
{
if ($model->save())
{
return [
'success' => true
];
}
}
}
}
return [
'success'=> false
];
}
Ajax validation
public function actionAjaxValidate($wbId)
{
Yii::$app->response->format = Response::FORMAT_JSON;
if (Yii::$app->request->isAjax)
{
/* #var $model Product */
$model = Product::find()->where(['wbId' => $wbId])->one();
if ($model->load(Yii::$app->request->post()))
{
return ActiveForm::validate($model);
}
}
return false;
}
Js - load form
$(document).on('click', updateItemButton, function (e)
{
let wbId = $(this).closest('tr').data('key');
$(updateModal).modal('show');
$.ajax({
type: "POST",
url: "/product/load-form",
dataType: "json",
cache: false,
data: {
"wbId": wbId
},
success: function (response)
{
if (response.success)
{
$(updateModal_content).html(response.render);
}
else
{
console.log(response);
}
},
error: function (response)
{
console.log(response);
}
});
e.preventDefault();
});
Js - submit-form
$(document).on('submit', updateModal_form, function (e)
{
e.preventDefault();
let formData = $(this).serializeArray();
$.ajax({
type: "POST",
url: $(this).attr('action'),
dataType: "json",
cache: false,
data: formData,
success: function (response)
{
console.log(response);
},
error: function (response)
{
console.log(response);
}
});
});
The validation event does not fire at all. Not when changing the data, nor when submitting the form. If incorrect data is entered, the request is sent to ajax-update and the server returns an empty response (because validation was not passed). How to make ajax data saving and ajax validation work together?
*I want to solve this problem without using pjax.
** Everything works correctly if you don't load the form via ajax. Apparently the problem is here.
Thx to Michal Hynčica. I just needed to use the method renderAjax() instead of renderPartial() when I render the form.
How can I use custom error messages in a json response? I'm using Ajax to validate a login form in frontend and I've already manage how to display the Validator errors, but I can't figure out how I can retrieve a custom error message.
This is the controller:
public function LoginValid(Request $request){
$validator = Validator::make($request->all(), [
'email' => ['required', 'string', 'email' ],
'password' => ['required', 'string', 'max:255'],
]);
if($validator->passes()){
$user = User::where('email', $request->email)->first();
if ($user &&
Hash::check($request->password, $user->password)) {
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard');
}else{
return response()->json('should be any custom message here');
}
}
}else{
return response()->json(['error'=>$validator->errors()->all()]);
}
}
And here's the Ajax:
$(document).ready(function() {
$("#btn-login").click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("input[name='email']").val();
var password = $("input[name='password']").val();
$.ajax({
url: "{{ route('login-valid') }}",
type: 'POST',
data: { _token: _token, email: email, password:password },
success: function(data) {
if ($.isEmptyObject(data.error)) {
window.location.href = 'dashboard';
} else {
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function(key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
});
you can customize validation messages in this way. I am using your code for an example.
$validator = Validator::make($request->all(), [
'email' => ['required', 'string', 'email' ],
'password' => ['required', 'string', 'max:255'],
], [
'email.required' => 'email is required',
'email.string' => 'email should be valid',
'email.email' => 'email should be in proper format'
.
.
.
.
and so on
]);
above code will overwrite the laravel default messages.
I have a form it works fine if i fill all fields, but if i don't fill attachment field it returns error says: The attachment must be a file of type: image/jpeg, image/png. while my attachment is nullable in back-end validator.
code
backend
public function sendEmail(Request $request) {
$this->validate($request, array(
'body' => 'required',
'subject' => 'required',
'receivers' => 'required',
'project_id' => 'required',
'attachment' => 'nullable|mimetypes:image/jpeg,image/png|max:2048',
));
if ($request->hasFile('attachment')) {
$request->validate([
'attachment' => 'nullable|mimetypes:image/jpeg,image/png|max:2048',
]);
$image = $request->file('attachment');
$filename = 'attachment-' . str_random(10) . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/'. $filename);
// $request->file('photo')->move(public_path('images') . $filename);
$request->file('attachment')->storeAs('attachment', $filename);
$attachment = $filename;
} else {
$attachment = null;
}
//rest of function
}
Ajax
$('body').on('click','.sendMailNowSubmit',function(e) {
e.preventDefault();
$(this).text('Please wait ...');
var formData = new FormData();
formData.append('body', $('#messageBody').val());
formData.append('subject', $('#messageSubject').val());
formData.append('receivers', $('#receivers').val());
formData.append('project_id', $(this).data('id'));
formData.append('attachment', $('input[type=file]')[0].files[0]);
$.ajax({
type:'POST',
url:'{{route('sendEmail')}}',
data: formData,
async: false,
cache: false,
contentType: false,
dataType: 'JSON',
enctype: 'multipart/form-data',
processData: false,
success:function(data){
$(".sendMailNow").attr("disabled", false);
document.getElementById("sendMailForm").reset();
$(".Mailmessage").append('<div class="alert alert-success fade in">'+data.success+'</div>').hide(4000);
$(".sendMailModal").modal('hide');
$(".sendMailNowSubmit").val("Done!");
$(".sendMailNowSubmit").text('Submit');
},
error: function(data){
$(".sendMailNow").attr("disabled", false);
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger alert-dismissible">×<ul>';
$.each(errors.errors,function (k,v) {
errorsHtml += '<li>'+ v + '</li>';
});
errorsHtml += '</ul></di>';
$( '.Mailmessage' ).html( errorsHtml );
$(".sendMailNowSubmit").text('Re-Submit');
}
});
});
Any idea?
Try this code for validation
$rules = [
'body' => 'required',
'subject' => 'required',
'receivers' => 'required',
'project_id' => 'required'
];
if ($request->hasFile('attachment')) {
$rules['attachment'] = 'mimetypes:image/jpeg,image/png|max:2048';
}
$this->validate($request, $rules);
I'm trying to login the user automatically after registration. From what I found from other answers, something like this should work, but it's not.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Auth::loginUsingId($user->id);
}
It's adding the new user, but not logging in. It is also redirecting to the proper page. Its also using ajax to register the user
$.ajax({
url: "userregister",
data: {_token:_token,useremail:useremail,userpassword:userpassword},
type: 'POST',
beforeSend: function () {
$("#showloadinsignup").html('<img src="'+site_url+'/public/images/loading.gif">');
},
success: function (result) {
if(result == "useraddsucess"){
$("#showloadinsignup").html('');
$("#emailerror").html('');
$("#success").html("<div class='alert alert-success fade in'><a href='#' class='close' data-dismiss='alert'>×</a><strong>Success!</strong> User Registered.</div>");
$("html, body").animate({ scrollTop: 0 }, "slow");
formid.reset();
}
when i try to submit a form with Ajax,i get this Error,MethodNotAllowedHttpException No message.
i guess problem is in routing, but when i tested without Ajax it works fine
here is my Ajax code:
$.ajax({
method: 'POST',
url: "{{ route('submitProfile') }}",
dataType: 'json',
data: {_token: CSRF_TOKEN, firstName:firstName, lastName:lastName, email:email, mobile:mobile},
success: function( data ) {
console.log(data);
}
});
my route is:
Route::get('/edit/profile',[
'uses' => 'UserController#getEditProfile',
'as' => 'editProfile'
]);
Route::post('/ajax/edit/profile',[
'uses' => 'UserController#postEditProfile',
'as' => 'submitProfile'
]);
and in my controller i have this functions:
public function postEditProfile(Request $request)
{
$this->validate($request,[
'firstName' => 'required',
'lastName' => 'required',
'email' => 'required|email',
'mobile' => 'required',
]);
$user = \Auth::user();
$user->firstName = $request['firstName'];
$user->lastName = $request['lastName'];
$user->email = $request['email'];
$user->mobile = $request['mobile'];
$user->save();
return response()->json([
'status' => 'its done!'
]);
}
thank you.
Can you try this for your route
Route::post('/ajax/edit/profile',[
'uses' => 'UserController#postEditProfile'
])->name('submitProfile');