0

I am used to writing AJAX using the following structure, where I would end up sending variables to PHP

function requestToggle(type, user, elem) {
                    _(elem).innerHTML = 'please wait ...';
                    var ajax = ajaxObj("POST", "request_system.php");
                    ajax.onreadystatechange = function () {
                        if (ajaxReturn(ajax) == true) {
                            if (ajax.responseText == "request_sent") {
                                _(elem).innerHTML = 'OK Request Sent';
                            } else if (ajax.responseText == "unrequest_ok") {
                                _(elem).innerHTML = '<button onclick="requestToggle(\'request\',\'<?php echo $u; ?>\',\'requestBtn\')">Request Number</button>';
                            } else {
                                alert(ajax.responseText);
                                _(elem).innerHTML = 'Try again later';
                            }
                        }
                    }
                    ajax.send("type=" + type + "&user=" + user);
                }

The example that I want to work on is for a photo upload form and the PHP script is using the $_FILES array but I am unsure how I would go about passing this array to the PHP using AJAX.

Here is the PHP

<?php 
$result = "";
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
    $fileName = $_FILES["avatar"]["name"];
    $fileTmpLoc = $_FILES["avatar"]["tmp_name"];
    $fileType = $_FILES["avatar"]["type"];
    $fileSize = $_FILES["avatar"]["size"];
    $fileErrorMsg = $_FILES["avatar"]["error"];
    $kaboom = explode(".", $fileName);
    $fileExt = end($kaboom);
    list($width, $height) = getimagesize($fileTmpLoc);
    if($width < 10 || $height < 10){
        $result = "That image has no dimensions";
        echo $result;
        exit();
    }
    $db_file_name = rand(100000000000,999999999999).".".$fileExt;
    if($fileSize > 1048576) {
        $result = "Your image file was larger than 1mb";
        echo $result;
        exit();
    } else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
        $result = "Please only JPG, GIF or PNG images";
        echo $result;
        exit();
    } else if ($fileErrorMsg == 1) {
        $result = "An unknown error occurred";
        echo $result;
        exit();
    }
    $sql = "SELECT profilePicture FROM User WHERE username='$log_username' LIMIT 1";
    $query = mysqli_query($db_conx, $sql);
    $row = mysqli_fetch_row($query);
    $avatar = $row[0];

        //delete old pic if set
    if($avatar != ""){
        $picurl = "users/$log_username/$avatar"; 
        if (file_exists($picurl)) { unlink($picurl); }
    }
        //move file from temp folder to users folder
    $moveResult = move_uploaded_file($fileTmpLoc, "users/$log_username/$db_file_name");
    if ($moveResult != true) {
        $result = "File upload failed";
        echo $result;
        exit();
    }
    include_once("image_resize.php");
        //replace original file with resized version
    $target_file = "users/$log_username/$db_file_name";
    $resized_file = "users/$log_username/$db_file_name";
    $wmax = 400;
    $hmax = 600;
    img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
    $sql = "UPDATE User SET profilePicture='$db_file_name' WHERE username='$log_username' LIMIT 1";
    $query = mysqli_query($db_conx, $sql);
    mysqli_close($db_conx);
    //header("location: user.php?u=$log_username");
       $result = "upload_success";
        echo $result;

    exit();
}
?>

UPLOAD FORM

$avatar_form = '<div class="bhoechie-tab-content" id="uploadphoto">';
        $avatar_form .= '<center>';
        $avatar_form .= '<form id="avatar_form"" method="post" enctype="multipart/form-data">';
        $avatar_form .= '<h1>Change avatar</h1>';
        $avatar_form .= '<input type="file" name="avatar" required>';
        $avatar_form .= '<p><input type="submit" value="Upload"></p>';
        $avatar_form .= '<p id="status"></p>';
        $avatar_form .= '</form>';
        $avatar_form .= '</center></div>';

1 Answer 1

1

You can easily enough pass an array eg ajax.send("type=" + type + "&user=" + user + "&files=" + files);

Having not seen the rest of your code I can't provide a full answer, but I'm assuming you're somehow creating a files array in js and want to pass that to the php? If so, the variable 'files' would then be using in PHP like:

$files= $_REQUEST['files'];

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, the php $_FILES is directly accessing the array of the image from the upload form. I have updated my question with the code of the form. I was using POST to send the form contents to the PHP before I added ajax so the PHP is directly accessing it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.