Store PDF file in JS variable - javascript

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

Related

Passing variable from PHP to Javascript, using Ajax returns 'undefined'

I have got a PHP file that received data that has been posted from a form. It then sends it to a database. However I needed to get those variables and put them in JavaScript. I have done the following, but when logging the variables supposed to store the php data (in the script file) it return undefined.
What am I doing wrong? I am new to all the languages. The files are all separate - with the PHP and Script files being external.
SCRIPT:
$(function(){
var data1 = $("#username").val();
console.log(data1);
$.ajax({
type: "POST",
url: 'signUp.php',
data: ({data1}),
success: function(data) {
console.log("success");
}
});
});
PHP
if (isset($_POST['signup'])){
//The connection to the database
include_once 'databaseHandler.php';
//Gets the infomation submitted from the form
//Protects the database by converting everything to text...
//The database therefore cannot read the inputs as code
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
echo (".$user.");
HTML
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
You never set the post parameter 'signup'. Which in turn does not let you enter your if construct and therefor php gives you nothing.
Try:
data:{
"username":$('usernameSignUp').val(),
"password":$('passwordSignUp').val(),
"signup":1,
}
I think, you don't send the variable correctly.
var data1 = $("#usernameSignUp").val();
var data2 = $("#passwordSignUp").val();
$.ajax({
type: "POST",
url: 'signUp.php',
data: {signup:'1',username:data1,password:data2 },//Supose data1= username data, data2 = password data
success: function(data) {
console.log("success");
}
});
There is so much wrong here, it is hard to know where to begin.
You make the Ajax request when the page loads. This is before the user has typed anything into the form.
When the form is submitted, you don't use Ajax at all
You pass a field called data1 to the server (which it is not looking for)
You give that field the value of the input with id="username" (which doesn't exist)
You don't pass fields called username or password to the PHP (which it is looking for)
You don't pass a field called signup to the PHP (which it tests for with isset before doing anything)
Your PHP echos a variable called $user which you haven't defined
Your JavaScript doesn't look at the response, it just logs the string "success"
You'd need something more like:
$(function() {
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: 'http://example.com/signUp.php',
data: ({
signup: 1,
username: $("#usernameSignUp").val(),
password: $("#passwordSignUp").val()
}),
success: function(data) {
console.log("Success", data);
},
error: function(data) {
console.log("This is a cross origin request to a dummy URL, what did you expect");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
Then there are the things which are bad practises but which don't directly affect the ability of the code to work.
You use mysqli_real_escape_string instead of placeholders.
You don't hash your passwords. "Not hashing at all" is an unsuitable hashing algorithm; you need to take better care of your users' passwords.
The HTML5 placeholder attribute is not a substitute for the label element

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

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.

jquery form serialization issue

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]

jQuery file Upload and ajax

So, I have the following form and js/php:
php
<form enctype="multipart/form-data">
<input id="fileupload" type="file" name="files[]" class="files " onChange="UploadImage" accept='image/*'/>
<input type="button" class="submit_form" value="submit">
</form>
<?php
add_action( 'wp_ajax_UploadImage', 'UploadImage' );
function UploadImage()
{
$upload_dir = wp_upload_dir();
$files = $_FILES['files'];
//Some function
}
?>
JS
function UploadImage(e)
{
jQuery('#fileupload').fileupload({
url: upload_image.ajax_url,
});
if(jQuery('#fileupload')) {
var form = document.forms.namedItem("upload_video");
var formdata = new FormData(form);
formdata.append('action', 'UploadImage');
jQuery.ajax({
success : function(data){
alert('sddsf');
}
})
}
};
As you can see from here, when an image is selected using Blueimp jQuery File upload (which the js is not properly written), I want the image file to be handled by the php function.
In other words, the js is not correctly written and I am not sure how to initiate the plugin then when the image is selected, it is processed by the php function via ajax (meaning, how do I parse the file info to php function via ajax?)
Don't use $.ajax directly. The plugin already does that behind the scenes.
Here's a working example, based on your code, but adapted to run on JSFiddle:
$(document).ready(function(){
var url = '/echo/json/';
var formdata = {json: JSON.stringify({field1: 'value1'})};
jQuery('#fileupload').fileupload({
url: url,
formData : formdata,
dataType: 'json',
type: "POST",
contentType:false,
processData:false,
success : function(data){
alert('success...');
console.dir(data);
}
});
});
Demo: http://jsfiddle.net/pottersky/8usb1sn3/3/

Categories

Resources