Duke Wang
Duke Wang

Reputation: 83

How to store image to folder and store the path to database using Ajax?

I am developing an application that use HTML and js for front-end and PHP for back-end. I have the following code which should have the functions that: 1, when click on the background image, user can choose photo from there phone as new background image, and use PHP to save the image on server and get the image path, store the path into database, then send new path back to front with JSON, and display the selected image as new background image. Thanks for any help.

javascript for sending and retrieve data:

function UploadImageDialog()
    {
        $("#newProfileImage").click();
    }
    function profileImageSelected(fileInput)
    {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "UploadProfileImage.php", true);
        var formData = new FormData();
        formData.append("file", fileInput.files[0]);
        xhr.send(formData);
        xhr.onload = function() {
        alert(xhr.responseText); //test the returned info from PHP.
        if(xhr.responseText != ""){
            $("#profileBackgroundImage").setAttribute("src", xhr.responseText);
        }
        else
        {
            alert("Your file failed to upload");
        }
    }
}

HTML code to call the javascript:

<div style="width:91.5vw;height:78.5vh;margin-top:10.5vh;">
    <img class="backgroundImage" id="pictureSrc" src="img/Jenny.jpg" onclick="UploadImageDialog()" />
</div>
<input type="file" id="newProfileImage" style="display:none;" onchange="profileImageSelected(this)"/>

PHP code to get the path:

<?php
if(is_uploaded_file($_FILES['file']['tmp_name'])) // if user uploads file
{
    if (!file_exists("./img/EventImages/" . $_FILES["file"]["name"]))
    {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], "./img/EventImages/" . $_FILES["file"]["name"]))
        {
            echo "img/EventImages/" . $_FILES["file"]["name"];
        }
    }
    else
    {
        echo "img/EventImages/" . $_FILES["file"]["name"];
    }
}
?>

Upvotes: 0

Views: 7783

Answers (2)

Duke Wang
Duke Wang

Reputation: 83

I have figured that out. There was nothing wrong with the code, but I didn't set the Directory Permission correctly on the server.

Upvotes: 1

Apul Gupta
Apul Gupta

Reputation: 3034

You should use some libraries like uploadify to upload files without posting form.

DEMO

Upvotes: 1

Related Questions