jquery form serialization issue - javascript

I am doing form serialization to send the file name to the server.
This serialization values is empty . I am expecting the file name over here.
My form is having a html file upload element. Which shows the file name in the right side when you select the file.
HTML:
<form name="MyForm" id="MyForm" method="post" action=cgi_path">
<input type="file" name="filename" id="my_file">
</form>
SCRIPT:
var frm_data = $("#MyForm").serialize(); // This is empty
$.ajax(
{
type: "POST",
url: "file upload cgi url",
data: frm_data
});
How to take the file name with out serializing this form?
Is there any problem with form serialization for file name?
Thanks

Files can only be uploaded with AJAX by using FormData, not serialisation (since you are sending more than just the filename).
$.ajax({
url: url,
data: new FormData($("#MyForm").get(0)),
processData: false,
contentType: false,
type: 'POST'
})

I assume you have an <input id="some_ID" name="some_name" type="file" />
so, you just need to pick the element "content"
var file = {}
$('#some_ID').change(function(){
file.content = this.files[0];
file.name = file.name;
file.size = file.size;
file.type = file.type;
});
then you just need to post it to the server.

You don't have to serialize the form to get the file name. To retrieve it just call
var filename = document.getElementById("my_file").files[0];
or this with jQuery
var filename = $('#my_file')[0].files[0]

Related

Post more than one parameter for file upload to the web api

I have this html form which let user upload a file and also another extra input type for extra info about this upload.
<form method="post" enctype="multipart/form-data">
<input id="files" name="files" type="file" size="1" />
<input type="text" id="tags">
<button type="submit" id="btnSave" onchange="uploadFiles();">Upload and Save</button>
</form>
and this is my javascript
function uploadFiles() {
var input = document.getElementById('files');
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax(
{
url: "https://localhost:xxx/api/file/upload",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function () {
alert("Files Uploaded!");
}
}
);
}
My question is how do I add others parameters (i.e tags here) to post to web api and at the same time upload the file? Post the request at complex type? Any example for complex type which include file upload?
You just can append new properties there.
formdata append will help you to add string and file
formData.append("tags",document.getelementbyid('tags').value);
this is some source to read about FormData
https://developer.mozilla.org/en-US/docs/Web/API/FormData

Sending images and text filed formdata ajax to php. images not identified by php

I have input text boxes of type text and one input text box of type file.I want to send these values to php file via ajax when a button is clicked. Everything seems well but for some crazy reason the image if not identified in the php file.
Kindly help, am out of ideas. My code is as below.
=========javascript code when a button if id=Saved is clicked====
$("#saved").on('click',function(){
$("#itemform").submit(function(e){
e.preventDefault();
});
var item_desc =document.getElementById("item_desc").value;
var item_price_type =document.getElementById("item_price_type").value;
var item_regular_price =document.getElementById("item_regular_price").value;
var item_type =document.getElementById("item_type").value;
var item_cat =document.getElementById("item_cat").value;
var taxablee =document.getElementById("taxablee").value;
var item_price_tax =document.getElementById("item_price_tax").value;
var item_offer_price=document.getElementById("item_offer_price").value;
var offer_start =document.getElementById("offer_start").value;
var offer_end =document.getElementById("offer_end").value;
var file =document.getElementById('file').value;
var price_tax="";
var formdata = new FormData();
formdata.append('file',file);
formdata.append('item_desc',item_desc);
formdata.append('item_price_type',item_price_type);
formdata.append('item_regular_price',item_regular_price);
formdata.append('item_type',item_type);
formdata.append('item_cat',item_cat);
formdata.append('taxablee',taxablee);
formdata.append('price_tax',price_tax);
formdata.append('item_offer_price',item_offer_price);
formdata.append('offer_start',offer_start);
formdata.append('offer_end',offer_end);
});
============php file to insert data into database===========
$item_desc =$_POST['item_desc'];
$item_price_type=$_POST['item_price_type'];
$item_regular_price=$_POST['item_regular_price'];
$item_type=$_POST['item_type'];
$item_cat=$_POST['item_cat'];
$taxablee=$_POST['taxablee'];
$price_tax=$_POST['price_tax'];
$item_offer_price=$_POST['item_offer_price'];
$offer_start=$_POST['offer_start'];
$offer_end=$_POST['offer_end'];
$item_image = $_FILES['file']['name'];
$folder = "../menu_images/";
$pics =time().$item_image;
//$sq="// this is my insert statment";
//$sq_insert =$conn->prepare($sq);
//$sq_insert->execute(array(//these are my array values for the insert
statment));
move_uploaded_file($_FILES["file"]["tmp_name"], $folder.$pics);
Why not use just a html form to submit your data, no need to use javascript for that.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
});

