3

Hi i am trying to upload an image with comments added to it into a database using php ajax and html.

here is the html part:

<form name="form1" enctype="multipart/form-data" action="">
            <h2></h2>
            <div class="form-group">
            <textarea name="msg" class="form-control status-box" id="post" rows="3" cols="60" placeholder="What\'s on your mind?"></textarea>

            <p>Upload an image.</p>
            <input type="file" id="postPhoto" name="postPhoto" value="upload" placeholder="Upload Image">

            </div>
    </form>

    <div class="button-group pull-right">
        <p class="counter">200</p>
        <a href="#" type="submit" onclick="submitChat()" class="post btn btn-primary">
            Post</a>
    </div><br><br>

this is what i have to the ajax which is on the same page as the html

<script>
function submitChat() {
var file = document.getElementById("postPhoto");
var formData = new FormData();
// alert(formData);
formData.append("file[]", file.files[0]);

if(form1.msg.value == '') {
    alert('You must Enter a Post');
    return;
}



var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById('logs').innerHTML = xmlhttp.responseText;

    console.log(xmlhttp.statusText);
    }
}
xmlhttp.open('POST', 'userposts.php?msg='+msg, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send(formData);


}
<script>

and this is the php part:

$msg = stripslashes(htmlspecialchars($_REQUEST['msg']));
 if(isset($_FILES['postPhoto']['type'])) {
$imageData = "";
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES['postPhoto']['name']);
$file_extension = end($temporary);

if((($_FILES['postPhoto']['type'] === 'image/png') || ($_FILES['postPhoto']['type'] == 'image/jpg') || ($_FILES['postPhoto']['type'] == 'image/jpeg')) && ($_FILES['postPhoto']['size'] < 2500000) && in_array($file_extension, $validextensions)) {
    if($FILES['postPhoto']['error'] > 0) {
        echo "return code: " . $_FILES['postPhoto']['error'] . "<br/><br/>";
    }
    else {
        $imageData = mysqli_real_escape_string($connection, file_get_contents($_FILES["postPhoto"]["tmp_name"]));
    }
}
}



$stmt = "INSERT INTO posts VALUES ('', '$uname', '$msg', '$imageData')";
$result = $connection->query($stmt);

the images do not seem to be getting sent to the php file idk how to go about fixing this. any help would be much appreciated.

shahidfoy
  • 1,951
  • 1
  • 17
  • 23

1 Answers1

2

Maybe Helpful,

You simply can't upload a file with pure Javascript ajax functions (at least not in a cross browser way, see this article for more information)

This is because XMLHttpRequest has no support for multipart/form-data, you can do tricks like using an iframe or use flash.

There are enough articles on the internet that explain this.(maybe helpful)

http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html

http://www.faqs.org/rfcs/rfc2388.html

Recomand

Use jQuery Ajax. which have easy lib. support and functions to upload images and submit/parse to destination files.

below sample jQuery AJAX code for demo

   $(document).ready(function(){
      $(document).on('submit','form[name="form1"]',function(e){
        e.preventDefault();
        var form = $(this)[0];
        var formData = new FormData(form);
            $.ajax({
              url: 'Your url here',
              data: formData,
              type: 'POST',
              // THIS MUST BE DONE FOR FILE UPLOADING
              contentType: false,
              processData: false,
              // ... Other options like success and etc
              success : function(data){
                  //Do stuff for ahed process....
              }
            });

      });
    });
Soni Vimalkumar
  • 1,449
  • 15
  • 26