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

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!

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

Save form inputs to txt, popup result, no page changing

I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article

$.ajax won't access url

I'm trying to send some data via jquery and $.ajax to a php file. When the page loads, a list of names is retrieved from "bewohner_func.php". This works.
At the end of the list is a form, which is used to add a new Name onto the list. It uses $.ajax to send the data, also to "bewohner_func.php", using a switch to differntiate from displaying or adding the data-. Problem is, when I try to send the form, the script does not include the php file. I can safely say that it's not the php file's fault, as I reduced it to an alert.
$(document).ready(function()
{
$("#bew_new").submit(function()
{
var frmData = $("#bew_new").serialize();
$.ajax({
url: "bewohner_func.php",
data: frmData,
success: function(msg)
{
$('#bewohnerliste').fadeOut(400);
$.get("bewohner_func.php", {'bew_new': '0'}, function(data){
$("#bewohnerliste").html(data);
});
$('#bewohnerliste').fadeIn(400);
}
});
return false;
});
});
This is the code for displaying, which does it's job fine:
$(document).ready(function()
{
$.get("bewohner_func.php", {'bew_new': '0'}, function(data){
$("#bewohnerliste").html(data);
});
});
The form:
<form id="bew_new" class="bew_form" action="bewohner_func.php" method="get">
<input name="anrede" size="6" value="Anrede" onFocus="if(this.value=='Anrede')this.value=''">
<input name="name" value="Name" onFocus="if(this.value=='Name')this.value=''">
<input name="wohnbereich" size="2" value="WB" onFocus="if(this.value=='WB')this.value=''">
<input type="submit" value="Neu anlegen">
</form>
It sounds like you are running your submit handler code on page load before form is loaded. If so, submit handler won't be bound to form if it doesn't exist.
You can delegate the handler to an eleemnt, or the document itself, that will be permanent asset in page
TRY:
$("#bewohnerliste").on('submit',"#bew_new",function(){
var frmData = $(this).serialize();
$.ajax......
})

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