0

Hello I have been working on a site where you can submit images. I dont want the page to be reloaded when the picture is submitted. After the picture is posted to the php page it is stored a a BLOB in a MYSQL database.

            form id="form2" action="saveImage.php" method="post" enctype="multipart/form-data">
            <input id="thumbage2" name="Image1" class="ModalArea2" type="file" style="display:none">       
            <center><label for="thumbage2" id="labelthumb2" style="margin-top:35px;">Choose Image</label></center>

            <button class="ModalButton2" >Submit</button>
            <a class="ModalButton2" onclick="cancel2();">Cancel</a>
            </form>

The above is my HTML code. Here is my javascript/jQuery code:

     $(':file').change(function(){
    var file = this.files[0];
    var name = file.name;
    var size = file.size;
    var type = file.type;
    //Your validation
    //console.log(name);
});

$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'upload.php',  //Server script to process data
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
    cancel2();
});

I copied this code from a website but they didn't do a great job of explaining how it works. So at the moment I have the data being posted to my PHP file and it works. The problem is that the PHP file is loaded. I thought the whole point of JQuery was not to load the file and to stay on the same page. Why doesn't this happen? Why do I keep getting the PHP page loaded in my browser? Thanks if you solve this for me I would be over the Moon It's been a real kick in the adams apple for me lately.

Jelly
  • 1
  • 3
  • 1
    jQuery is a javascript framework. The whole point of **AJAX** is to submit data in the background, without (re)loading any page. And you really shouldn't just copy code anywhere without knowing what it does or how to customize it to work for you. Now we see that it doesn't work for you, since the page still gets loaded und you don't stay on the same page. – Charlotte Dunois Nov 27 '16 at 17:16
  • About saving BLOB in a database: You really shouldn't do this, it's slow and the filesystem is built for that, the database isn't - while it works, you still shouldn't do this. Read this https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – Charlotte Dunois Nov 27 '16 at 17:18
  • A simple Google search "Ajax upload without reload" gives you this SO answer: http://stackoverflow.com/questions/22038036/uploading-images-using-php-but-without-page-refresh – nvkrj Nov 27 '16 at 17:20
  • @Nvj I dont understand how all of that works could you explain how I could alter my code to stop loading in the page and just do it in the background? Thanks – Jelly Nov 27 '16 at 17:28

1 Answers1

0

I was stuck on a similar problem once, and as far as I searched it, the only way to upload a file without reloading the page is by using iFrames. But iFrames, to me, are ugly.

The below approach converts an image into a data URL, and instead of uploading the image, uploads the data URL (which is just a string) to the server.

I've made a few changes to your HTML code. We don't want to submit the form, since that leads to the web page getting reloaded in the browser. Adding onsubmit = 'return false;' to the form tag will prevent the form from getting submitted when the submit button is clicked.

I've added a few ID's to the input elements in order to make them unique when accessed in JQuery.

Then I've added an image element with a src attribute. When the user selects an image from the input box, the src attribute of this element gets filled with the image's data URL.

<form id="form2" action="saveImage.php" onsubmit="return false;" method="post" enctype="multipart/form-data">
    <input id="imageSelect" name="Image1" class="ModalArea2" type="file" style="display:block;">       
    <center><label for="thumbage2" id="labelthumb2" style="margin-top:35px;">Choose Image</label></center>
    <button class="ModalButton2" id="uploadImageButton">Submit</button>
    <a class="ModalButton2" onclick="cancel2();">Cancel</a>
    <img id="imgURL" src="none"/>
</form>

Next is your JavaScript code. The comments will help you understand how it works. The main changes to it are

Added an event handler to the input button to select images. When the user selects an image using the input button, the onchange event fires and the <img> element's src attribute is filled with the image's data URL.

The second major change is to your AJAX request. I've changed it to .post, since it is simpler to read (at least to me) and inside that request, instead of sending the image itself, we are sending the image's data URL grabbed from the <img> tag's src attribute. This is sent in JSON format, so your PHP script handling the upload request should read the data in JSON format.

$(':file').change(function(){
    var file = this.files[0];
    var name = file.name;
    var size = file.size;
    var type = file.type;
    //Your validation
    //console.log(name);
});

$('#uploadImageButton').click(function(){
    var imgData = $('#imgURL').src;
    $.post({
        'upload.php', // Name of the PHP script which handles upload function
        {imageData:imgData}, // Use $_POST['imageData] to access the image data in your PHP script
        function data() {
            // whatever you want to do after the POST request is complete
            alert('Uploaded image');
        };

    });
});

$('#imageSelect').change(function(){
    readURL(this);
});

function readURL(input)
{
    if(input.files && input.files[0])
    {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#imgURL').attr('src', e.target.result);
        };
    }
    reader.readAsDataURL(input.files[0]);
}

You will need to edit your PHP script so that it reads the image's data URL in JSON format, and then saves the data URL as an image file. It should look like this:

<?php
    function upload()
    {
        if(isset($_POST))
        {
            // Get the image data URL
            $imageData = $_POST['imageData'];

            // Replace the spaces with plus signs
            $imageData = str_replace(' ', '+', $imageData);

            // Decode the image data
            $imageData = base64_decode($imageData);

            // Path where you want to save the image
            $uri = "/image.png";

            // Save the image data to an image file on the server
            file_put_contents($imageData, $uri);

        }
    }
?>
nvkrj
  • 1,002
  • 1
  • 7
  • 17