简体   繁体   中英

PHP/Javascript - Check in JS if PHP file upload was successful

there. I have a page that makes a form containing file upload in a Bootstrap Modal.

The submit of the form is made on Javascript and I need to get a message about the file upload to show to the user before reloading the page. Here is the example:

HTML :

<div id="modal-insert-occurrence-form" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="modal-insert-occurrence-label" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="modal-insert-occurrence-label">Insert occurrence</h3>
    </div>
    <div class="modal-body">
        <form id="insert-occurrence-form">
            <fieldset>
                <label for="obs-occurrence">Obs</label>
                <textarea name="obs-occurrence" id="obs-occurrence" rows=3 class="span4"></textarea>
                <label for="image-occurrence">Screenshot</label>
                <input type="file" name="image-occurrence" id="image-occurrence" />
            </fieldset>
        </form>
    </div>
    <div class="modal-footer">
        <button id="modal-insert-occurrence-submit" class="btn btn-info" onClick="fileUp('insert-occurrence-form','ajax/upload.php');" >Insert</button>
        <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
    </div>
</div>

JavaScript :

function fileUp(form_id, action_url) {
    var form = document.getElementById(form_id);
    form.setAttribute("action", action_url);
    form.setAttribute("method", "post");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("encoding", "multipart/form-data");

    form.submit();
    //Need to show the message here!
    location.reload();
}

What can I do? Thanks.

Basically... you can't "Check in JS if PHP file upload was successful". Js is client side, php is server side. What you can do, since you already reload the page on form submission, is to check in php if the file was uploaded, and set a var in js with the answer. Something like:

   <script>
         var uploaded = <?php echo $uploadSuccess; ?>;
   </script>

But that's kind of messed up. A cleaner solution would be to send an ajax request to check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM