简体   繁体   中英

require_once() or AJAX causing php script to run twice

I'm making a step by step form that stores session variables as you follow the steps.

On one step I have a file upload that previews the image and shows an upload button, which when pressed calls a php script that needs to modify a $_SESSION variable, as well as echo the path to the uploaded file.

When I test it in my debugger without require_once('config.php') , it works exactly as I anticipate, showing the image and it's filename, however, for some reason when I include the config file, when I iterate through it in my debugger, it appears to run the php script twice, it correctly updates the session variable, but the filename isn't echoed anymore and the data is lost before it reaches the frontend.

I can't tell if the mistake is in the config.php file, or in the AJAX call, or maybe somewhere else where I'm missing.

The markup ('step4.php'):

<form method="post" action="step5.php">
    <span id="newfile">
        <input type="file" name="uploaded_file" id="imageupload" accept=".jpg, .jpeg, .png">
        <img alt="Preview Loading..." id="imagepreview">
    </span>
    <!-- The submit button is elsewhere before the end of the form, it acts as a next button -->
</form>

The javascript function:

$(document).on('click', '#uploadbutton', function(e) {
    e.preventDefault();
    //Grab upload elements and and file
    var uploadbutton = this;
    var uploader = document.getElementById('imageupload');
    var file = document.getElementById('imageupload').files[0];
    //Hide the upload elements
    uploadbutton.parentNode.removeChild(uploadbutton);
    uploader.parentNode.removeChild(uploader);
    //Make the form and pass it to server
    var formData = new FormData();
    formData.append('file', file); //$_FILES['file']
    $.ajax({
        url: 'uploadfile.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false
    })
    .done(function(data) {//Data is the relative path to the file
        //Hide the old content
        document.getElementById('newfile').innerHTML = '';
        //Show the new image
        var text = document.createTextNode('Uploaded File: '+data.replace('temp/', '', data));
        var br = document.createElement("br");
        var imgElement = document.createElement("IMG");
        imgElement.setAttribute('src', data);
        document.getElementById('newfile').appendChild(text);
        document.getElementById('newfile').appendChild(br);
        document.getElementById('newfile').appendChild(imgElement);
    })
    .fail(function() {
        alert("Error uploading the file. Hit refresh and try again.");
    });
});

'uploadfile.php': (the one that my debugger shows gets executed twice...)

<?php
//require_once('config.php'); //THE PROBLEM?

if($_FILES) {
    //Get the uploaded file information
    $name_of_uploaded_file = $_FILES['file']['name'];
    //Actually upload the file to the server!
    $upload_folder = 'temp/'; //Make a file named temp
    $path_of_uploaded_file = $upload_folder.$name_of_uploaded_file;
    $tmp_path = $_FILES["file"]["tmp_name"];

    if(is_uploaded_file($tmp_path)) {
        copy($tmp_path,$path_of_uploaded_file);
        $_SESSION['step4filepath'] = $path_of_uploaded_file;
        echo $path_of_uploaded_file;
    }   
}

?>

'config.php': the one that screws stuff up when it's included

<?php
session_start();

//Initialize session data
if(empty($_SESSION)) {
    if(!isset($_SESSION['step4filepath'])) {
        $_SESSION['step4filepath'] = '';
    }
}

//Update session data
if($_SERVER['REQUEST_METHOD'] === 'POST') {

    if($_SESSION['currentPage'] == 4) {
        //input for step 4, we just want filename if they submit the form
        $_SESSION['step4filepath'] = $_POST['step4filepath'];
    }
    //Enable us to hit the back button!
    header("Location: " . $_SERVER['REQUEST_URI']);
}
?>

Totally lost on this.

May be this? Why that line is there on your config file?

header("Location: " . $_SERVER['REQUEST_URI']);

It looks like config.php is replacing the value of $_SESSION['step4filepath'] with $_POST['step4filepath'], rather than leaving it as $path_of_uploaded_file.

EDIT

As mentioned elsewhere, header() will be causing a reload. My answer is irrelevant as config.php is called before the var is set.

Solution 1

Replace

$(document).on('click', '#uploadbutton', function(e) { 

To

$(document).off('click').on('click', '#uploadbutton', function(e) {

Solution 2: See below sample code

$(document).on("click", "#someID", function(e) {
    $(this).attr("disabled","disabled");
    // Disabling the input stops the event from firing multiple times.
    var targetObj = $(this);
    // targetObj can be used within the $.POST function, not $(this)
   var myVariable = "Hello world";
   $.post("/DoSomethingAJAXY.php", { variable1: myVariable },
   function(data, status){
    if (status == "success") {
        // Do something
    }
    $(targetObj).removeAttr("disabled");
    // Re-enable the event input trigger
});
}

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