why is my variable empty in my controller? - javascript

I am trying to make an upload function to upload multiple files. But everytime if i check in my controller where I send the data to the variable is empty. What am I doing wrong please help.
This is the form where i get the myfiles variable
<form name="Document" method="post" action enctype="multipart/form-data">
<div class="col-md-6">
<input type="file" id="documento" name="myFiles[]" required="required" multiple>
</div>
</form>
This is my script that i wrote that makes it an array and get the files based on the id documentto.
$(document).on('click', '#btnSaveUploadedFiles', function(e){
e.preventDefault();
var fileArray = [];
var fileBag = new FormData();
var files = document.getElementById('documento').files;
var arrayOfAllUploadedFiles = Array.from(files);
fileArray.forEach(file => fileBag.append("myFiles[]", file));
console.log(files);
$.ajax({
url: "{{ admin.generateUrl("uploadFiles") }}",
traditional: true,
data: {
"files": fileBag,
"uniqId": "{{ admin.uniqId }}",
"reservation": {{ admin.subject.id }}
},
processData: false,
contentType: false,
type: 'POST',
success: function () {
Swal.fire({
title: "test",
icon: "success",
confirmButtonText: "Sluiten"
});
},
});
});
This is my controller of symfony where i get the data from the {{ admin.generateurl.uploadfiles }}
public function uploadFilesAction(Request $request)
{
$reservationID = $request->get('reservation');
$files = $request->files;
dd($files);
$directory = "images/uploads/";
foreach ($files as $uploadedFile) {
// name the resulting file
$name = $reservationID;
$file = $uploadedFile->move($directory, $name);
// do something with the actual file
$this->doSomething($file);
}
// return data to the frontend
return new JsonResponse();
}
if you need more information ask me

Related

Image upload not working through ajax Laravel

Having a weird issue and I'm sure it's got something to do with the way my script is grabbing the value of the file input field.
I know the controller function works because I've been able to do it by manually submitting the form without using ajax.
I also know the ajax works in sending and receiving the request because I tested it by modifying it to parse a string back and forth which worked.
Additionally I can see that the script is grabbing the file as when I select a file, it shows the selected file in the console.
In my browser I'm getting a 500 error and in Laravel I'm only getting this:
Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function getClientOriginalExtension() on string in C:\123\app\Http\Controllers\MyController.php:156
I've tried updating the controller to use Request->logo instead with no success.
View:
<form enctype="multipart/form-data" class="form-horizontal" method="POST" action="{{ url('studio/uploadLogo') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('studioname') ? ' has-error' : '' }}">
<label for="imageInput" class="col-md-4 control-label">Logo</label>
<div class="col-md-6">
<input data-preview="#preview" name="logo" type="file" id="imageInput">
<img id="preview" src="" style="display: none"></img>
<input class="form-control" type="submit">
</div>
</div>
</form>
Script:
$('#imageInput').change(function (e) {
e.preventDefault();
var logo = $('#imageInput').val();
console.log(logo);
$.ajax({
type: "POST",
url: '/studio/uploadLogo',
data: {logo: logo},
success: function( data ) {
console.log(data);
}
});
});
Controller:
public function uploadLogo() {
$file = Input::file('logo')->getRealPath();
$photoName = str_random(20) . '.' . Input::file('logo')->getClientOriginalExtension();
Input::get('logo')->move(public_path('avatars'), $photoName);
$response = array(
'status' => 'success',
'data' => $photoName
);
return \Response::json($response);
}
Routes:
Route::post('/studio/uploadLogo', 'MyController#uploadLogo');
Route::get('/studio/uploadLogo', 'MyController#uploadLogo');
You just change a view js script to submit like below
$('.form-horizontal').submit(function(event){
event.preventDefault();
$.ajax({
type : 'POST',
url : "/studio/uploadLogo",
data : new FormData(this),
contentType:false,
processData:false,
})
.done(function(data,status){
//Your codes here
});
});
and
echo string response from controller like below
----------------
$file=$request->file('logo');
$uploaded_file_path='';
if($file!=null) {
$destinationPath = 'uploads';
$uploaded=$file->move($destinationPath,$file->getClientOriginalName());
$uploaded_file_path= $uploaded->getPathName();
$response = array(
'status' => 'success',
'data' => $uploaded_file_path
);
}else{
$response = array(
'status' => 'failed',
'data' => $uploaded_file_path
);
}
echo json_encode($response);
----------------
Try this in your controller
public function uploadLogo() {
$file = Input::file('logo')->getRealPath();
$photoName = str_random(20) . '.' . Input::file('logo')->getClientOriginalExtension();
Input::file('logo')->move(public_path('avatars'), $photoName);
$response = array(
'status' => 'success',
'data' => $photoName
);
return \Response::json($response);
}
You have given
Input::get('logo')->move(public_path('avatars'), $photoName);
Please change it to
Input::file('logo')->move(public_path('avatars'), $photoName);
and you should submit the form from ajax as like #jalin comment (https://stackoverflow.com/a/47906201/4049692)
Hope this should be the issue.
Thanks!.
Try adding processData: false, contentType: false in your script code
$('#imageInput').change(function (e) {
e.preventDefault();
var logo = $('#imageInput').val();
var form_data = new FormData();
form_data.append("logo",$("#imageInput")[0].files[0]);
console.log(logo);
$.ajax({
type: "POST",
url: '/studio/uploadLogo',
data: {form_data},
cache : false,
processData: false,
contentType: false
success: function( data ) {
console.log(data);
}
});
});
And try getting values in controller like $request->logo
Refer my answer here enter link description here
add data into FormData instance using 'this' and pass it to the data object in the ajax, also add contentType: false, processData: false
let formData = new FormData(this);
$.ajax({
type: "POST",
url: "{{ route('auth.societies.store') }}",
contentType: false,
processData: false,
});
then it will upload the form images

