AJAX - Uploading a file (HTML 5) & PHP - php

I feel completely out of my depth but I feel so close..
I'm trying to Upload a file using AJAX. I found this tutorial http://blog.new-bamboo.co.uk/2010/7/30/html5-powered-ajax-file-uploads and it seemed to be going quite well until the end. I can't seem to access the file in PHP i.e. using $_FILES["foo"]["name"];
and I'm not sure how to upload using other techniques.
I'm not looking for the code to be perfect, just kept simple so I can understand what's going on. Thanks in advance :-)
Here is my server side code:
HTML:
page title
</head>
<body>
<form onsubmit='showUser(); return false;' enctype='multipart/form-data'>
<input id='the-file' name='file' type='file' />
<input type='submit'>
</form>
<br />
<div id='txtHint'><b></b></div>
</body>
Javascript:
function showUser(str)
{
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var foo = file.fileName;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","new_film_pro.php",true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.setRequestHeader("X-File-Type", file.type);
xmlhttp.setRequestHeader("X-File-Name", foo);
xmlhttp.send(file);
}
PHP:
<?php
$postdata = file_get_contents("php://input");
echo "Name: " . $_SERVER['HTTP_X_FILE_NAME'] . "<br />";
?>

Have a look at http://aquantum-demo.appspot.com/file-upload
Writing straight JavaScript is no longer such a great idea. Using libraries as demonstrated on that page, you can create a much more powerful file upload which supports multiple files, resumeable downloads, progress bar and many other features that you would really have to sweat to implement yourself but which give your user a better experience.

I am not sure.but on form tag you have not specified method

You may use file_get_contents('php://input') to get the file content.

Related

It smells like AJAX but I'm not sure

