Image not uploading without submit button - javascript

I am trying to upload mp3 file to server without using submit button i am using ajax but file not uploading to server.Where i am wrong here is my code
<script>
$(document).ready(function() {
$('#fileToUpload').change(function(){
var file_data = $('#fileToUpload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "modules/phone/newvoicemail.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
}
});
});
});
</script>
In newvoicemail.php i put following code
$src = $_FILES['file']['tmp_name'];
$file_name = $_FILES['fileToUpload']['name'];
$file_size =$_FILES['fileToUpload']['size'];
$file_tmp =$_FILES['fileToUpload']['tmp_name'];
$file_type=$_FILES['fileToUpload']['type'];
move_uploaded_file($file_tmp,"voicemail/".$file_name);
here is my html code
<form name="voicemailform" action="modules/phone/voicemail.php" method="POST" enctype="multipart/form-data" class="form-inline for-frm">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>

Since you are uploading using ajax, you do not need name,action,
method and enctype attributes on your HTML form tag. Same applies to name attribute of file input tag.
You need to add enctype: 'multipart/form-data', to $.ajax({...});
Since you are appending form data with param name file in JS as
form_data.append('file', file_data);, you should access it in php
as $_FILES['file'] and not $_FILES['fileToUpload']
HTML Code:
<form class="form-inline for-frm">
<input type="file" id="fileToUpload">
</form>
JS Code:
$('#fileToUpload').change(function () {
var file_data = $('#fileToUpload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "modules/phone/newvoicemail.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
console.log(data);
}
});
});
PHP Code: newvoicemail.php
<?php
$src = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
move_uploaded_file($src, "./voicemail/".$file_name);

Related

Data not sending to php JS/FormData/AJAX using PHP

I am trying to send a file to my DB together with text using this:
let formData = new FormData($('#image_form')[0]);
formData.append("message", $('#messageInput').val());
$(document).ready(function() {
$('#image_form').submit(function(e) {
e.preventDefault();
$.ajax({
url: "https://example.com/test.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData:false,
success: function(status) {
$('#result').append(status);
}
});
});
});
That's the DOM
<form id="image_form" enctype="multipart/form-data">
<input type="file" name="files[]" id="files[]" multiple >
<input type="submit" name="submit" is="submit" id="submit"/>
</form>
<input type="text" name="message" id="messageInput">
PHP:
<?php
$file = $_FILES['files'];
$message = $_POST['message'];
var_dump($_POST);
?>
The Image is received by php and can be display. But the Text is not.
Besides the Image, the php script outputs:
array(1) { ["submit"]=> string(6) "Submit" }
You need to assign formData inside the submit handler, so it gets the values after the user has submitted the form.
$(document).ready(function() {
$('#image_form').submit(function(e) {
e.preventDefault();
let formData = new FormData($('#image_form')[0]);
formData.append("message", $('#messageInput').val());
$.ajax({
url: "https://example.com/test.php",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(status) {
$('#result').append(status);
}
});
});
});

Uploading Image Using JSON is not Working

Can anyone help my code structure? What's wrong with it?
HTML
<form method="post">
<div class="col-md-4">
<div class="field name-box">
<input class="btn" name="image_file" id="image_file" type="file" style="font-size:15px;width:100%;margin-bottom:2px;" required=""/>
</div>
</div>
</form>
JS
var form_data = new FormData();
$.ajax({
type: "POST",
url: baseUrlAction() + '?btn=add_product_image',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert("Successfully");
},
error: function(ts){
}
});
AJAX_CONTROLLER
public function add_product_image(){
if(is_array($_FILES)){
if(is_uploaded_file($_FILES['image_file']['tmp_name'])){
$sourcePath = $_FILES['image_file']['tmp_name'];
$targetPath = "product_images/"."sample_img_name".".png";
if(move_uploaded_file($sourcePath,$targetPath)){
// echo '<script>alert("Successfully Save")</script>';
}
}
}
}
But I've been wondering why I will get a success response on my ajax form? even my upload_file doesn't work properly. Can anyone help me?
you need to append data with form_data in your js file and send response
formData.append('image_file', $('#image_file')[0].files[0];);
var form_data = new FormData();
formData.append('image_file', $('#image_file')[0].files[0]);
$.ajax({
type: "POST",
url: baseUrlAction() + '?btn=add_product_image',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert("Successfully");
},
error: function(){
}
});
pass form Element to FormData
let form = document.getElementById("yourFormId");
var form_data = new FormData(form);

