0

I need to prevent the page redirected to the upload php when click upload button.

How can I do this in below code.

<form id="myForm"  action="http://example/DB_1/AccessWeb/file_upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload1">
</form>

<button onclick="myFunction()">  Upload
</button>

<script>

function myFunction(){

  document.getElementById("myForm").submit();


}
</script>
CodeDezk
  • 1,230
  • 1
  • 12
  • 40
  • can you clarify the question please? You do not wish for the form to POST to `file_upload.php` or redirect after processing the upload? – Professor Abronsius Aug 05 '17 at 14:46
  • Yes, I need to upload the file when click the upload button, but don't want to redirect file_upload.php, instead stay in the same page. – CodeDezk Aug 05 '17 at 14:49
  • two options as I see it: have the form POST to the same page ( means having the php code that handles the upload on the same page ) or in `file_upload.php` redirect using `header('Location: page.php');` where `page.php` is the name of the webpage with the form. Third option - use ajax – Professor Abronsius Aug 05 '17 at 14:51
  • I found similar is possible by ajax https://stackoverflow.com/questions/25983603/how-to-submit-html-form-without-redirection?noredirect=1&lq=1 but no idea how to do in above code – CodeDezk Aug 05 '17 at 14:53
  • Move your `file_upload.php` content into the script where the form is. Put it at the beginning and wrap it with the `if` statement that will check if the form has been submitted. – Anis Alibegić Aug 05 '17 at 15:08
  • I believe what you are looking for is FormData objects https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects – Robert Aug 05 '17 at 15:13
  • Thanks for the feedback, I will check it. – CodeDezk Aug 05 '17 at 15:16
  • Ramraider and ministry of chaps did really good answers. You can't simply submit the form and not have it redirect. You'll have to make an ajax call and prevent default on the submission button. – Altimus Prime Aug 05 '17 at 16:43

3 Answers3

2

A very basic, quickly written example of how to send a file - using ajax to the same page so that the user doesn't get redirected. This is plain vanilla javascript rather than jQuery.

The callback function can do more than print the response - it could, for instance, be used to update the DOM with new content based upon the success/failure of the upload.

<?php
    $field='fileToUpload';

    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){
        $obj=(object)$_FILES[ $field ];

        $name=$obj->name;
        $tmp=$obj->tmp_name;
        $size=$obj->size;
        $error=$obj->error;
        $type=$obj->type;

        if( $error==UPLOAD_ERR_OK ){
            /* 
                This is where you would process the uploaded file
                with various tests to ensure the file is OK before
                saving to disk.

                What you send back to the user is up to you - it could
                be json,text,html etc etc but here the ajax callback 
                function simply receives the name of the file chosen.
            */
            echo $name;
        } else {
            echo "bad foo!";
        }
        exit();
    }
?>
<!doctype html>
<html>
    <head>
        <title>File Upload - using ajax</title>
        <script>
            document.addEventListener('DOMContentLoaded',function(e){
                var bttn=document.getElementById('bttn');
                bttn.onclick=function(e){
                    /* Assign a new FormData object using the buttons parent ( the form ) as the argument */
                    var data=new FormData( e.target.parentNode );
                    var xhr=new XMLHttpRequest();
                    xhr.onload=function(e){
                        document.getElementById('status').innerHTML=this.response;
                    }
                    xhr.onerror=function(e){
                        alert(e);
                    }
                    xhr.open('POST',location.href,true);
                    xhr.send(data);
                };
            },false);
        </script>
    </head>
    <body>
        <form method='post' enctype='multipart/form-data'>
            Select image to upload:
            <input type='file' name='fileToUpload'>
            <input type='button' id='bttn' value='Upload' />
        </form><div id='status'></div>
    </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
1

Using JQuery AJAX methods will allow you to send and receive information to a specified url without the need to refresh your page.

You will need to include the JQuery library in your HTML page aswell. You can either download it and put it in your project folder or include an online library here, like so:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

So your form will now look like this:

<form id="myForm" method="post" >
        Select image to upload:
        <input type="file" name="fileToUpload" id="fileToUpload1">
        <input type="submit">
</form>

Then you can use this code to simply upload your image to your file upload page (tested and working for myself):

 <script>
$(document).ready(function ()
    {
        $("#myForm").submit(function (e)
            {
                //Stops submit button from refreshing page.
                e.preventDefault();

                var form_data = new FormData(this);

                $.ajax({
                    url: 'http://example/DB_1/AccessWeb/file_upload.php', //location of where you want to send image
                    dataType: 'json', // what to expect back from the PHP script, if anything
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: form_data,
                    type: 'post',
                    success: function (response)
                        {
                            alert('success');
                        },
                    error: function ()
                        {
                            alert('failure');
                        }
                });
            });
    });
 </script>
MinistryOfChaps
  • 1,458
  • 18
  • 31
1

use AJAX With jQuery

$("#myForm").submit(function() 
{

    var formData = new FormData(this);

    $.post($(this).attr("action"), formData, function(response) {
        //Handle the response here
    });

    return false;
});
Ali Faris
  • 17,754
  • 10
  • 45
  • 70