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
Related
i am a begineer of laravel and ajax i can do the system well in core php. i just converted to laravel.
i creating simple crud using laravel with ajax but i don't know how call the path through ajax request. what i tried so fat i attached below.pls give me the solution for it.
Screen shot of folder structure
this is view part. i name it
list.blade.php
div class="row">
<div class="col-sm-4">
<form class="card" id="frmProject">
<div class="form-group" align="left">
<label class="form-label">First name</label>
<input type="text" class="form-control" placeholder="first_name" id="first_name" name="first_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Last name</label>
<input type="text" class="form-control" placeholder="last_name" id="last_name" name="last_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Address</label>
<input type="text" class="form-control" placeholder="Address" id="address" name="address" size="30px" required>
</div>
<div class="card" align="right">
<button type="button" id="save" class="btn btn-info" onclick="addProject()">Add</button>
</div>
</form>
</div>
Ajax Call
function addProject() {
if ($("#frmProject").valid())
{
var _url = '';
var _data = '';
var _method;
if (isNew == true) {
_url = '/student';
_data = $('#frmProject').serialize();
_method = 'POST';
}
else {
_url = '/student',
_data = $('#frmProject').serialize() + "&project_id=" + project_id;
_method = 'POST';
alert(project_id);
}
$.ajax({
type: _method,
url: _url,
dataType: 'JSON',
data: _data,
beforeSend: function () {
$('#save').prop('disabled', true);
$('#save').html('');
$('#save').append('<i class="fa fa-spinner fa-spin fa-1x fa-fw"></i>Saving</i>');
},
success: function (data) {
$('#frmProject')[0].reset();
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Add');
get_all();
var msg;
console.log(data);
if (isNew)
{
msg="Brand Created";
}
else{
msg="Brand Updated";
}
$.alert({
title: 'Success!',
content: msg,
type: 'green',
boxWidth: '400px',
theme: 'light',
useBootstrap: false,
autoClose: 'ok|2000'
});
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
}
Student Controller
class StudentController extends Controller
{
public function index()
{
$data['students'] = Student::orderBy('id','desc')->paginate(5);
return view('student.list',$data);
}
public function create()
{
}
public function store(Request $request)
{
$student = new Student([
'first_name' => $request->post('first_name'),
'last_name'=> $request->post('lastname'),
'address'=> $request->post('address')
]);
]);
$student->save();
return Response::json($student);
}
routes
Route::get('/', [App\Http\Controllers\StudentController::class, 'index']);
Route::get('student', [App\Http\Controllers\StudentController::class, 'index']);
Route::post('student', [App\Http\Controllers\StudentController::class, 'store'])->name('student.store');
$(document).ready(function() {
$(".btn-submit").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("#email").val();
var pswd = $("#pwd").val();
var address = $("#address").val();
$.ajax({
url: "url",
type:'POST',
data: {_token:_token, email:email, pswd:pswd,address:address},
success: function(data) {
printMsg(data);
}
});
});
function printMsg (msg) {
if($.isEmptyObject(msg.error)){
console.log(msg.success);
$('.alert-block').css('display','block').append('<strong>'+msg.success+'</strong>');
}else{
$.each( msg.error, function( key, value ) {
$('.'+key+'_err').text(value);
});
}
}
});
Please use csrf token
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>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
i am creating the simple crud system using php ajax.in the crud system i add the image also.but when i fill the data and browse image and click add button record is not added in to the database.what i tried so far i attached below.no error shown on the console.i think might be the problem with jquery
send the form values and images data: {form_data: form_data,data: data},
Form Design
<form role="form" id="frmcompany" class="card" enctype="multipart/form-data">
<div align="left">
<h3>Company</h3>
</div>
<div align="left">
<label class="form-label">Company name</label>
<input type="text" class="form-control" placeholder="Patient No" id="cno" name="cno" size="30px" required>
</div>
<div align="left">
<label class="form-label">Country</label>
<input type="text" class="form-control" placeholder="Patient Name" id="coutry" name="coutry" size="30px" required>
</div>
<div align="left">
<label class="form-label">Currency</label>
<input type="text" class="form-control" placeholder="Phone" id="currency" name="currency" size="30px" required>
</div>
<div align="left">
<label class="form-label">Address</label>
<input type="text" class="form-control" placeholder="Address" id="address" name="address" size="30px" required>
</div>
<div align="left">
<div class="fileuploader fileuploader-theme-default">
<input type="hidden" name="fileuploader-list-files_" value="[]">
<input type="file" id="file" name="file" >
<div class="fileuploader-items">
<ul class="fileuploader-items-list"></ul>
</div>
</div>
</div>
</br>
<div align="right">
<button type="button" id="save" class="btn btn-info" onclick="addPatient()">Add</button>
<button type="button" id="clear" class="btn btn-warning" onclick="reset()">Reset</button>
</div>
</form>
jquery
function addPatient()
{
var upload_date = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', upload_date);
if($("#frmcompany").valid())
{
var url = '';
var data = '';
var method = '';
if(isNew == true)
{
url = 'php/add_patient.php';
data = $('#frmcompany').serialize() ;
method = 'POST';
}
$.ajax({
type : method,
url : url,
dataType : 'JSON',
cache: false,
contentType: false,
processData: false,
// data: data,
data: {form_data: form_data,data: data},
success:function(data)
{
if (isNew == true) {
alert("Company Addedd");
}
}
});
}
}
$('#file').fileuploader
({
limit: 1,
});
<div align="right">
<button type="button" id="save" class="btn btn-info" onclick="addPatient()">Add</button>
<button type="button" id="clear" class="btn btn-warning" onclick="reset()">Reset</button>
</div>
</form>
php code
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error)
{
die("connection failed" . $conn->connect_error);
}
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (0 < $_FILES['file']['error'])
{
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else
{
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
$stmt = $conn->prepare("insert into company(companyname,coutry,currency,address,image) VALUES (?,?,?,?,?)");
$stmt->bind_param("ssss",$companyname,$coutry,$currency,$address,$image);
$companyname = $_POST['cno'];
$coutry = $_POST['coutry'];
$currency = $_POST['currency'];
$address = $_POST['address'];
$image = $_FILES['file']['name'];
if($stmt->execute())
{
echo 1;
}
else
{
echo 0;
}
$stmt->close();
}
?>
You can't send a FormData object inside another object. All the POST parameters have to be in form_data.
function addPatient() {
if ($("#frmcompany").valid()) {
var url = '';
var data = '';
var method = '';
var form_data = new FormData(document.getElementById("frmcompany"));
var upload_date = $('#file').prop('files')[0];
form_data.append('file', upload_date);
if (isNew == true) {
url = 'php/add_patient.php';
data = $('#frmcompany').serialize();
method = 'POST';
}
$.ajax({
type: method,
url: url,
dataType: 'JSON',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
if (isNew == true) {
alert("Company Addedd");
}
}
});
}
}
function addPatient()
{
var upload_date = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', upload_date);
$.ajax({
url: 'php/add_patient.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
I am very new to Codeigniter. I m trying to create a form with some text input field along with two image upload field. The image uploading working fine but the text input field value are not coming. Can anyone please check my code and tell me where I am doing wrong Here is my Code:
Front End
<body>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data"">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
</script>
Controller Script is this
public function upload(){
$uploadData = "";
//Get the details
$productName = $_POST['product_name'];
$productCode = $this->input->post('product_code');
$productLink = $this->input->post('product_link');
$uploadData = $productName.','.$productCode.','.$productLink;
// setting cofig for image upload
$config['upload_path'] = 'uploads/profile/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
//$config['max_size'] = '1024'; //1 MB
// Get the profile image
$errorMsg = "";
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
$errorMsg = 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/profile/' . $_FILES['file']['name'])) {
$errorMsg = 'File already exists : uploads/profile/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
$errorMsg = $this->upload->display_errors();
} else {
$data = $this->upload->data();
$errorMsg = 'File successfully uploaded : uploads/profile/' . $_FILES['file']['name'];
$uploadData = $uploadData.','.$data['full_path'];
}
}
}
} else {
$errorMsg = 'Please choose a file';
}
//upload product screenshots
$config['upload_path'] = 'uploads/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
$link="";
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
$errorMsg = "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
$errorMsg = 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
$fileOriginalNmame = $_FILES["files"]["name"][$i];
$explodeFile = explode(".",$fileOriginalNmame);
$fileExtenstion = end($explodeFile);
$fileName = md5(md5(uniqid(rand(), true)).$_FILES["files"]["name"][$i]).'.'.$fileExtenstion;
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $fileName);
$link= $link.$fileName.',';
}
}
}
$uploadData =$uploadData .','. $link;
$errorMsg = $uploadData;
} else {
$errorMsg = 'Please choose at least one file';
}
echo $errorMsg;
}
And if anyone can improve my controller code that will be very helpful tnx.
FormData() Method:
As per our definition .FormData() submit a element data in a Key/Value form. The Form element must have a name attribute. One advantage of FormData() is now you can post a files on next page.
Simple Syntax:
var formData = new FormData(form);
Highlight Points:
This method does post files.
This method post complete form using Get & Post method including files.
var formData = new FormData();
formData.append('username', 'joe');
In addition you could add a key/value pair to this using FormData.append.
So your code broke because you need to pass value of input as key/pair format that you missed except for file.
Hope this will help you.
Please find solution describe below.
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
var inputs = $('#product-upload input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
formData.append(name, value);
});
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
Let me know if it not works for you.
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'];
}
}
}