Ajax File Upload With Form Data Laravel 5.3 - php

i want to upload a profile image of a user to the server and i'm stuck at ajax upload of image
all my form data are posting to database including the image name but the file is not uploading to the server
my view is
//form
<form id="example-form" method="post" enctype="multipart/form-data">
{!! csrf_field() !!}
<div class="row">
<div class="col m12">
<div class="row">
<div class="input-field col m12 s12">
<input id="name" name="name" type="text" placeholder="Full Name" class="required validate">
</div>
<div class="input-field col s12">
<input id="email" name="email" type="email" placeholder="Email" class="required validate">
</div>
<div class="input-field col s12">
<input id="phone_number" name="phone_number" type="tel" placeholder="Phone Number" class="required validate">
</div>
<div class="input-field col m6 s12">
<input id="address" name="address_city_village" type="text" placeholder="Address City Village">
</div>
<div class="input-field col m6 s12">
<input id="state" name="address_state" type="text" placeholder="State">
</div>
<div class="input-field col s12">
<input id="password" name="password" type="password" placeholder="Password" class="required validate">
</div>
<div class="input-field col s12">
<input id="confirm" name="confirm" type="password" placeholder="Confirm Password" class="required validate">
</div>
<div class="file-field input-field col s12">
<div class="btn teal lighten-1">
<span>Image</span>
<input type="file" name="image">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="waves-effect waves-green btn blue">Submit</button>
</div>
</form>
//ajax
$(document).on("click", ".agent-add", function () {
var agent_id = $(this).data('id');
$('form').submit(function(event) {
event.preventDefault();
$.ajax
({
url: '{{ url('/agents') }}',
type: 'POST',
data: {
"_method": 'POST',
"name": $('input[name=name]').val(),
"email": $('input[name=email]').val(),
"phone_number": $('input[name=phone_number]').val(),
"address_city_village": $('input[name=address_city_village]').val(),
"address_state": $('input[name=address_state]').val(),
"image": $('input[name=image]').val(),
"password": $('input[name=password]').val()
},
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});
});
});
my controller is
public function store(Request $request)
{
if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
return $this->respondBadRequest('Phone Number Exists');
}
else
{
User::create($request->all());
return redirect('agents')->with('Success', 'Agent Added');
if($request->hasFile('image')) {
$file = $request->file('image');
//you also need to keep file extension as well
$name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
//using array instead of object
$image['filePath'] = $name;
$file->move(public_path().'/uploads/', $name);
}
}
}
i guess i'm missing something in ajax posting, but i couldn't figure it out
i dd($request->all());
the result is
array:9 [▼
"_token" => "heSkwHd8uSIotbqV1TxtAoG95frcRTATgeGL0aPM"
"name" => "fwe"
"email" => "sanjiarya2112#gmail.com"
"phone_number" => "4444422555"
"address_city_village" => "sgf"
"address_state" => "gfdgsdf"
"password" => "ffffff"
"confirm" => "ffffff"
"image" => UploadedFile {#208 ▼
-test: false
-originalName: "Screenshot (8).png"
-mimeType: "image/png"
-size: 135920
-error: 0
path: "C:\wamp\tmp"
filename: "php47F2.tmp"
basename: "php47F2.tmp"
pathname: "C:\wamp\tmp\php47F2.tmp"
extension: "tmp"
realPath: "C:\wamp\tmp\php47F2.tmp"
aTime: 2017-01-24 06:14:40
mTime: 2017-01-24 06:14:40
cTime: 2017-01-24 06:14:40
inode: 0
size: 135920
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\wamp\tmp\php47F2.tmp"
}
]
i checked the C:\wamp\tmp\php47F2.tmp enen there i din't find the image
looking forward for much needed help
thank you

Try using the FormData in ajax while you upload a file.
Just try this
$('form').submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '{{ url('/agents') }}',
type: 'POST',
data: formData,
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});
});
OR
You can try with this jQuery library
https://github.com/malsup/form
EDIT
public function store(Request $request)
{
if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
return $this->respondBadRequest('Phone Number Exists');
}
else
{
$user=User::create($request->all());
if($request->hasFile('image')) {
$file = $request->file('image');
//you also need to keep file extension as well
$name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
//using the array instead of object
$image['filePath'] = $name;
$file->move(public_path().'/uploads/', $name);
$user->image= public_path().'/uploads/'. $name;
$user->save();
}
return redirect('agents')->with('Success', 'Agent Added');
}
}

Try something like 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 : 'route_url',
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
}
});
});

