send uploaded files and inputs values with ajax - javascript

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

Related

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);

Image not uploading without submit button

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);

how to reuse a form and jquery ajax call in multiple sections of a document?

I am working on jquery dialog email attachment. I created a separate form to upload file that uses formdata object. I want to reuse the form and its related ajax call in different dialogs in the same php page(reason: need email attachment functionality in other dialogs). How can i achieve this?
Jquery Ajax call:
$('#attchform').submit(function(event) {
$.ajax({
url: 'uploadfile.php',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
document.getElementById("fileToUpload").disabled = true;
$("#loadimg").html(data);
}
});
event.preventDefault();
});
Html form:
<form id="attchform" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Attach" name="submit">
</form>
<div id="loadimg"></div>
You can define a function and call any where in the same page:
function UploadFile(){
$.ajax({
url: 'uploadfile.php',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
document.getElementById("fileToUpload").disabled = true;
$("#loadimg").html(data);
}
});
}
$('#attchform').submit(function(event) {
UploadFile();
event.preventDefault();
});

Javascript: Upload some files synchronous from a form

I need to upload multiple files from a form. I have an event "submit" that processes the data of the form, uploads the files and then shows a message. I need that this process syncronous to show the message when the files have been uploaded.
I have this HTML code in the form:
<form method="post" action="files/upload_project_file" id="upload_project_file_form" target="upload_project_file_iframe" enctype="multipart/form-data">
<input type="file" name="uploaded_file[]" class="multi" maxlength="0" accept="" />
<input type="hidden" name="action" value="upload_project_file">
<input type="hidden" name="id_project_files" value="" id="id_project_files">
</form>
And this Javascript code in the javascript Submit event:
//processes data
//...
//Upload files
var data = new FormData();
jQuery.each($('input[name^="uploaded_file"]')[0].files, function(i, file) {
data.append('uploaded_file'+i, file);
});
data.append('id_project_files', $("#id_project_files").val());
$.ajax({
url: 'files/upload_project_file',
enctype: 'multipart/form-data',
data: data,
cache: false,
contentType: false,
processData: false,
async: false,
type: 'POST',
success: function(data){
//Clear
$('.filesToUpload').empty();
}
});
//Then show the message and redirect page
//...
I upload only one file but not all, I can't, I don't know why. I've seen Jquery.each runs only once.
No, thanks "user2698878", I didn't want to use Uploadify.
Finally I changed the ajax code and it works perfectly. This is the new code:
var formData1 = new FormData($("#upload_project_file_form")[0]);
$.ajax({
url: "files/upload_project_file",
enctype: 'multipart/form-data',
type: 'POST',
data: formData1,
async: false,
success: function (data) {
$('.filesToUpload').empty();
},
cache: false,
contentType: false,
processData: false
});

File upload using Jquery ajax without form

Here is mycode
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
var startdate=$("#from_date"+elem).val();
var enddate=$("#to_date"+elem).val();
$.ajax({
url: "addpackage/",
type:"post",
contentType:false,
data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
success: function(data) {
}
});
}
I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object]. How to post image with input field without form in jquery ajax?
You can do it like following. Hope this will help you.
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('startdate', $("#from_date"+elem).val());
dataimg.append('enddate', $("#to_date"+elem).val());
dataimg.append('packageid', elem);
dataimg.append('img', $("#browseimg"+elem)[0].files[0]);
$.ajax({
url: "addpackage/",
type:"post",
cache : false,
contentType : false,
processType : false,
data: dataimg,
success: function(data) {
}
});
}
You can try this:
Your JS Code:
<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
type: "POST",
url: url,
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
</script>
Dummy HTML:
<form method="post" action="addpackage/" id="yourFormID">
<input type="text" name="firstvalue" value="some value">
<input type="text" name="secondvalue" value="some value">
<input type="file" name="imagevalue">
</form>
in addpackage php file:
print_r($_POST);
print_r($_FILES);

Categories