send image url and data through serialization

I am trying to make a form where there will be user data(name,dob etc) and an image. When user submits the form a pdf will be generated with the user given data and the image. I can successfully serialize the data but failed to get image in my pdf. I am using simple ajax post method to post data. Below is my code.
HTML code
<form onsubmit="submitMe(event)" method="POST" id="cform">
<input type="text" name="name" placeholder="Your Name" required>
<input type="file" name="pic" id="pic" accept="image/*" onchange="ValidateInput(this);" required>
<input type="submit" value="Preview"/>
</form>
Jquery code
function submitMe(event) {
event.preventDefault();
jQuery(function($)
{
var query = $('#cform').serialize();
var url = 'ajax_form.php';
$.post(url, query, function () {
$('#ifr').attr('src',"http://docs.google.com/gview?url=http://someurl/temp.pdf&embedded=true");
});
});
}
PHP code
<?php
$name=$_POST['name'];
$image1=$_FILES['pic']['name'];
?>
Here I am not getting image1 value. I want to get the url of the image.
You need FormData to achieve it.
SOURCE
Additionally, you need to change some stuff inside ajax call(explained in link above)
contentType: false
cache: false
processData:false
So the full call would be:
$(document).on('change','.pic-upload',uploadProfilePic);
#.pic-upload is input type=file
function uploadProfilePic(e){
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
$.ajax({
type:"POST",
url:"uploadpic.php",
data: actual,
contentType: false,
cache: false,
processData:false,
dataType:"json",
success: function (response){
#Maybe return link to new image on successful call
}
});
}
Then in PHP you handle it like this:
$_FILES['file']['name']
since you named it 'file' here:
actual.append('file', newpic[0]);

Submit HTML form data as a file / Combine form data + file and send as single file in Javascript