No data receive in Jquery from php json_encode

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.
My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.
car_detail.js
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
cache: false,
data: { car_rent_id: this.car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
car_detail.php
$car_rent_id = $_GET['car_rent_id'];
$query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour,
c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status,
r.pickup_location
FROM car_rent c
JOIN rental r ON c.car_rent_id=r.car_rent_id
WHERE c.car_rent_id = $car_rent_id");
$users = array();
while($r = mysql_fetch_array($query)){
$user = array(
"car_name" => $r['car_name'],
"car_type" => $r['car_type'],
"car_colour" => $r['car_colour'],
"plate_no" => $r['plate_no'],
"rate_car_hour" => $r['rate_car_hour'],
"rate_car_day" => $r['rate_car_day'],
"car_status" => $r['car_status'],
"pickup_location" => $r['pickup_location']
);
$users[] = $user;
// print_r($r);die;
}
print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]
car_detail.html
<label>ID:</label>
<input type="text" name="car_rent_id" id="car_rent_id"><br>
<label>Car Name:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
</div></br>
<label>Car Type:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
</div></br>
Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
car_rent_id.value = car_rent_id1; // where was this declared?
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
You can also use $.post(), post is just a shorthand for $.ajax()
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
console.log(users);
$('#car_name').val(users.car_name);
});
});
and in your PHP change
$car_rent_id = $_GET['car_rent_id'];
to
$car_rent_id = $_POST['car_rent_id'];
Here is a code skeleton using .done/.fail/.always
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$.ajax({
url: 'theurl',
dataType: 'json',
cache: false
}).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
}).always(function(data){
console.log(data);
});
});
</script>
I've adapted your code, so you can see the error, replace the ajax call with this one
<script>
$.ajax({
url: "theurl",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
},
error: function(data) {
console.log(data);
alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
}
});
</script>
A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

Upload file using MVC Razor from Ajax - Beginner logic issue

