I'm recently trying to upload images without page refreshing. To do that I had identify ajax. My server side programing language is php. So I tried and success with it, but it's refreshing page. So I change that code after do research. But it shows error. Please help me with this.

This is my html form and it's file name is index.php

<form method="post" enctype="multipart/form-data" id="formUploadFile">
            <label>Select single file to upload:</label>
            <input type="file" name="files[]" multiple="multiple" />
            <input type="submit" value="Upload File" name="btnSubmit"/>
</form>

In the same index.php page I opened <script></script> tag and put following code.

<script>
    $(document).ready(function (e) {
        $('#formUploadFile').on('submit', function(e) {
            e.preventDefault();
            $.ajax({
                url: "up",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,
                success: function(data)
                {
                    //$('#loading').hide();
                    //$('#message').html(data);
                    console.log(data);
                }
            });
        });
    });
</script>

In above ajax post request it sends data to up.php file which is in the same directory. And it's code is this,

<?php
function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}

if(isset($_POST["btnSubmit"]))
{
    $errors = array();
    $uploadedFiles = array();
    $extension = array("jpeg","jpg","png","gif");
    $bytes = 1024;
    $KB = 1024;
    $totalBytes = $bytes * $KB;
    $UploadFolder = "UploadFolder";

    $counter = 0;

    foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
        $temp = $_FILES["files"]["tmp_name"][$key];
        $name = $_FILES["files"]["name"][$key];
        $unique_name=random_string(50);

        if(empty($temp))
        {
            break;
        }

        $counter++;
        $UploadOk = true;

        if($_FILES["files"]["size"][$key] > $totalBytes)
        {
            $UploadOk = false;
            array_push($errors, $name." file size is larger than the 1 MB.");
        }

        $ext = pathinfo($name, PATHINFO_EXTENSION);
        if(in_array($ext, $extension) == false){
            $UploadOk = false;
            array_push($errors, $name." is invalid file type.");
        }

        if(file_exists($UploadFolder."/".$name) == true){
            $UploadOk = false;
            array_push($errors, $name." file is already exist.");
        }

        if($UploadOk == true){
            //move_uploaded_file($temp,$UploadFolder."/".$name);
            move_uploaded_file($temp,$UploadFolder."/".$unique_name.'.'.$ext);
            array_push($uploadedFiles, $name);
        }
    }

    if($counter>0){
        if(count($errors)>0)
        {
            echo "<b>Errors:</b>";
            echo "<br/><ul>";
            foreach($errors as $error)
            {
                echo "<li>".$error."</li>";
            }
            echo "</ul><br/>";
        }

        if(count($uploadedFiles)>0){
            echo "<b>Uploaded Files:</b>";
            echo "<br/><ul>";
            foreach($uploadedFiles as $fileName)
            {
                echo "<li>".$fileName."</li>";
            }
            echo "</ul><br/>";

            echo count($uploadedFiles)." file(s) are successfully uploaded.";
        }
    }
    else{
        echo "Please, Select file(s) to upload.";
    }
}
else
    echo 'data not comes from ajax or html form';
?>

I tried this and even try after celan browser cache. Each time it show 'data not comes from ajax or html form' message in the console of browser. Which I put end of the above php file. In any case if it is ((!isset($_POST))).

Please guys help me to figure out what's wrong with this.

Dani AI

Generated

Short diagnosis: the client-side approach (FormData + AJAX) is fine — modern browsers do support uploading files via XHR/fetch. The reason your PHP is returning "data not comes from ajax or html form" is that up.php is checking isset($_POST['btnSubmit']), but when you build new FormData(form) the submit button's name/value is not included by default. The FormData constructor can accept an explicit submitter or you can append fields manually. (developer.mozilla.org)

Two simple fixes:

  • Server-side: stop relying on btnSubmit and detect an incoming upload via $_FILES or the request method. Example check (short):

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['files']['name'][0])) {
      // process uploaded files
    } else {
      echo 'No files received';
    }

    PHP populates $_FILES for multipart/form-data posts; use that rather than a submit-button sentinel. (php.net)

  • Client-side alternative: explicitly add a flag to the FormData before sending:

    var fd = new FormData(formElement);
    fd.append('btnSubmit', '1'); // now $_POST['btnSubmit'] will be present
    // send fd via AJAX (processData:false, contentType:false)

Hardening and debugging tips: check each $_FILES['files']['error'] value and only call move_uploaded_file() when UPLOAD_ERR_OK. Verify the upload folder exists and is writable and that upload_max_filesize / post_max_size in php.ini are large enough. Validate images with finfo or exif_imagetype() rather than trusting extensions, and check the return value of move_uploaded_file() for errors. The PHP manual has examples for these checks. (php.net)

A few final notes tied to the thread: is right that libraries like Dropzone make UI, progress and retries easier, but the underlying mechanism (FormData + XHR/fetch) is supported by browsers — your approach was correct, you only need to adjust the server-side detection or explicitly append the submit value and add the file/error checks. Also keep processData: false and contentType: false when sending FormData with jQuery. Use the browser Network tab to inspect the multipart payload and the server response while testing. (api.jquery.com)

Without reading your code (because it's a lot to process), file uploads are not possible through AJAX alone. Apparently, browsers believe there is a security vulnerability of some type and prohibit it from working. In the past, we used a workaround with iframes to mimic AJAX file uploads. Today, we use https://www.dropzonejs.com/ which has native AJAX support.

commented: thank you ! +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.