Just me or does your <input type="file"> not have a "name" attribute? Therefore the server is not receive the file data from the post?
EDIT:
After you insert the record into the database, you then handle the file uploading - but you never then update the record with the files name.
*Just confirm that the file was uploaded.

I will explain using a simple example.
HTML:
<form id="header_image_frm" method="POST" action="">
<input type="file" name="header_image" id="header_image" value="Upload Header Image">
</form>
JS: (Properties of ajax called contentType, processData must)
<script>
$(document).ready(function() {
$('#header_image').change(function() {
let formData = new FormData($('#header_image_frm')[0]);
let file = $('input[type=file]')[0].files[0];
formData.append('file', file, file.name);
$.ajax({
url: '{{ url("/post/upload_header") }}',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: formData,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
});
</script>
Laravel / PHP:
public function upload(Request $request) {
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = public_path() . '/images/' . $filename;
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo '/images/' . $filename;
} else {
echo = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
}

Related

How to send an image alongside other fields to PHP?

I have a jQuery function that does the insert of an image with other fields to the database. Currently my function only inserts the image but does not insert the other form fields. I am using formData object and I don't understand how to append my fields together with the image file so I can pass it to the ajax request body.
Here is what I have tried so far:
// submit function
function Submit_highschool() {
jQuery(document).ready(function($) {
$("#highschool").submit(function(event) {
event.preventDefault();
$("#progress").html(
'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
var firstname_h = $("#firstname_h").val();
var middlename_h = $("#middlename_h").val();
formData.append(firstname_h, middlename_h);
$.ajax({
url: 'insertFunctions/insertHighSchool.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
alert(returndata);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
});
});
}
// html form
<form method="post" enctype="multipart/form-data" id="highschool">
<div class="card" id="highschool">
<div class="col-3">
<label for="firstname">First name *</label>
<input type="text" class="form-control" id="firstname_h" placeholder="First name" />
</div>
<div class="col-3">
<label for="middlename">Middle name *</label>
<input type="text" class="form-control" id="middlename_h" placeholder="Middle name" />
</div>
<div class="col-6">
<label for="grade11_h">Grade 11 Transcript (image) *</label>
<input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
</div>
<button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
</div>
</form>
The image name is succesfully inserted in the db and the image is uploaded to the required target location,However, the fields - firstname and middlename are not inserted and I don't understand how to append these properties to the formData.
How can I pass these fields to the formData please?
You can use the following approach for storing the data with image.
1.In PHP API write logic for Upload image to server using move_uploaded_file() & Insert image file name with server path in the MySQL database using PHP.
2.In JS/JQuery, Read all HTML element & create an object & POST it to the API using AJAX Call.
your JS code should be like this. Hope this will help you to fix the issue.
var RegObj = {
'Field1': $("#Field1").val(),
'Field2': $("#Field2").val(),
'logo': $("#company_logo").attr('src'),
}
console.log(RegObj);
$.ajax({
url: "API_PATH_HERE",
type: "POST",
data: JSON.stringify(RegObj),
headers: {
"Content-Type": "application/json"
},
dataType: 'text',
success: function (result) {
//
},
error: function (xhr, textStatus, errorThrown) {
}
});
Like #Professor Abronsius suggested in the comments section I only needed to add the "name" tag to the form elements and remove the append from my function thus, I have edited the function and the form as follows:
// since I have added the name tag to the form elements, there is now
// no need to use the append() thus, I have commented out the append
// lines.
function Submit_highschool() {
jQuery(document).ready(function($) {
$("#highschool").submit(function(event) {
event.preventDefault();
$("#progress").html(
'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
// var firstname_h = $("#firstname_h").val(); // removed this
// var middlename_h = $("#middlename_h").val(); // removed this
//formData.append(firstname_h, middlename_h); // removed this
$.ajax({
url: 'insertFunctions/insertHighSchool.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
alert(returndata);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
});
});
}
// added the "name" tag to the form elements
<form method="post" enctype="multipart/form-data" id="highschool">
<div class="card" id="highschool">
<div class="col-3">
<label for="firstname">First name *</label>
<input type="text" class="form-control" name="firstname_h" id="firstname_h" placeholder="First name" /> // added name="firstname_h"
</div>
<div class="col-3">
<label for="middlename">Middle name *</label>
<input type="text" class="form-control" name="middlename_h" id="middlename_h" placeholder="Middle name" /> // added name="middlename_h"
</div>
<div class="col-6">
<label for="grade11_h">Grade 11 Transcript (image) *</label>
<input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
</div>
<button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
</div>
</form>

Undefined index when trying to upload image ( with jquery validate and steps )

I'm using form steps with jquery steps and jquery validate. But when i try to upload image, it show "Undefined Index: picture". When i try without both of jquery, it works.
register.php
<form class="form-contact contact_form" id="register" enctype="multipart/form-data">
<input name="remarks" id="remarks" type="hidden" value="SMP">
<div class="row">
<h3> Profil </h3>
<section>
<div class="col-md-3">
<p class="katapen">NISN</p>
</div>
<div class="col-md-9">
<input class="form-control required number" name="nisn" id="nisn" type="text" placeholder='Please enter your NISN'>
</div>
<div class="col-md-3">
<p class="katapen">School Status</p>
</div>
<div class="col-md-4">
<div class="switch-wrap d-flex justify-content-between">
<div class="primary-radio">
<input type="radio" name="schoolstatus" value="A" id="primary-radio" required>
<label for="primary-radio"></label>
</div>
<p class="spasidrradio">A</p>
</div>
</div>
<div class="col-md-4">
<div class="switch-wrap d-flex justify-content-between">
<div class="primary-radio">
<input type="radio" name="schoolstatus" value="B" id="primary-radio">
<label for="primary-radio"></label>
</div>
<p class="spasidrradio">B</p>
</div>
</div>
</section>
<h3> Personal Data </h3>
<section>
<div class="col-md-3">
<p class="katapen">Full Name</p>
</div>
<div class="col-md-9">
<input class="form-control required" name="fullname" id="fullname" type="text" placeholder='Please enter your fullname' required>
<div class="col-md-3">
<p class="katapen">Picture</p>
</div>
<div class="col-md-9">
<input class="form-control" name="picture" id="picture" type="file">
</div>
</section>
test.js
var former = $("#register");
former.validate
({
errorPlacement: function errorPlacement(error, element)
{
element.before(error);
},
rules:
{
}
});
former.children("div").steps
({
headerTag: "h3",
bodyTag: "section",
transitionEffect: "slideLeft",
onStepChanging: function (event, currentIndex, newIndex)
{
former.validate().settings.ignore = ":disabled,:hidden";
return former.valid();
},
onFinishing: function (event, currentIndex)
{
former.validate().settings.ignore = ":disabled";
return former.valid();
},
onFinished: function (event, currentIndex)
{
studentregister();
}
});
function studentregister()
{
var remarks = document.getElementById('remarks');
$.ajax
({
type: "POST",
url : base_url + "register/" + remarks.value,
data: $('#register').serialize(),
dataType: 'json',
success: function(data)
{
if(data.log.status == '1')
{
swal
({
title: "",
type: "success",
text: data.log.ket,
confirmButtonClass: "btn-success",
confirmButtonText: "Con"
},function(){
});
}else{
swal
({
title: "",
type: "error",
text: data.log.ket,
confirmButtonClass: "btn-default",
confirmButtonText: "Back"
},function(){
});
}
$("#register")[0].reset();
},
error: function(ts)
{
alert(ts.responseText);
}
});
return false;
};
base_url + "register/" + remarks.value will be route to saveregister and remarks.value as uri2
This is my adm.php
public function saveregister()
{
$uri1 = $this->uri->segment(1);
$uri2 = $this->uri->segment(2);
$uri3 = $this->uri->segment(3);
$uri4 = $this->uri->segment(4);
//var post from json
$p = json_decode(file_get_contents('php://input'));
$_log = array();
if($uri2 == "SD")
{
}else if($uri2 == "SMP"){
$p = $this->input->post();
$folder = "./upload/register/";
$allowed_type = array("image/jpeg", "image/jpg", "image/png", "image/gif",
"audio/mpeg", "audio/mpg", "audio/mpeg3", "audio/mp3", "audio/x-wav", "audio/wave", "audio/wav","video/mp4", "application/octet-stream", "application/pdf", "application/doc");
$file_name = $_FILES['picture']['name'];
$file_type = $_FILES['picture']['type'];
$file_tmp = $_FILES['picture']['tmp_name'];
$file_error = $_FILES['picture']['error'];
$file_size = $_FILES['picture']['size'];
$ekstensi = explode("/", $file_type);
$time = date("Yhsms");
$filename= $this->db->escape($p['nisn'])."_".$time .".".$ekstensi[1];
#move_uploaded_file($file_tmp, $folder .$filename);
}else{
}
}
If you look at the jquery serialize() Documentation, it says the data from file select elements is not serialized. You could use FormData to send file input through ajax :
function studentregister()
{
var remarks = document.getElementById('remarks');
var form = $("#register")[0]; // use the form ID
var formData = new FormData(form);
$.ajax
({
type: "POST",
url : base_url + "register/" + remarks.value,
data: formData,
dataType: 'json',
contentType: false, // required
processData: false, // required
success: function(data)
{
if(data.log.status == '1')
{
swal
({
title: "",
type: "success",
text: data.log.ket,
confirmButtonClass: "btn-success",
confirmButtonText: "Con"
},function(){
});
}else{
swal
({
title: "",
type: "error",
text: data.log.ket,
confirmButtonClass: "btn-default",
confirmButtonText: "Back"
},function(){
});
}
$("#register")[0].reset();
},
error: function(ts)
{
alert(ts.responseText);
}
});
return false;
};

AJAX Form refreshing page when using move_uploaded_file()

I've built a simple form that posts data using jQuery AJAX to a PHP endpoint.
Everything works fine and the data is all being posted correctly.
The problem I am having is once the file is added to the input and submitted, the page refreshes. It doesn't refresh if I don't add the file, and doesn't refresh if I take the file input out altogether. Only when the file is successfully moved.
I need the page not to refresh, hence the use of AJAX in the first place.
Form:
<form id="form-send">
<div class="c-form-group grid-2">
<label for="first_name">First Name</label>
<input class="c-form-control" type="text" id="first_name" name="first_name" placeholder="Joe" value="Joe">
</div>
<div class="c-form-group grid-2">
<label for="file">Add File</label>
<input class="c-form-control c-form-control--file" type="file" id="file" name="file">
</div>
<div class="c-btn-group">
<button id="send" class="c-btn c-btn--primary" type="submit">Submit</button>
</div>
</form>
Ajax:
$("#form-send").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '/send-form.php',
cache: false,
processData: false,
contentType: false,
data: new FormData(this),
success: function(data) {
console.log(data);
},
error: function(response) {
console.log('An error ocurred.');
},
});
})
Endpoint:
<?php
$uploadDir = 'uploads/';
// If post
if (isset($_POST)) {
// Request Values
$firstname = $_REQUEST['firstname'];
$file = $_REQUEST['file'];
// Upload to folder
if(!empty($_FILES["file"]["name"])){
// File path config
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $uploadDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
echo "Success: File uploaded.";
} else {
echo "Error: Something went wrong.";
}
} else{
echo "Error: File is not the correct format.";
}
}
}
?>
As the ajax call is asynchronous, you have to prevent the form from submitting, and then when a result is returned, you check if it matches the condition and submit the form with the native submit handler, avoiding the preventDefault() in the jQuery event handler :
$("#form-send").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: '/send-form.php',
cache: false,
processData: false,
contentType: false,
data: new FormData(this),
success: function(data) {
console.log(data);
},
error: function(response) {
console.log('An error ocurred.');
},
});
});
You can remove the form tag that is responsible for refreshing the page. Else, you can change button to
<button id="send" class="c-btn c-btn--primary" type="button">Submit</button>
This is how I am able to achieve in one of my projects.Hope it helps
AJAX CALL:
var form_data = new FormData();
form_data.append('title',title);
form_data.append('body',body);
form_data.append('link',link);
$.ajax
({
url: 'blog_insert.php',
dataType: 'text',
cache : false,
contentType : false,
processData : false,
data: form_data,
type: 'post',
success: function(php_script_response)
{
$("#success-message").css('display','active').fadeIn();
var title = $('#title').val(' ');
var body = $('.nicEdit-main').html('');
//$('#sortpicture').prop(' ')[0];
var link = $('#link').val('');
}
});
HTML
Blog posted successfully
<div class="form-group">
<label for="exampleFormControlInput1">Blog Title</label>
<input type="text" class="form-control" required="" name="title" id="title" placeholder="Enter your blog title">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Write your blog body here</label>
<textarea class="form-control" name="body" id="body" ></textarea>
</div>
<div id="dropzoneFrom" class="dropzone">
<div class="dz-default dz-message">Test Upload</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Reference Link</label>
<input type="text" class="form-control" id="link" name="link" placeholder="Post a reference link">
</div>
<button type="submit" id="submit-all" class="btn btn-primary" name="submit" >Post</button>

