I have this form in a page:
<div class="card-block">
{!! Form::open(array( 'autocomplete' => 'off', 'id' => 'AddModel', 'url' => 'model/useradd', 'files' => true)) !!}
<div class="form-group">
<label for="picture">Picture</label>
#if( (new Jenssegers\Agent\Agent)->isMobile() )
{!! Form::file('image', ['id' => 'modelpic', 'accept' => 'image/*', 'capture' => 'camera']) !!}
#else
{!! Form::file('image', ['id' => 'modelpic']) !!}
#endif
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show preview of the image through JS */
<div class="form-group">
{!! Form::submit('Submit', array('id' => 'AddBtn', 'class' => 'btn btn-default' )) !!}
{!! Form::close() !!}
</div>
in my controller:
public function preview(Request $request)
{
dd($request->file('image'));
}
result of dumping = NULL
I don't understand what's the catch here. I have an identical form in another page that is working normally.
by validating request I get the error "image is required"
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png,gif|image|image_size:>=640'
]);
new info:
There must be a problem with the javascript because removing it the controller works normally:
this is the JS
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
solved, thanks #sagar
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
var postData = new FormData($("#AddModel")[0]);
$.ajax({
type:'POST',
url:form.prop('action'),
processData: false,
contentType: false,
data : postData,
success:function(data){
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
To upload image using ajax:
Do it like:
You can upload the file using ajax like this.
In your form tag use attribute enctype and form html will be like below:
<form enctype="multipart/form-data" id="modal_form_id" method="POST" >
<input type="file" name="documents">
</form>
Js code:
var postData = new FormData($("#modal_form_id")[0]);
$.ajax({
type:'POST',
url:'your-post-url',
processData: false,
contentType: false,
data : postData,
success:function(data){
console.log("File Uploaded");
}
});
On your controller side you can do in the function like below to upload image.
if(Input::hasFile('documents')) {
$path = "directory where you wish to upload file";
$file_name= Input::file('documents');
$original_file_name = $file_name->getClientOriginalName();
$extension = $file_name->getClientOriginalExtension();
$fileWithoutExt = str_replace(".","",basename($original_file_name, $extension));
$updated_fileName = $fileWithoutExt."_".rand(0,99).".".$extension;
$uploaded = $file_name->move($path, $updated_fileName);
echo $updated_fileName;
}
More details :
File upload through a modal using Ajax
This code checks if request has a file if yes then names it and then moves the files to a folder in public dir.
if($request->hasFile('modelpic')) {
$file = Input::file('modelpic');
//get file extension
$name = 'image'.$file->getClientOriginalExtension();
//move file to public/images dir
$file->move(public_path().'/images/', $name);
}
Images are submitted with multiple part request due to size use (Multipart-form-data) in form tag.
Like this,
<div class="card-block">
{!! Form::open(array( 'autocomplete' => 'off', 'id' => 'AddModel', 'url' => 'model/useradd', 'files' => true,'enctype' => 'multipart/form-data')) !!}
<div class="form-group">
<label for="picture">Picture</label>
#if( (new Jenssegers\Agent\Agent)->isMobile() )
{!! Form::file('image', ['id' => 'modelpic', 'accept' => 'image/*', 'capture' => 'camera']) !!}
#else
{!! Form::file('image', ['id' => 'modelpic']) !!}
#endif
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show preview of the image through JS */
<div class="form-group">
{!! Form::submit('Submit', array('id' => 'AddBtn', 'class' => 'btn btn-default' )) !!}
{!! Form::close() !!}
</div>
Related
This is the view :
{{ Form::open([
'url' => '/contacts/create',
'files' => true
])}}
<div class="row">
<div class="collapse" id="collapseExample">
<div class="col-md-9">
{{ Form::label('group', 'group name')}}
{{ Form::text('group', null, [
'placeholder' => 'Enter group name here',
'class' => 'form-control'
])}}
</div>
<div class="col-md-3">
<button id="add-new-btn" class="btn btn-success"><i class="pe-7s-add-user"></i> Add</button>
</div>
</div>
</div>
{{ Form::close() }}
in my that view i have this script
$("#add-new-btn").click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var newGroup = $('#group');
$.ajax({
url: "/groups/autocomplete",
method: "post",
data: {
name: $("#group").val(),
_token: $("input[name=_token]").val()
},
success: function(response) {
console.log(response);
},
error: function(xhr) {
var errors = xhr.responseJSON;
var error = errors.name[0];
if(error) {
newGroup.addClass('has-error');
var inputGroup = newGroup.closest('.col-md-9');
inputGroup.next('text-danger').remove();
inputGroup
.find('input')
.after('<p class="text-danger">' + error + '</p>');
}
}
});
});
and in store method of GroupsController i have a simple Validator that may returns these 2 values:
1.The name field is required
2.The name has already been taken
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique:groups'
]);
}
Now the problem is this :
Every time i try to submit the form, the browser returns this error "errors.name is undefined" in console.
where is the problem?
i had a mistake for accessing property of object, jsonData.errors
var data = xhr.responseText;
var jsonData = JSON.parse(data);
var msg = jsonData.errors.name[0];
console.log(msg);
or
var jsonData = xhr.responseJSON;
var msg = jsonData.errors.name[0];
console.log(msg);
I'm using resource controller , when i submit form through ajax , it is showing method not allowed exception.
View
{!! Form::open(array('route' => 'product.store','class' => 'form-horizontal','id' => 'productform','name' => 'productform','files' => true)) !!}
{!! csrf_field() !!}
<div class="form-group" style="padding-top: 20px">
<label for="productName" class="col-sm-3 control-label">Product name</label>
<div class="col-sm-9">
{!! Form::text('productName',null, array('id'=> 'productName','class'=>'form-control','placeholder'=>'Product name'))!!}
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
{!! Form::submit('Save', array('class' => 'btn btn-primary btn-block')) !!}
</div>
</div>
{!! Form::close() !!}
AJAX
$("#productform").submit(function () {
var token = $('[name=_token]').val();
$.ajax({
type: 'POST',
url: 'product/store',
data: {
id: '4',
_token: token,
},
success: function (data) {
alert('success');
return false;
}
})
return false;
});
routes.php
Route::resource('product', 'ProductController');
What is the problem here...Any help is much appreciated.
in jquery
var BASEURL = $("#baseURL").val()
in html
<input type="hidden" id="baseURL" value="{{ url('') }}" >
when you try to store data in laravel your URL must be.
url: 'product',
try to go on your CMD and type:
php artisan route:list
and check the URI of product.store Name then that will be you url in your AJAX.
in AJAX
try to set url in AJAX to be route
$("#productform").submit(function () {
var token = $('[name=_token]').val();
$.ajax({
type: 'POST',
url: '{{ route("product.store") }}',
data: {
id: '4',
_token: token,
},
success: function (data) {
alert('success');
return false;
}
});
return false;
});
I'm tryin to use ajax to login to my web application, but when i submit the login form i get a blank page with json responses, for example on success login i get:
{"success":true}
On wrong credentials i get:
{"fail":true,"errors":"Email or password is incorrect"}
And on wrong email or password i get(validation error):
{"fail":true,"errors":{"email":["The email field is required."],"password":["The password field is required."]}}
My js file contains this piece of code:
$('#loginForm').submit('click',function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr("action"),
dataType: 'json',
data: formData,
success: function (data) {
window.location.replace("localhost:8000");
},
error: function (data) {
$.each(data.errors, function(index,value) {
var errorDiv = '#'+index+'_error';
$(errorDiv).html(value);
});
}
});
});
In my controller i have the login function:
public function login(Request $request){
try{
$validate = Validator::make($request->all(),[
'email' => 'required|max:320',
'password' => 'required|max:150',
'remember_me' => 'nullable|accepted'
]);
if($validate->fails()){
return response()->json(array(
'fail' => true,
'errors' => $validate->getMessageBag()->toArray()
));
}
$rememberMe = $request->remember_me ? true : false;
if(Sentinel::authenticate(['username'=>$request->email, 'password' => $request->password], $rememberMe)){
return response()->json(array(
'success' => true
));
}
elseif(Sentinel::authenticate(['email'=>$request->email, 'password' => $request->password], $rememberMe)){
return response()->json(array(
'success' => true
));
}
else{
return response()->json(array(
'fail' => true,
'errors' => 'Email or password is incorrect'
));
}
}
catch(ThrottlingException $e) {
$delay = $e->getDelay();
return redirect('/')->with('error',"After too many login attempts\n you've banned for $delay seconds!");
}
catch(NotActivatedException $e) {
return redirect('/')->with('error','Your account is not activated!');
}
catch(Exception $e){
return redirect('/')->with('error',$e->getMessage());
}
}
Form:
{{ FORM::open(['url' => 'loginua','id'=>'loginForm']) }}
<div class="input-container">
{{ FORM::text('email', null, ['placeholder' => 'E-mail or Username','id'=>'email', 'autofocus' => 'autofocus','required' => 'required']) }}
<i class="fa fa-envelope-o"></i>
<div id="#email_error"></div>
</div>
<div class="input-container">
{{ FORM::password('password', ['placeholder' => 'Password','id' => 'password', 'required' => 'required']) }}
<i class="fa fa-unlock"></i>
<div id="#email_error"></div>
</div>
<div class="input-container">
<label>
<span class="radio">
{{ FORM::checkbox('remember_me')}}
<span class="radio-value" aria-hidden="true"></span>
</span>
<span>Remember me</span>
</label>
</div>
<div class="input-container">
{{ FORM::submit('Sign in',['class' => 'btn-style', 'name' => 'sign_in','id'=>'sign_in']) }}
</div>
<div class="user-box-footer">
<p>Dont have account?<br>Sign up as User</p>
<p>Lost password?</p>
<p id="0_error"></p>
</div>
{{ FORM::close() }}
Route:
Route::post('loginua', 'PagesController#login');
I don't know why the jquery on success or fail isn't triggered. Thanks in advance!
Use
$('#loginForm').on('submit',function(e){
instead of
$('#loginForm').submit('click',function(e){
The problem were with the meta tag at the view file, i had to add this line of code to correspond to the ajaxSetup:
<meta name="csrf-token" content="{{csrf_token()}}"/>
Thanks everyone for tips.
when i try to upload my file with ajax, the $file is empty.
I tried with:
$file = Input::file('image');
$file= $request->file('image');
jQuery:
$(document).on('submit', '#update_form', function(e){
e.preventDefault(e);
$.ajax({
type: "POST",
url: '{{route('admin/users/update')}}',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('.error').fadeOut();
success(data);
load_data('{{route('admin/users/edit')}}', '{{ $user->id }}', '{{ $user->part }}');
},
error: function (data) {
$('.success').fadeOut();
errors(data);
}
})
});
Controller:
public function updateUser(Request $request){
//$file = Input::file('image');
$file= $request->file('image');
return \Response::json( $file );
}
Route:
Route::post('admin/users/update', ['as' => 'admin/users/update', 'uses' => 'admin\UserController#updateUser']);
Form:
{!! Form::model($user, ['id' => 'update_form', 'files' => true]) !!}
<div class="col-md-12">
<div class="form-group">
{{ Form::label(trans('User image')) }}
{!! Form::file('image', null,['class' => 'form-control', 'placeholder' => trans('Image')]) !!}
</div>
{{ Form::hidden('id') }}
{{ Form::hidden('part', app('request')->input('part')) }}
{!! Form::submit(trans('Save changes'), ['class' => 'pull-right btn btn-success submit', 'id' => 'submit' ]) !!}
</div>
{!! Form::close() !!}
Repsonse is empty or: {}
response image:
https://gyazo.com/04e431f16237dfada40c864df96ad412
Thank you!
param is your server method parameters
FormData fd =new FormData();
fd.append('param',$('input[type=file]').files[0]);
Laravel 6.x Ah finally nailed it down, for me the way its worked is first i have get the form by it's form id using jQuery then create a new FormData instance passing form through the constructor then if you need anything pass to server side as key value pair use append function.
<form id="form_id" enctype="multipart/form-data">
<div class="from-group">
<label for="title">App name:</label>
<input type="text" name="title" id ="title_id" class="form-control" placeholder="App name"><br>
</div>
<br>
<div class="form-group">
<input type="file" id="image" name="cover_image" autocomplete="off" class="form-control" />
</div>
<button type="button" onclick="WebApp.CategoryController.onClickAppSubmitButton()" class="btn btn-primary">Submit </button>
</form>
var form = $("#form_id")[0];
var formData = new FormData(form);
formData.append('parent_id','0');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: url_app_post,
method: "POST",
contentType: false,
processData: false,
data: formData,
success: function (result) {
var data_array = $.parseJSON(result);
if (data_array.status == "200") {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-success", data_array.message);
} else {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger", data_array.message);
}
$(messageView).html(messageHtml);
},
error: function (jqXHR, exception) {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger",
WebApp.CategoryController.getjqXHRmessage(jqXHR, exception));
$(messageView).html(messageHtml);
}
})
function storeCategory(Request $request, $type){
try{
$fileNameToStore='no_image.jpg';
if($request->hasFile('cover_image')){
$fileNameWithExt = $request->file('cover_image')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('cover_image')->getClientOriginalExtension();
$fileNameToStore=$fileName.'_'.time().'.'.$extension;
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
}
$cat = new Category();
$cat->title = $request->title;
$cat->parent_id = $request->parent_id;
$cat->cover_image=$fileNameToStore;
$cat->user_id=auth()->user()->id;
$cat->save();
return json_encode(array("message"=>"This ".$type." successfully added", "status" => "200"));
}catch(Exception $e){
return json_encode(array("message"=>$type." failed to insert: ".$e->getMessage(), "status" => "403"));
}
}
Jquery Ajax
the ajax request
$.ajax({
type: 'POST',
url: 'Enviar_Solicitud',
data: {
'nombres': $('input[name=ModTextNombres]').val(),
'email': $('input[name=ModTextEmail]').val(),
'categoria': $('select[name=ModSelctCategoria]').val(),
'descripcion': $('textarea[name=ModTextAreaDescripcion]').val(),
'referencia': $('input[name=ModFilArchReferencia]').val()
},
cache: false,
success: function (data) {
if (data.Success == true) {
toastr.success(data.Message);
}
},
error: function (jqXhr) {
if (jqXhr.status === 422) {
var errors = jqXhr.responseJSON;
errorsHtml = '<ul>';
$.each(errors , function(key, value) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul>';
toastr.error(errorsHtml);
}
}
});
Form Blade
the form blade whith the correct files => true
<div class="modal-body">
{!! Form::open(array("class" => "form-horizontal", "name" => "FormEnviarPresupuesto", "role" => "form", "files" => true, "data-toggle" => "validator")) !!}
<div class="form-group">
{!! Form::label("LablNombres", "Nombres", array("class" => "col-md-2 control-label")) !!}
<div class="col-lg-8">
{!! Form::text("ModTextNombres", null, array("class" => "form-control input-md", "placeholder" => "Nombres", "pattern" => "[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+", "required" => "")) !!}
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
{!! Form::label("LablEmail", "Email", array("class" => "col-md-2 control-label")) !!}
<div class="col-md-8">
{!! Form::email("ModTextEmail", null, array("class" => "form-control input-md", "placeholder" => "ej#dominio.com", "required" => "")) !!}
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
{!! Form::label("LablCategoria", "Categoría", array("class" => "col-md-2 control-label")) !!}
<div class="col-lg-8">
{!! Form::select("ModSelctCategoria", array("1" => "Nuestro Software", "2" => "Sistema Personalizado", "3" => "Web Auto-Administrable", "4" => "CMS", "5" => "Mantenimiento"), null, array("class" => "form-control", "placeholder" => "Seleccione...")) !!}
</div>
</div>
<div class="form-group">
{!! Form::label("LablDescripcion", "Descripción", array("class" => "col-md-2 control-label")) !!}
<div class="col-md-8">
{!! Form::textarea("ModTextAreaDescripcion", null, array("class" => "form-control", "rows" => "6", "required" => "")) !!}
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
{!! Form::label("LablArchReferencia", "Referencia", array("class" => "col-md-2 control-label")) !!}
<div>
{!! Form::file("ModFilArchReferencia", null, array("class" => "input-file")) !!}
</div>
</div>
<div class="form-group text-center">
{!! Form::button("<i class='fa fa-check fa-lg'></i> Enviar Solicitud", array("class" => "btn btn-lg btn-success", "name" => "BtnEnviarSolicitud", "type" => "submit")) !!}
</div>
{!! Form::close() !!}
</div>
Controller
the controller. in laravel 5.0 this work but in this version 5.2 not working because $request->file("referencia") return null
namespace App\Http\Controllers;
use Request;
use App\SolicitudModel;
use App\Http\Requests\SolicitudFormRequest;
class SolicitudController extends Controller
{
public function GuardarSolicitud (SolicitudFormRequest $request)
{
if (Request::ajax())
{
$_solicitud = new SolicitudModel;
$_solicitud->nombres = $request->get("nombres");
$_solicitud->email = $request->get("email");
$_solicitud->categoria = $request->get("categoria");
$_solicitud->descripcion = $request->get('descripcion');
$_solicitud->referencia = $request->file("referencia")->getClientOriginalName();
$name = $request->file("referencia")->getClientOriginalName();
$request->file("referencia")->getClientOriginalExtension();
$request->file("referencia")->move(base_path() . '/public', $name);
$_solicitud->save();
return response()->json(["Success" => true]);
}
}
}
Files cannot be serialized as a normal post request, they must be sent using multipart/form-data enctype, so in the form tag you have to place:
{!! Form::open(array("class" => "form-horizontal", "name" => "FormEnviarPresupuesto", "role" => "form", "files" => true, "data-toggle" => "validator", "enctype" => "multipart/form-data")) !!}
And pass FormData Object to Jquery Ajax function:
var formData = new FormData($('form')[0]); //select your form
$.ajax({
type: 'POST',
url: 'Enviar_Solicitud',
data: formData, //pass the formdata object
cache: false,
contentType: false, //tell jquery to avoid some checks
processData: false,
success: function (data) {
if (data.Success == true) {
toastr.success(data.Message);
}
},
error: function (jqXhr) {
if (jqXhr.status === 422) {
var errors = jqXhr.responseJSON;
errorsHtml = '<ul>';
$.each(errors , function(key, value) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul>';
toastr.error(errorsHtml);
}
}
});
I wrote this code for Laravel 6, anyway you can use html and js codes for any platform, if you are using laravel framework first you have to run a command by using terminal/command line to create a folder in your project public directory named 'storage' php artisan storage:link
html:
<form id="form_id" enctype="multipart/form-data">
<div class="from-group">
<label for="title">App name:</label>
<input type="text" name="title" id ="title_id" class="form-control" placeholder="App name"><br>
</div>
<br>
<div class="form-group">
<input type="file" id="image" name="cover_image" autocomplete="off" class="form-control" />
</div>
<button type="button" onclick="WebApp.CategoryController.onClickAppSubmitButton()" class="btn btn-primary">Submit </button>
</form>
js:
WebApp.CategoryController.onClickAppSubmitButton = function (){
var title = document.getElementById("title").value;
var messageView = $('.messages');
var messageHtml = "";
if (title == null || title == "") {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger", "Title should not empty");
$(messageView).html(messageHtml);
return;
}
var form = $("#form_id")[0];
var formData = new FormData(form);
formData.append('parent_id','0');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: url_app_post,
method: "POST",
contentType: false,
processData: false,
data: formData,
success: function (result) {
var data_array = $.parseJSON(result);
if (data_array.status == "200") {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-success", data_array.message);
} else {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger", data_array.message);
}
$(messageView).html(messageHtml);
},
error: function (jqXHR, exception) {
messageHtml += WebApp.CategoryController.getAlertMessage("alert-danger",
WebApp.CategoryController.getjqXHRmessage(jqXHR, exception));
$(messageView).html(messageHtml);
}
})
}
Controller:
public function storecat(Request $request){
if($this->checkforExist($request) !== null){
$output = array("message"=>"This category name already exist", "status" => "403");
return json_encode($output);
}
echo $this->storeCategory($request, "Category");
}
function checkforExist(Request $request){
return DB:: table('categories')
->where('title',$request->title)
->get()->first();
}
function storeCategory(Request $request, $type){
try{
$fileNameToStore='no_image.jpg';
if($request->hasFile('cover_image')){
$fileNameWithExt = $request->file('cover_image')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('cover_image')->getClientOriginalExtension();
$fileNameToStore=$fileName.'_'.time().'.'.$extension;
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
}
$cat = new Category();
$cat->title = $request->title;
$cat->parent_id = $request->parent_id;
$cat->cover_image=$fileNameToStore;
$cat->user_id=auth()->user()->id;
$cat->save();
return json_encode(array("message"=>"The ".$type." successfully added", "status" => "200"));
}catch(Exception $e){
return json_encode(array("message"=>$type." failed to insert: ".$e->getMessage(), "status" => "403"));
}
}
Finally pulling image from storage:
<td><img width="50" height="50" src="/storage/cover_images/{{$cat->cover_image}}"></td>