4

I'm stuck!! :( I want to upload image file with a title and a caption, I want to use javascript for validation of title caption and a file choosen.

My html goes here:

<input type="text" name="title2" id="title2" value="title" /><br />

<textarea cols="50" rows="10" name="caption" >caption goes here...</textarea><br />
<input type="file" name="photo" id="photo" /><br />
<button id="submit_info" onclick="photowcap()" >post</button><br />

and my javascript here:

function photowcap()
{

var title = document.getElementsByName("title2")[0].value;
var photo = document.getElementsByName("photo")[0].value;
var captions = document.getElementsByName("caption")[0].value;
var caption = encodeURIComponent(captions)

var xmlhttp;
if(title == "" || title == " " || title == "title")
{
    document.getElementsByName("title2")[0].focus();
    document.getElementsByName("title2")[0].value="";
    return;
}
else if(captions == "" || captions == " " || captions == "caption goes here..."){
    document.getElementsByName("caption")[0].focus();
    document.getElementsByName("caption")[0].value="";
    return;
}
else if(photo == ""){
    alert("please choose image");
}
else{
if (window.XMLHttpRequest)
{
    xmlhttp=new XMLHttpRequest();
}
else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert("Success!!!");
        }
    }
xmlhttp.open("GET","photowcap.php?    title="+title+"&caption="+caption+"&photo="+photo,true);
    xmlhttp.send();}

}

And for saving it using php:

<?php

include("admin_conn.php");

$title = $_GET["title"];
$caption = $_GET["caption"];
$photo = $_GET["photo"];
$time=time();
$date = (date("D F d Y",$time));

$query_photowcap = "INSERT INTO school_updates(title, photo, caption, date, time)     VALUES('$title','$photo','$caption','$date','$time')";
mysql_query($query_photowcap);

?>

it only save for the file path as "C:fakepath/filename...." because I dont have any idea on how to get filename using javascript, and finally I have this code for saving the actual image into the folder but I dont really get where I should place it: THANKS IN ADVANCE :)

<?php

error_reporting(0);
$max_file_size = 200 * 1024; #200kb
if (($_FILES["photo"]["type"] == "image/gif")
  || ($_FILES["photo"]["type"] == "image/jpeg")
  || ($_FILES["photo"]["type"] == "image/png" )
  && ($_FILES["photo"]["size"] < $max_file_size))
  {
  $path = 'images/' . uniqid();
  move_uploaded_file($_FILES["photo"]["tmp_name"],
  $path.$_FILES["photo"]["name"]);

  }
else
  {
  echo "Files must be either JPEG, GIF, or PNG and less than 200 kb";
  }

?>
5
  • 1
    "C:fakepath/filename...." is sth given by the browser security settings. The original path you won't be able to get. dev.sencha.com/deploy/ext-4.0.0/examples/form/file-upload.html was done by professional programmers, and even they couldn't circumvent it. Commented Jan 9, 2014 at 14:52
  • please help :) I'm just kinda stucked...sorry for bad english :D Commented Jan 9, 2014 at 14:52
  • Help with WHAT EXACTLY? Commented Jan 9, 2014 at 14:53
  • 1
    @Alexdn you need to learn how files work. This is not as simple as copy/paste. You need to send the file as binary data and handle it as such on the server side. Commented Jan 9, 2014 at 14:54
  • I have done uploading image before, but using pure PHP. Now, I want to do it with javascript. What can you suggest sir?? Commented Jan 9, 2014 at 14:55

2 Answers 2

6

In order to access files with the $_FILES superglobal they need to be sent with a multipart/form-data content-type header and appropriate attributes. Unfortunately you cannot do this with xhr's send method manually because sending a string will be automatically converted to UTF-8. Fortunately though you can still send binary data such as a file from javascript's window.File.

This is not supported in older browsers. The code would look like

var file = document.getElementById('photo').files[0];

...

xhr.send(file);

And then on the server side you will need to access the input buffer directly in order to grab a hold of this file

$file = file_get_contents('php://input');

If you insist on using $_FILES you could use the FormData object in javascript. The reason I left this as a second option is because I've heard about greater support issues and I personally avoid using it for now.

var formData = new FormData(document.getElementById('theForm'));
...
xhr.send(formData);

EDIT 2016

It has been some time now since I posted this answer and now the FormData object is widely supported, if you are looking to upload files along with other data you may look into that.

Sign up to request clarification or add additional context in comments.

2 Comments

Didn't know this... can you share a link or something with more details?
@zozo Have a look at the File API and XHR2.
0

You are trying to upload an image with ajax... short answer... normally you can't. You need a multipart/form-data to upload, making ajax upload a pain.

An easy work around would be to validate the form with js, then normally submit it. Like here: Ajax Upload image - well... ignore the title, is misleading.

6 Comments

Now, I have just realized something important.
You can share with the rest... not just make us curious :).
You can upload files via ajax in all modern browsers.
That's why I said normally... and said it is a pain not impossible :P. Also ty for the other comment (at php_nub) answer.
It's not a pain, it's very easy with the File API and XHR2
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.