image upload using ajax in Laravel

I have an user information form in my Laravel site and trying to upload image using Ajax.
Blade
<form id="edit_form" enctype="multipart/form-data">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
<div class="form-group">
<label>Image</label>
<input id="edit_form_image" type="file" class="form-control" name="user_image">
</div><!-- end form-group -->
<div class="form-group">
<label>Name</label>
<input id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
</div><!-- end form-group -->
<button type="button" id="edit_form_submit" class="btn btn-orange">Save Changes</button>
Ajax
$('#edit_form_submit').click(function(event) {
var fd = new FormData();
var edit_form_image = $('#edit_form_image')[0].files;
var edit_form_name = $('#edit_form_name').val();
var token = $('input[name=_token]').val();
fd.append( 'image', edit_form_image );
fd.append( 'name', edit_form_name );
fd.append( '_token', token );
$.ajax({
url:"{{ url('/profile-update') }}",
data: fd,
async:false,
type: 'POST',
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
But in my controller I can't get the image file.
controller
if (request()->hasFile('image'))
{
return "file present";
}
else{
return "file not present";
}
Though I upload an image controller always response that `file no present'.
Where is the error? Anybody Help please ?
why dont you name your input tags as you need to send in post method in :
<input name="image" id="edit_form_image" type="file" class="form-control">
<input name="name" id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
And,
$("#edit_form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url:"{{ url('/profile-update') }}",
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
This might works.

upload image with laravel using ajax

I have table user:
id (int)
firstname (string)
lastName (string)
email (string)
login (string)
password (string)
image (text)
I would like to insert image in my database using ajax jquery.
But at the given database level it does not insert the data with the image.
I try with this code but doesn't work.
Controller:
public function addUser(Request $request){
$user = new User();
$user->lastName = $request->lastName;
$user->firstName = $request->firstName;
$user->email = $request->email;
$user->login = $request->login;
$user->password = bcrypt($request->password);
if($request->has('image') ) {
$file_local = $request->file('image');
$extension = $request->file('image')->getClientOriginalExtension();
if($extension == 'jpg' || $extension == 'png' || $extension == 'jpeg'){
$name=$request->file('image')->getClientOriginalName();
$path = $file_local->storeAS('public/',$name);
$user->image = $name;
}
}
$user->save();
return response()->json($user);
}
View:
<form enctype="multipart/form-data">
<div class="form-group">
<input type="text" id="lastName" class="form-control" placeholder="last Name" required />
</div>
<div class="form-group">
<input type="text" id="firstName" class="form-control" placeholder="name" required />
</div>
<div class="form-group">
<input type="email" id="email" class="form-control" placeholder="Email" required/>
</div>
<div class="form-group">
<input type="text" id="login" class="form-control" placeholder="Login" required/>
</div>
<div class="form-group">
<input type="password" id="password" class="form-control" placeholder="password" required/>
</div>
<div class="form-group">
<input type="file" id="image" class="form-control" required />
</div>
</form>
ajax:
$(document).on('click', "#creer_utilisateur", function() {
var lastName= $('#lastName').val();
var firstName = $('#firstName').val();
var email = $('#email').val();
var login = $('#login').val();
var password = $('#password').val();
var image = $('#image').val();
success: function(data) {
$.ajax({
url: "{{action('UserController#addUser')}}",
method: 'POST',
data: {
lastName: lastName,
firstName: firstName,
email: email,
login: login,
password: password,
image: image
},
success: function(data) {
alert('success');
},
error: function(){
alert('failed');
}
});
}
});
});
You are actually saving the name of the image:
$name=$request->file('image')->getClientOriginalName();
...
$user->image = $name;
You said:
"But at the given database level it does not insert the data with the image."
And the type of the column is:
image (text)
So, I guess you don't want to store the name, right?
when you are using ajax to upload file you need to create form with File attribute. and Then append other values with that.
Something like this:
var formData = new FormData();
if ($('#images')[0].files.length > 0) {
for (var i = 0; i < $('#images')[0].files.length; i++)
formData.append('file[]', $('#images')[0].files[i]);
}
formData.append('lastName', $('#lastName').val());
second when you pass files with ajax make sure cache is false.
$.ajax({
type: 'POST',
dataType: "JSON",
url: jQuery('form').attr('action'),
xhr: function() {
myXhr = $.ajaxSettings.xhr();
return myXhr;
},
cache: false,
contentType: false,
processData: false
data: formData,
success: function(data) {
// Success
},
error: function(error) {
// error
},
});
Good luck
you can change an image text area like you can select an image: file then you can insert a file

Categories