send image url and data through serialization - javascript

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

Related

upload a form's file and text data to PHP using jQuery and AJAX

Good morning. I'm trying to make the form submission of a message more fluid avoiding the reload of the page for the sending of it. Since the message may be text or image, I need to send both of them to a PHP page for upload. I'm using this code in the html page:
<form id="newmessage" enctype="multipart/form-data">
<textarea form="newmessage" id="messagetext" name="messagetext" ></textarea>
<input type="submit" name="submit" value="send" onclick="return newMessage();">
<input type="file" accept="image/*" id="image" name="image">
</form>
<script>
function newMessage(){
var messagetext = document.getElementById("messagetext").value;
var image = document.getElementById("image").value;
$.ajax({
type:"post",
url:"new_message.php",
data:
{
"messagetext" :messagetext,
"image" :image,
},
cache:false,
success: function(html) {
document.getElementById("messagetext").value = "";
}
});
return false;
}
</script>
As you can see, I'm allowing users to type in the textarea or upload a file. When they submit the form, the newMessage() method is invoked and sends image and messagetext to new_message.php, which process them:
// new_message.php
$messagetext = $_POST["messagetext"];
$image = $_FILES["image"]["tmp_name"];
if((!empty($messagetext) || isset($image))) {
if(!empty($messagetext)) {
// create text message
} else if(isset($image)) {
// create image message
}
}
When I write a text message it works perfectly, but it doesn't send anything if it's image. Maybe the image variable in AJAX is not taking the file properly. I excuse if this question is unclear, but I'm a beginner in StackOverlow and I'm open to edits. Thanks for all replies.
can you try this. you don't need to worry about the file and message in textarea. Make sure you have added jQuery.
$("#newmessage").on("submit", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var formData = new FormData(this);
$.ajax({
url: "new_message.php",
type: "POST",
data: formData,
success: function (msg) {
document.getElementById("messagetext").value = "";
},
cache: false,
contentType: false,
processData: false
});
return false;
});

Store PDF file in JS variable

Here comes the html code
<input type="text" class="txtbox" placeholder="Name" id="name" name="name" />
<input type="text" class="txtbox" placeholder="E-mail"id="email" name="email" />
<input type="text" class="txtbox" placeholder="Phone" id="phone" name="phone" />
<input type="file" class="txtbox" name="file" id="resume">
<input name="submit" id="submitbutton1" value="Apply Now" type="button" onClick="submitbutton1()" class="txtbox">
and my js function is as follows
<script>
function submitbutton1()
{
console.log("here");
var name=$("#name").val();
console.log(name);
var email=$("#email").val();
console.log(email);
var phone=$("#phone").val();
console.log(phone);
var tal={"name":name,"email":email,"phone": phone};
$.ajax({
type: "POST",
url: "email.php",
data: tal,
success: function(ch)
{
console.log(ch);
}
});
}
</script>
I would like to store the value of that pdf file into a js variable so that I can post all these variables into email.php Is it possible to store a pdf file in a js variable? If it is possible how? Please help me...
I have edited your script.
<script>
function submitbutton1()
{
console.log("here");
var name=$("#name").val();
console.log(name);
var email=$("#email").val();
console.log(email);
var phone=$("#phone").val();
console.log(phone);
var resume=$("#resume").val();
var tal={"name":name,"email":email,"phone": phone,"resume":resume};
$.ajax({
type: "POST",
url: "email.php",
data: tal,
success: function(ch)
{
console.log(ch);
}
});
}
</script>
you can store pdf value inside of your js variable, if you will have this value. You can do it using ajax call to load pdf document from your server. But, it will be binary data, and you will no be able to display it in browser to your client.
You can post this value to server, but it have no sense, because you can post only path to this file, and get content of this file using some server-side programming language functions (file_get_contents in your case).
There is no sense to send binary data as email content, so you should send it as attachment. Have no idea, is it possible to send attachment with php mail() function, previously I do it only with phpmailer. Php mailer need no your binary data, it require only path to file.
I think you have to upload PDF file with ajax and post data into ajax using one ajax request. You can use FormData() object for post file and data value both
function submitbutton1() {
var file_data = $('#resume').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', $("#name").val());
form_data.append('email', $("#email").val());
form_data.append('phone', $("#phone").val());
$.ajax({
url: 'email.php',
cache: false,
data: form_data,
type: 'post',
success: function(result){
console.log(result);
}
});
};

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

Image upload via ajax POST without using HTML form

I am trying to send some data via POST method to a PHP file without using form in HTML. This is the code I have. Why doesn't it do anything?
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid" id="gid">
<input type="hidden" value="User" name="user" id="user">
<button onclick="myFormData()">Upload Image</button>
<script>
$('#fileToUpload').on('change', function() {
var myFormData = new FormData();
var file = document.getElementById('fileToUpload').value;
var gid = document.getElementById('gid').value;
var user = document.getElementById('user').value;
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
});
$.ajax({
url: 'imgupload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
</script>
On imgupload.php I get the POST data like this
$gid = $_POST['gid'];
$user = $_POST['user'];
It worked when I used the HTML form method. What's wrong here?
FormData.append() takes key-value pairs, so this is wrong:
myFormData.append(file,gid,user);
You need something like:
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
Appart from that you need to put this code inside an event handler so that it triggers when you need it to.
For example:
$('#fileToUpload').on('change', function() {
// your javascript code
});
And you should probably also put it inside a document.ready block.

Isset does not work with ajax call

I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.

Categories

Resources