Html video upload sent to a php file using XMLHttpRequest - php

Here's a very simple problem I came across today that's been very frustrating to me:
Say I'm uploading a video file through the HTML 'choose file' input, and I have a submit button that calls an onclick java script function for sending the video to a php file and returns data about the video back to the original page, (something simple like echo $_FILES[$myvideoupload]['name'] ) all through XMLhttpRequest().
Is this possible?
As it is right now, the video simply isn't being passed through my ajax function to the php file. Does document.getElementByID("stuff") work for video files? or is it more about how I should format var in send(var)? Any ideas or knowledge on the subject of passing files through XMLHttpRequest() would be awesome.
Here is my not-so-awesome code with the file attempts commented out in the js. Hope this helps.
<html>
<head>
<link href="jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script language="JavaScript" type="text/javascript">
function file_upload(){
var hr = new XMLHttpRequest();
var url = "vidcon.php";
if(document.getElementById('preset_mp4').checked) {
pr = document.getElementById("preset_mp4").value;
}else if(document.getElementById('preset_ogg').checked) {
pr = document.getElementById("preset_ogg").value;
}else if(document.getElementById('preset_mov').checked) {
pr = document.getElementById("preset_mov").value;
}else if(document.getElementById('preset_wmv').checked) {
pr = document.getElementById("preset_wmv").value;
}else if(document.getElementById('preset_3gp').checked) {
pr = document.getElementById("preset_3gp").value;
}
//var fd = new FormData();
//fd.append('uploadedfile', document.getElementByID("uploadedfile").files[0]);
var vars = "preset="+pr;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.response;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="hidden"/>
<form enctype="multipart/form-data" action="" method="POST">
Choose pload:<br> <input id="uploadedfile" name="uploadedfile" type="file" /><br />
</form>
Select Output Format for Conversion (changes will be made to conversion settings) <br>
<div class="field form-inline radio">
<input id="preset_mp4" name="preset" type="radio" value="mp4">mp4<br>
<input id="preset_ogg" name="preset" type="radio" value="ogg">ogg<br>
<input id="preset_mov" name="preset" type="radio" value="mov">mov<br>
<input id="preset_wmv" name="preset" type="radio" value="wmv">wmv<br>
<input id="preset_3gp" name="preset" type="radio" value="3gp">3gp<br>
</div>
<input type="submit" value="Upload File" onClick="javascript:file_upload();"/>
<div id="status"></div>
</body>

You need to use a FormData object to upload a file via ajax. Something like
var fd = new FormData();
fd.append('preset', pr);
fd.append('videofile', document.getElementByID("videofileinputid").files[0]);
hr.open("POST", url, true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.response;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(fd);
document.getElementById("status").innerHTML = "processing...";
Note that not all browsers support the FormData object but the are js libraries that simulate an ajax file upload.

Related

Unexpected end of JSON input - Retrieving Data from server issue

I am trying to create a page whereby you can submit some text and then retrieve it on button press, I have managed to get it to submit to my server, however on retrieval I keep getting the error "unexpected end of JSON input" and have no idea what to do about it, my knowledge of PHP/JSON is very limited, any criticism / pointers are greatly appreciated.
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("DataSubmitted");
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var data = JSON.parse(this.responseText);
alert(data);
}
}
xxhttp.open("GET", "gethint2.php", true);
xxhttp.send();
}
PHP/HTML:
<php? session_start(); ?>
<html>
<script type="text/javascript" src="main.js"></script>
<head>
</head>
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
</html>
Sending Data:
<?
$_SESSION["input_data"] = $_POST;
echo $_POST["input"];
?>
Retrieving Data:
<?php
$_SESSION["input_data"] = json_encode($_POST);
?>

FormData Ajax not posting data in PHP

Hope you can help me with my problem.
The problem is that i put my data in FormData but when i'm calling them in php file using echo there is no values and data existing and gives me error
an undefined variable
But when im using var_dump() or print_r() it show all the values. and also if i var_dump the files for the images it throws me also an error.
Here in html:
<form id="form" action="myurl.php" method="post" enctype="multipart/form-data" onsubmit="return false">
<input type="file" name="image" accept="image/*"/>
<input type="text" name="description"/>
<input type="submit" />
</form>
Here is my code in ajax:
function getName(key)
{
key = document.getElementsByName(key)[0];
return key;
}
function getId(key)
{
key = document.getElementById(key);
return key;
}
var url = getId('form').getAttribute('action');
var datas = new FormData();
var xhr = new XMLHttpRequest();
var image = getName('image').value.trim();
var description = getName('description').value.trim();
datas.append('file_image', image.files[0]);
datas.append('description', description);
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(datas);
xhr.onreadystatechange = function()
{
var OK = 4;
var DONE = 200;
if(xhr.readyState == 4 && xhr.status == DONE)
{
alert(xhr.responseText);
}
}
now in my myurl.php php file
var_dump($_POST);
var_dump($_FILES);
We don't actually using third party script like jQuery. We practice native javascript language.
Thank you.
You don't have to append the element manually to form data, create FormData from the form itself.
Give your form a name name="upload-image
<form id="form" action="myurl.php" name="upload-image" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*"/>
<input type="text" name="description"/>
<input type="submit" />
</form>
In your Javascript
var form = document.forms.namedItem("upload-image");
var url = form['action'];
form.addEventListener('submit', function(ev) {
var oData = new FormData(form);
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
alert(oReq.responseText);
} else {
alert(oReq.status + " occurred when trying to upload your file.");
}
};
oReq.send(oData);
ev.preventDefault();
}, false);