I have a form with input field like some textfields ,textareas,dropdowns and a file upload field which the user will upload while filling the form i want to send form contents (both form field values + uploaded file) as one file to the server below is a very simplified version of my problem .Say i have the following markup
<form id="myForm" method="post" action="something">
<input type="text" name="username" id="username">
<input type="text" name="email" id="email">
<input type="file" name="myFile" id="myFile">
</form>
So now what i want is instead of sending above 2 text fields and a file separately i want them to get embedded in a file and then get sent as a whole.
example
Note that the server where i am sending is third party and only excepts files also file format is proprietary but nonetheless it still a ASCII plain/text.I realize that it's only possible by AJAX and fileReader API so here is what i have tried
var file;
$('#myFile').change(function(e){
file = this.files[0];
var fr = new FileReader();
fr.onload = function(event){
fileData = fr.result;
};
fr.readAsDataURL(file);
$('#myForm').submit(function(e){
e.preventDefault();//prevent submit
var myFile= [$('#username').val(),$('#email').val(),fileData];
$.ajax({
url : "some url",
type: "POST",
contentType:false,
processData:false,
data: myFile;
success:function(data){ }
});
});
Issue is that upon form submission no file gets sent .Any help would be greatly appreciated , thanks.
In form submit you can do as mentioned below for send file with AJAX request
$('#myform').submit(function(e){
e.preventDefault();//prevent submit
var form_data = new FormData();
form_data.append('file', $('#myfile').prop('files')[0]);
form_data.append('username', $("#username").val());
form_data.append('phone', $("#phone").val());
$.ajax({
url : "some url",
type: "POST",
contentType:false,
processData:false,
data: form_data;
success:function(data){ }
});
});
There are 2 parts
Convert file to string format or serialize it on client side using FileReader API
Combine your form values with this string and send them as a file.
Part one
I don't know if you have noticed or not but when you use readAsDataURL() you don't get the original file byte-stream but its base64 encoded version so keeping that in mind change you code to
var fileData;
$('#myFile').change(function(e){
file = this.files[0];
var fr = new FileReader();
fr.onload = function(event) {
encfileData = fr.result;
startInx = encfileData.indexOf('base64');
startInx += 7;
tmp = encfileData.substr(startInx);
//removes the file MIME header part ie. "data:text/plain;base64," before decoding
//regex may be preferable
fileData = atob(tmp); //DECODE
};
fr.readAsDataURL(file);
});
So now you have a string containing your file's byte-stream now as you have said there is some format so depending on that you do whatever manipulation you may need to make it align with the format, since you have mentioned it's plain text format so basic string function are sufficient here.For next part i assume simple colon based CSV format key1:value1,key2:value2
Part Two
Now to truly create a file out of thin air you can use either File or Blob but i would suggest using Blob due to its better support.To contain the file you require FormData simply append your blob to it and send
$('#myForm').submit(function(e){
e.preventDefault();
var txtData = "\n username:"+$("#username").val()+","+"email:"+$("#email").val();
// NOTE: windows uses \r\n instead of \n for newlines
var payLoad = fileData + txtData; //append text field data to the file data
var blob = new Blob([payLoad], {type : 'plain/txt'});
var form = new FormData();
var fileName = 'combined.txt'; //filename that will be used on server
form.append('something', blob, fileName);
$.ajax({
url: "some url",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: form,
success: function(response){alert(response);}
});
});
If using php on linux your $_FILES should look something like this
Array
(
[something] => Array
(
[name] => combined.txt
[type] => plain/txt
[tmp_name] => /tmp/phpJvSJ94
[error] => 0
[size] => 95
)
)
It seems that you're passing sending the wrong variable in your AJAX payload - shouldn't you be sending fileData instead of file?
You can upload data and files:
HTML
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="text" name="email" id="email">
<input type="file" name="myFile" id="myFile">
</form>
Jquery
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'your_url',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});

File upload into database is empty

I want to upload an array of files, send it to javascript formData object and then via ajax to some php script which will put the file into database. It works fine when I upload one file, send it to formData object in javascript and send it to php.
Problem is when I send an array of files via formData object, my php script will insert an empty file into database (BLOB - 0B). What do I do wrong?
Example:
<form method="post" action="javascript:sendPHP()" enctype="multipart/form-data">
<input type="file" onchange = 'handleFiles(this.files)' name="pics[]" />
<input type="file" onchange = 'handleFiles(this.files)' name="pics[]" />
<input type="file" onchange = 'handleFiles(this.files)' name="pics[]" />
<input type="submit" value="Upload" />
//Javascript
var formData = new FormData();
function handleFiles(files) {
var file = files[0];
formData.append('pics[]', file, file.name);
}
function sendPHP() {
$.ajax({
type: "POST",
url: "../php/haus.php",
data: formData,
processData: false,
contentType: false,
success: function(data){}
})}
//php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !empty($_FILES))
{
foreach($_FILES['pics']['tmp_name'] as $index => $tmpName )
{
if(!empty($tmpName) && is_uploaded_file($tmpName))
{
$imgData= addslashes(file_get_contents($_FILES['pics']['tmp_name']));
$resultPics = $dbConnection->query("INSERT INTO picture (pic, text, id) VALUES ('".$imgData."', 'Hi','1')");
}
}
}
You are missing this attribute multiple="multiple" in your <input>
Do it this way ,
<input type="file" onchange = 'handleFiles(this.files)' name="pics[]" multiple="multiple" />
This function handles only single file upload
function handleFiles(files) {
var file = files[0];
formData.append('pics[]', file, file.name);
}
For multiple uploads you need to use a loop inside to append to each file.
Something Like this ,
function handleFiles(files) {
for(var file in files)
{
formData.append('pics[]', file, file.name);
}
The PHP part , you need to use a loop there as well to loop through each file and use json_encode() to convert the array of files into json string , so that you can insert the record as a string in the database and use json_decode() when retrieving the data back from DB.
Hope this helps.

Categories

Resources