jQuery AJAX passing more than one variable to data

below you can see the html code, javascript/jquery and PHP. I'm trying to send a request using AJAX PHP, to send multiple variable to PHP, one of them is FormData and the other is some text or values from inputs etc.
Here's html code:
<div>
<p>Name:</p>
<input id="newP_name"></input>
<p>Product Image</p>
<input type="file" id="img"></input>
<p>Description:</p>
<textarea id="newP_desc"></textarea>
<button name="submitProductBtn" id="submitProductBtn">Submit</button>
Here's my javascript:
$("#submitProductBtn").click(function(){
var file_data = $('#img').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'imgParser.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data, name: "John",
type: 'POST',
success: function (response) {
alert(response);
},
error: function (response) {
alert("ERROR OCCURED");
}
});
});
As you can see I'm trying to pass to 'data:' the FormData (image) and a second variable name.
Here's PHP code:
<?php
if(isset($_FILES["file"]["name"])){
if($_FILES["file"]["error"] == 0){
move_uploaded_file($_FILES["file"]["tmp_name"], "images/".$_FILES["file"]["name"]);
echo $_POST["name"];
}else{
echo $_POST["name"];
}
}
?>
I would expect it to print "John", but the alert is blank, image showing ->
Any help appreciated,
thanks in advance.
EDIT:
Changed slightly the jQuery code, still outputs empty, but when I had code commented out in PHP (below closing tag), it printed it.
here's my new jquery code:
$("#submitProductBtn").click(function(){
var file_data = $('#img').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', "John");
$.ajax({
url: 'imgParser.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function (response) {
alert(response);
},
error: function (response) {
alert("ERROR OCCURED");
}
});
});
You append all data fields to the form data object just like you did with the file
form_data.append('file', file_data);
form_data.append('name', 'John');
I'm not sure what is form_data maybe you can try this,
form_data.append('file', file_data);
form_data.append('name', 'john');
and simply pass form_data in data property
$.ajax({
...
...
data: form_data

send uploaded files and inputs values with ajax

I'm trying to upload files with datas using ajax.
here is my html form :
<body>
<input type="text" id="name" value="test" />
<input type="file" id="pic" accept="image/*" />
<input id = "submit" type="submit" />
</body>
when I send the uploaded file alone with ajax it is working using new FormData();
var file_data = $('#pic').prop('files');
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'test.php', // point to server-side PHP script
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(php_script_response){
alert(php_script_response);
}
});
but Idon't know how to send the input 'name' with Data
var DATA = 'name='+name;
$.ajax({
url: "test.php",
type: "post",
data: DATA,
success: function (response) {
console.log($response);
},
});
Thanks

Laravel 5.2 - Upload image with ajax

I'm trying to upload an image with ajax like this:
ROUTE
Route::get('upload', 'PostController#addPhoto');
VIEW
<form action="" id="upload" enctype="multipart/form-data">
<input type="file" id="file" name="file">
<input type="hidden" name="_token" value="{{csrf_token()}}" id="token">
Upload
</form>
CONTROLLER
public function addPhoto(Request $request){
$file = $request->file('file');
//dd($file);
return response()->json(['file'=>$file]);
}
JS
function upload(){
var token = $('#token').val();
var route = "http://localhost:8000/upload";
var form = $('#upload')[0];
var formData = new FormData(form);
console.log(form);
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: "GET",
cache: false,
dataType:'json',
processData: false,
contentType: false,
data: {'file': formData},
success:function(data){
console.log(data);
},
});
}
var uploaded = document.querySelector('#submit').onclick= upload;
In my controller dd($file); return null. Please how can i fix this error? how can i get the file image well? Maybe some error in ajax or form? I would like upload file image, thank you for your help!

Categories