I am trying to upload a file using AJAX using C#-Razor. When I submit by clicking on the button the controller method is not being executed. How can I solve this ?
My code is as follows:
View
<div class="form-group">
#Html.TextBoxFor(model => model.IMG, new { #class = "control-label col-md-12", type = "file", placeholder = "Industry", name = "files[]", id="FileUpload" })
#Html.LabelFor(model => model.IMG, new { #class = "col-md-12 " })
#Html.ValidationMessageFor(model => model.IMG)
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Create" class="btn btn-default" id="UseShipAddr" />
</div>
</div>
AJAX
$('#UseShipAddr').click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("IMG", file);
alert("h" + file);
}
formData.append("name", "James");
formData.append("age", "1");
$.ajax({
url: "/Post/New",
type: "POST",
data: formData,
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});
Controller
[HttpPost]
//[ValidateAntiForgeryToken]
public async Task<ActionResult> New([Bind(Include="age","name","IMG")] POST rec)
{
if (ModelState.IsValid)
{
db.REC.Add(rec);
await db.SaveChangesAsync();
return RedirectToAction("My", "Post");
}
return View(rec);
}
Send the extra parameters in a querystring. Here is the AJAX code:
$.ajax({
url: "/Post/New?name=James&age=1",
type: "POST",
data: formData,
cache: false,
async: true,
contentType: false, // Not to set any content header
processData: false, // Not to process data
success: function (data) {
alert(data);
}
});
And your controller should be similar to below:
public async Task<ActionResult> New(string name, int age)
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = Path.GetFileName(file);
using (var fileStream = new MemoryStream())
{
stream.CopyTo(fileStream);
}
// File is in the memory stream, do whatever you need to do
}
}
}
catch (Exception)
{
// whatever you want to do
}
}
You are not specifying any form while creating the form in object in your form submit #UseShipAddr click event. please specify your form while creating object as:
var formData = new FormData($(#formID)[0]);
or create form constructor
var dataString = new FormData();
append file to the form
dataString.append("UploadedFile", selectedFile);
var form = $('#formID')[0];
var dataString = new FormData(form);
now send that string to the action in controller.
There are lots of problem in your request. First remove this then you'll be able to call that action of the controller.

Auto submit Form via ajax on selecting image

I have this form to change profile pic of user. I am trying to change the pic on clicking current pic and select from user filesystem
Form:
<form id="changeProfilePicForm" action="<?=base_url()?>user/change_profile_pic" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<div data-content="Click To update" class="image" id="profile-image">
<input id="profile-image-upload" class="hidden" name="image" type="file" accept="image/x-png, image/gif, image/jpeg">
<?if(strlen($user['image'])){?>
<img src="<?=base_url().'uploads/profile/'.$user['image']?>" class="img-circle" alt="user profile pic" height="125px" width="125px">
<?}else{?>
<img src="<?=base_url()?>includes/img/avtar.png" class="img-circle" alt="user profile pic" height="125px" width="125px">
<?}?>
<input type="submit" class="hidden">
</div>
</form>
Javascript:
$("#changeProfilePicForm").on('submit',(function(e){
e.preventDefault();
var $form = $( this );
$.ajax({
url: $form.attr( 'action' ),
type: "POST",
data: new FormData($form),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}));
document.getElementById('profile-image').onclick = function() {
document.getElementById('profile-image-upload').click();
};
document.getElementById('profile-image-upload').onchange = function(){
document.getElementById('changeProfilePicForm').submit();
};
PHP controller:
public function change_profile_pic()
{
$user_id = $this->session->user_id;
$image = $this->uploadimage();
if(strlen($image)){
$user_data['image'] = $image;
$updated = $this->user_model->update_user($user_id, $user_data);
$data['response'] = 1;
$data['image'] = $image;
// redirect(base_url()."user");
echo json_encode($data);
}else{
$data['response'] = 0;
$data['message'] = "error";
echo json_encode($data);
}
//redirect(base_url()."user");
}
Problem I am facing is, the form is not submitted via ajax. It is directory submitted as simple form. I can't figure out whats wrong with the code since image is being upload on simple form submission. Is there any problem with event binding or i am missing something here ?
When you call
document.getElementById('changeProfilePicForm').submit();
the submit event is not fired. Try
$('#changeProfilePicForm').trigger('submit');
Edit. Get rid of the form in html:
<input type="file" id="image">
js:
function handleUpload(event) {
var file = this.files[0];
if (!file) return;
var formData = new FormData();
formData.append('file', file);
return $.ajax({
type: 'POST',
url: '/images',
data: formData,
processData: false,
contentType: false,
//...
});
}
$('#image').on('change', handleUpload);
I believe FormData expects a native form element $form[0], not jQuery form element $form.
$("#changeProfilePicForm").submit(function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr('action'),
type: "POST",
data: new FormData($form[0]),
contentType: false,
cache: false,
processData: false,
success: function (data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}));

upload image using formdata ajax send to php

I newbie in this webpage area and I was try to upload image to my file by using ajax and send it to php. But I have done some coding here. Can some one correct me where I'am wrong ?
here is my form with file upload and a button
<form method="post" enctype="multipart/form-data" action="">
<input type="file" name="images" id="images" multiple="" />
<input type="submit" value="submit" id="harlo">
</form>
Once I click on button the file will send it here and receive the src and ajax to php file
but I guess is about getting source problem. Need some one correct it for me.
(function upload() {
var input2 = document.getElementById("harlo"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input2.addEventListener("click", function () {
var i = 0, len = $('input[type="file"]')[0].files;
for ( ; i < len.length; i++ ) {
file = len.files[i];
if (formdata) {
formdata.append("images", file);
}
}
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
}, false);
}());
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
?>
Use something like:
$("form").on("submit", function(
// Your ajax request goes here
$.ajax({
url: "upload.php",
type: "POST",
data: $("form").serialize(),
processData: false,
contentType: false,
success: function (res) {
$("#response").innerHTML = res;
}
});
return false;
));
But there seems to be a problem with sending files trough ajax anyway. Cause they're missed by the serialize() method because JS has no access to files content on users computer. So the form must be sent to the server to get the file data.
See here: https://stackoverflow.com/a/4545089/1652031

Categories

Resources