Post ID on Keyup AJAX/PHP/MYSQL

I have the below code. Currently it submits only the first_name which is exactly what I want and it does that on the fly without the page refreshing.
However I need to parse an ID number along the same ajax request through the hidden id field.
Can anybody suggest any ideas to help me?
Thanks in advance
CODE:
<html>
<head>
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var vars = "firstname="+fn+;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<input type="hidden" name="my_id" value="1234">
First Name: <input id="first_name" name="first_name" type="text" onkeyup="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>
Use jquery
<!DOCTYPE html>
<html>
<head>
<title>TITLE</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ajax_post(){
var $elementStatus = $('#status');
$elementStatus.html('processing...');
var url = 'my_parse_file.php';
var data = { firstname : $('#first_name').val() };
var success = function(responseText, textStatus, jqXHR) {
if(jqXHR.status != 200)
return;
$elementStatus.html(responseText);
};
$.post(url, data, success);
};
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<input type="hidden" name="my_id" value="1234">
First Name: <input id="first_name" name="first_name" type="text" onkeyup="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>

Basic jquery & PHP session.upload_progress.name

I am trying to get the file progress working with the new session.upload_progress.name functionality in PHP 5.4.
So far my code is this:
<?
session_start();
?>
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
$("#jimbo").submit(function () {
setInterval(function() {
$.ajax({
url: "ajx.php",
success: function (data) {
$("#feedback").html(data + Math.random(999));
}
});
//$("#feedback").html("hello " + Math.random(999));
},500);
//return false;
});
});
</script>
</head>
<body>
<h1>Upload</h1>
<br/>
<form action="test.php" method="POST" enctype="multipart/form-data" id='jimbo'>
<input type="hidden" name="<?=ini_get('session.upload_progress.name'); ?>" value="myupload" />
<input type="file" name="file1" />
<input type="submit" id='submitme' />
</form>
<div id="feedback">Hello</div>
</body>
</html>
And then the ajx.php file:
<? session_start(); ?>
<pre>
<?
echo "SESSIONVAR<br/>";
var_dump($_SESSION);
?>
</pre>
Now. When I click the submit button (after selecting a file), The file starts uploading, but the setinterval doesnt start. However, If I have the return false; in there, I get the setInterval results, but the file doesnt start uploading. If I submit the file without returning false, and in a seperate window view the contents of ajx.php, I can see that the variable is working fine and updating. So how do I get the #feedback div to update once the form has been clicked?
note the session array is populated, the problem here is with the jquery and nothing else.
You can achieve similar functionality using javascript XMLHttpRequest objects 'upload' property. It has a couple of events you can hook into, 'progress' is one of them.
here's a sample I've used. It will add a row with the progression (in %) to a <div class="progression"> for each file from a <input type="file"> field:
function startUpload() {
var fileInput = document.getElementById("file1");
$('.progression').show();
for(var i = 0;i<fileInput.files.length;i++) {
doFileUpload(fileInput.files[i]);
}
}
function doFileUpload(file) {
var xhr = new XMLHttpRequest();
var data = new FormData();
var $progress = $('<div class=\"progress\"><p>' + file.name + ':</p><span>0</span>%</div>');
$('div.progression').append($progress);
data.append("file", file);
data.append("album", $("#album").val());
xhr.upload.onprogress = function(e) {
var percentComplete = (e.loaded / e.total) * 100;
$progress.find('span').text(Math.ceil(percentComplete));
};
xhr.onload = function() {
if (xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
if(result.success == "true") {
console.log("Great success!");
}
else {
console.log("Error! Upload failed");
}
};
xhr.onerror = function() {
console.log("Error! Upload failed.");
};
xhr.open("POST", "/_admin/_inc/upload.php", true);
xhr.send(data);
}

Form gets re-rendered after submit Ajax

<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "index2.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Your First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
The code above works and submits the data and gets the result, along with the result it renders the form again. Image --> http://oi47.tinypic.com/1bt02.jpg
How to fix it?
Thanks in advance.
Don't include the form in the response you send to the Ajax request.

Categories