简体   繁体   中英

stop javascript to redirect after alert() function

I am using javascript to check file size. If it is bigger than 1m it shows an alert and after that it redirect to index page.

I want know how to make it stay in the same page without redirect and without refresh and keep all page information inserted by user as it is.

This is the code:

if(fileInput.files[0].size > 1050000) {
    alert('File size is bigger than 1Mb!');
    return false;
}

the hole code:

var handleUpload = function(event){
    event.preventDefault();
    event.stopPropagation();

    var fileInput = document.getElementById('file');

    var data = new FormData();

    data.append('javascript', true);

    if(fileInput.files[0].size > 1050000) {
        //document.getElementById("image_id").innerHTML = "Image too big (max 1Mb)";
        alert('File bigger than 1Mb!');
        //window.location="upload.php";
        return false;
        }

    for (var i = 0; i < fileInput.files.length; ++i){

        data.append('file[]', fileInput.files[i]);

    }   

    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function(event){
        if(event.lengthComputable){
            var percent = event.loaded / event.total;
            var progress = document.getElementById('upload_progress');

            while (progress.hasChildNodes()){
                progress.removeChild(progress.firstChild);
            }
            progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
            document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
        }
    });
    request.upload.addEventListener('load', function(event){
        document.getElementById('upload_progress').style.display = 'none';
    });
    request.upload.addEventListener('error', function(event){
        alert('Upload failed');
    });
    request.addEventListener('readystatechange', function(event){
        if (this.readyState == 4){
            if(this.status == 200){
                var links = document.getElementById('uploaded');
                var uploaded = eval(this.response);
                var div, a;
                for (var i = 0; i < uploaded.length; ++i){
                    div = document.createElement('div');
                    a = document.createElement('a');
                    a.setAttribute('href', 'files/' + uploaded[i]);
                    a.appendChild(document.createTextNode(uploaded[i]));
                    div.appendChild(a);
                    links.appendChild(div);
                }
            }else{
                console.log('server replied with HTTP status ' + this.status);
            }
        }
    });
    request.open('POST', 'upload.php');
    request.setRequestHeader('Cache-Control', 'no-cache');
    document.getElementById('upload_progress').style.display = 'block';
    request.send(data);

}

window.addEventListener('load', function(event){

    var submit = document.getElementById('submit');
    submit.addEventListener('click', handleUpload);
});

the upload.php code with the html

<?php
foreach($_FILES['file']['name'] as $key => $name){
        if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
            $uploaded[] = $name;
        }
    }
    if(!empty($_POST['javascript'])){
        die(json_encode($uploaded));
    }
?>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="upload.js"></script>
</head>
<body>
        <div id="uploaded">
            <?php

            if (!empty($uploaded)){
                foreach ($uploaded as $name){
                    echo '<div><a href="files/',$name,'">',$name,'</a></div>';
                }
            }

            ?>
             </div>
<div id="upload_progress"></div>
        <div>
            <form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>

Thanks in advance

You may get rid of return it should work. Else, maybe you should try modals instead of alerts. They are more neat and pretty

Return false is preventing the redirect.

       var val = $("#inputId").val();      

        if (val >= 0 || val <=9)
        {           
            return true;
        }
        else
        {
            alert("Enter Digits Only");
            return false;
        }
     ```

Add event.preventDefault(); below the alert function.
This may help you to stay on the same page.

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