AMENDMENT:
Hi all, thanks for all your replies. I've been wrestling trying to shoe horn the code into my page but I've still had no luck. While fiddling around I can't see why something like the below code wouldn't work - I can't get this to work either mind you(!). If it's not possible I'm hoping someone can shoot the idea down to save me wasting time trying to do it:
<form name='Names' role='form' action='#' method='get' onchange='this.form.submit()'>
<select name="FirstName">
<option value="1">FirstName#1</option>
</select>
<select name="LastName">
<option value="1">LastName#1</option>
</select>
</form>
...could I then pick up these selections in $_GET['FirstName'] and $_GET['LastName'] and pass them into my mysqli_query() to generate the table?
To prevent any chance of my confusion spreading I first want to describe what I'm trying to do... I want a webpage that has a table with a group of dropdowns that I can filter on - similar to Excel filters. If you know of a better way of doing it than how I'm trying below - please do enlighten me!!
Now, to describe the best progress I've made so far:
I have the below script (copied straight over from W3schools:
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","entry_table.php?q="+str,true);
xmlhttp.send();
}
</script>
The above script is called from the below dropdown which populated using a PHP while loop from an SQL query:
<form>
<select name="Name" onchange="showUser(this.value)">
<option value="1">User#1</option>
</select>
</form>
The $q value is then passed to a PHP page to display the table after generating the SQL query with a:
WHERE UserID="$q"
This works but I'm concerned it seems to be a long-winded way of doing it - especially if I'm try to and expand the queries to include 6-7 other dropdown filters.
Thanks in advance,
Ben
You could go for a callback function instead.
function getData(url, callback)
{
if (window.XMLHttpRequest)
{
//IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ //IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
And then make an ajax call like this:
getData("entry_table.php?q="+str, function(data)
{
document.getElementById("txtHint").innerHTML=data;
});
Outer function
function doStuff(value) {
getData("entry_table.php?q="+value, function(data)
{
document.getElementById("txtHint").innerHTML=data;
});
}
and then select would be
<select onchange="doStuff(this.value)">

Sql Querying with Ajax while offline returning blank

I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(str) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status== 200) {
document.getElementById("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?

Data output using Ajax with PHP

I will break this question into paragraphs for easier reference.
I have a script that calls a php file using Ajax; the script is executed once a button is pressed.
The PHP file contains a simple code that plusses a number with 1.
<?php
$response = $response + 1;
echo $response;
?>
However, something goes wrong when the button is pressed multiple times. I have done some research and I can conclude that there is either something wrong with the simple PHP script that I have made, or the code is only executed once per page reload.
I read an article explaining a lot of work using Javascript if I want an Ajax command to execute multiple times during the same script but I don't see the reason that it can't execute multiple times already when the button is pressed.
Question: Is the PHP file "post.php" even getting executed everytime the button is pressed? Is it something with my PHP file?
How can I make the script plus the number by 1 everytime the button is pressed? And is it because I need some extra Javascript to do that?
The rest of the script is here:
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","post.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<p>This button will execute an Ajax function</p>
<button type="button" onclick="loadXMLDoc()">Press here!</button>
<div id="myDiv"></div>
<script type="text/javascript" src="http://www.parameter.dk/counter/5b0d9873158158e08cad4c71256eb27c"></script>
</body>
If I wasn't clear enough at some point, please pick out the paragraph number and I'll deepen that part.
In your code $response is always 1 because php by default have no state. You can fix it by saving response inside a session.
session_start();
if (isset($_SESSION['response'])) {
$_SESSION['response'] = $_SESSION['response'] + 1;
} else {
$_SESSION['response'] = 1;
}
echo $_SESSION['response'];

Change an image using AJAX

I want to create a login page.
So I put a captcha picture in the login form with following html code:
<img name="captcha" id="captcha" src="captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5"/>
and I put a button that users can click on to change captcha if it is unreadable as follow :
<input type="button" name="new_Captcha_button" onClick="new_captcha()"/>
and I wrote a script as follow which work just in chrome :
<script type="text/javascript">
function new_captcha()
{
document.images["captcha"].src = "captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5";
}
</script>
but it doesn't work in other browsers, so I replace the previous code with the following :
<script type="text/javascript">
function new_captcha()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("captcha").src = xmlhttp.responseText;
  }
}
xmlhttp.open("GET","captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5",true);
xmlhttp.send();
}
So please tell me what changes I need to do in my code to make it correct. I think I need to change just following line :
document.getElementById("captcha").src = xmlhttp.responseText;
Thanks a lot.
<script type="text/javascript">
function new_captcha()
{
document.getElementById('captcha').src = 'captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5&_t=' + Math.random(1);
}
</script>
Do not need to use ajax, function new_captcha() is ok as it is.
You may try to do this
login.php
<div id="captcha_container"></div>
<input type="button" id="btn_recaptcha" value="Recaptcha">
<script>
function ajax_loadpage(loadUrl,output_container)
{
$.post
(
loadUrl,
{language: "php", version: 5},function(responseText){$(output_container).html(responseText);},"html"
);
}
ajax_loadpage("captcha_page.php","#captcha_container");
$('#btn_recaptcha').click(function(){
ajax_loadpage("captcha_page.php","#captcha_container");
})
</script>
______________________________________________________________________________________
captcha_page.php
<img width="212" height="53" src="captcha.php">
captcha.php contains my captcha code, it contains a header ("Content-type: image/gif"); code, so i needed an extra php file on where i can save the image file, thus using my captcha_page.php.
Worked for me :)

How to recognise if user clicked out of text input and run php in that event

How can I use javascript to check, if the user clicks out of my text input class = "foo", and then, if the user has done so, execute a php file.
The easiest way to go about doing this, is to use jQuery.
First, include jQuery in your <head></head> section:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Then add in the following Javascript:
$(document).ready(function() {
$('input.foo').blur(function(){
$.ajax('myScript.php');
});
});
This will setup the input (who's class is foo) to use ajax to run myScript.php whenever someone clicks out of it, which in development terms is called blurring.
Here an example with plain javascript.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function runAjax(){
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","fooscript.php",true);
xmlhttp.send();
}
</script>
<form>
<input name="vorname" type="text" onblur="runAjax()">
</form>
</body>
</html>
Maybe it's a good idea to use a javascript framework like jQuery. I've stolen this example from here.

Categories