can not get file path from image browse in javascript onclick button - javascript

i have a simple browse which accepts only images. But after onclick button i can not get the full path in javascript so that i can send them to server by jquery post. i am only getting the filename.
javascript
<script type="text/javascript">
function post_ad() {
var img = document.getElementById('img1'),
tempimg= img.value;
alert(tempimg);
jQuery.ajax({
type: 'POST',
url: 'process.php',
data: {
tempimg: tempimg
},
success: function (html) {
}
});
}
</script>
HTML
<input id="img1" name="img1" accept="image/*" type='file'>
<input type="button" onclick="post_ad()" value="click">

For security reasons its forbidden. Here its a more complete answer:
How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

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

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

How to Upload and Display File Using Play Framework and jQuery?

I have one scenario: I am uploading one file at some server location using: https://www.playframework.com/documentation/2.0/JavaFileUpload ,
//Uploading file:
<input type="file" name="fileUpload">
<input type="submit" value="Upload">
And from the below code, I am uploading the above uploaded file and getting/displaying it on my view page like(After clicking the Submit button):
<input type="file" id="inputfile">
<input type="button" value="Submit" id="submitfile">
jQuery:
$("#submitfile").click(function(){
var path1 =$('input[type=file]').val().replace(/C:\\fakepath\\/i, '');//uploaded file names
//adding the Play framework server path for Application to get the image(s) file(s) path
var filespath = '/files/images/'+path1;//giving my uploaded files path here
});
But my requirement is that: I need only one type which does both: accepts/uploads the file at server location and returns/displays the same file path from server location on my view page ? I am struggling for it. Please help me.
This looks like a similar issue to 33163555. That question has the following example:
Edit: Reference 2320069 for support on ajax file uploads & alternatives:
FormData support starts from following desktop browsers versions. IE
10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" id="file" name="file" />
<input type="submit" id="submit" name="" value="Upload" />
</form>
<script>
$('#submit').click(function (event) {
event.preventDefault();
var file = $('#file').get(0).files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'upload',
data: formData,
type: 'POST',
contentType: false,
processData: false,
beforeSend: function (data) {
alert('Are you sure you want to upload document?');
},
success: function (data) {
//call your jQuery action here
alert('Upload completed: ' + data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ': ' + errorThrown);
}
});
return false;
});
</script>
In your routes you have:
POST /upload controllers.Application.upload()
Where your controller method returns the filepath:
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart fileP = body.getFile("file");
if (fileP != null) {
File file = fileP.getFile();
//If we want to move from temp
//FileUtils.moveFile(file.getCanonicalPath(), "FileB");
return ok(file.getCanonicalPath());
} else {
return badRequest("Upload Error");
}
}
And you can perform your custom jQuery action in the ajax success callback

Form not submitting file / Undefined index: FileInput - PHP/AJAX/jQuery

I am trying to use jQuery to trigger a form submission and then use AJAX to call a PHP script that will handle the file and return a response. The issue, though, is that the file is not being uploaded upon submitting the form.
HTML:
<div id="browseButton" class="step1Button" onclick="browseFile()">Browse</div>
<form method="post" id="fileForm" style="display:inline-block;">
<input id="browseInput" type="file" name="FileInput" style="display: none"/>
<label for="upload-click-handler"></label>
<input id="upload-click-handler" type="text" readonly />
<input id="submitForm" type="submit" style="display: none"/>
</form>
<div id="previewButton" class="step1Button pull-right" onclick="uploadFile()" style="background-color: #57a957">
Preview
</div>
jQuery:
function uploadFile() {
submitForm();
parseExcel();
}
var submitForm = function() {
$('#previewButton').click(function(){
$('#submitForm').click();
});
};
var parseExcel = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",'default/ParseExcel',true);
xmlhttp.send();
console.log("made it past excel parse");
};
The PHP that's called:
public function actionParseExcel() {
print "made it to parse".PHP_EOL;
print "File:";
if($_FILES['FileInput']['tmp_name']) {
print_r($_FILES['FileInput']['tmp_name']);
}
else {
print "Not found";
}
print "Done.";
}
I know the issue is that my form isn't submitting the chosen file because that's typically why the "Undefined index" error is thrown. But I can't understand why.
First, if you don't want your page to refresh, you better use <input type="button">
or else call your JavaScript via <form onSubmit="uploadFile()"> and return false at the end of your function uploadFile().
Second, you'll need to put enctype="multipart/form-data" in your <form>.
I see you're using JQuery, you should use it to send your AJAX request too :
// This code supports multiple type="file" inputs
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Create a formdata object and add the file
var data = new FormData();
// In case you want to upload more than one file
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'your.php?FileInput',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Prevent the file from beeing converted to string
contentType: false, // Set the content file to false prevent JQuery from using 'application/x-www-form-urlencoded; charset=UTF-8' as default type
...
});
I hope this will lead you to the solution...
Edited : var files declaration + files processing
To send forms with files you need to use enctype="multipart/form-data".
BUT, as far as I know, you can't send files using ajax.
So, the solution for that is to use a hidden iFrame:
Create a hidden iFrame (outside of your form) and assing it an ID
Create the form pointing to yout PHP file, and using the attribute enctype="multipart/form-data" and target="ID_OF_THE_IFRAME" (so the form, when submitted, will be sent to that iframe)
When the PHP finish procesing the file, you could output a javascript that calls parent.YOURFUNCTION(), so you can do whatever you want when the process is done.
Good luck!

How do you submit a Javascript generated bitmap image via POST?

If I create a dynamic bitmap on the clientside via javascript, how can I submit this via POST or GET ( and then parse out values from the bitmap on the serverside? NodeJS, PHP etc )
From Making Images Byte-by-Byte in Javascript
var src = 'data:image/bmp;base64,' + myBase64EncodedData;
Just upload the base 64 data. Parse it on the server side form there any way you like.
HTML:
<form id="uploadImage" method="POST">
<input type="hidden" name="imageData64" id="imageData64"/>
<input type="submit" value="upload"/>
<form>
JS:
document.getElementById('uploadImage').onsubmit = function() {
document.getElementById('imageData64').value = myBase64EncodedData;
};
Or you could do the same with an ajax request.
You probably don't want to use GET though. Partly because it's not appropriate, you aren't retrieving anything form the server. But more because GET puts some limits on URL length, so your image data may not fit. POST has no such limit since the request can have a body, unlike GET.
You can use post like this..
HTML
<img src="whatever.jpg" id="myimage" />
<div id="button" data-role="button">Click on button</div>
JS
$(function() {
$("#button").click(function() {
postImageData();
});
});
function postImageData(){
var img = document.getElementById('myimage')
var myBase64EncodedData = getBase64Image(img);
$.ajax({
type: 'POST',
url: 'http://same_domain_url.com/',
data: {
'imagedata': myBase64EncodedData
},
success: function(msg){
console.log('posted' + msg);
}
});
}
php
$imagedata=$_POST['imagedata'];
For getBase64Image function refer to this SO question
Get image data in JavaScript?

Categories

Resources