dqyknf4423 2019-07-31 00:01
浏览 39
已采纳

无法使用ajax将图像数据发送到php文件

I'm trying to upload an image to a database using AJAX and PHP. When I click on a form's submit button, ajax should send the image's information to a php page where it will be inserted into a database. Here's the form for the image upload:

<form enctype='multipart/form-data' class='img-form'>
<input type='hidden' name='size' value='1000000'>
<input type='file' name='image' id='file-input' class='profile-file'>
<input type='submit' name='upload' value='Upload Image' id='submit-input'>
</form>

Then, when I click on the form's submit button/input type, I send an ajax request by calling a function I put the request in:

$(".img-form-container").on("click", "#submit-input", function(e) {

    e.preventDefault();

    setImage();
}

Here's the setImage() function:

function setImage() {

    var sessid = "<?php echo $_SESSION['id'] ?>";

    $.ajax({
        url: 'includes/profile/set_image.php',
        type: 'POST',
        data: {sessid: sessid},
        success: function(data) {
            console.log("successful image update");
        },
        error: function(requestObject, error, errorThrown) {
            console.log(error);
            console.log(errorThrown);
        }
    });

}

Finally, in a separate file, I have the PHP code that recieves the AJAX request:

    $allowed = ['image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'];
        if (in_array($_FILES['image']['type'], $allowed)) {

            $sessid= $_REQUEST['sessid'];
            $target = "images/".basename($_FILES['image']['name']);
            $image = $_FILES['image']['name'];

            $q = "INSERT INTO profileimages (image, idUsers) VALUES ('$image', '$sessid')";
            $r = mysqli_query($conn, $q);
        } else {
            echo "<p class='errormsg'>Only JPG and PNG files are permitted.</p>";
    }

The problem is that I need the information needed for the $target and $image variables, but I don't know how to get it from javascript.

I already tried adding some of the PHP code into the JS function setImage() to send over to the PHP file, like so:

function setImage() {

<?php
    if (isset($_POST['upload'])) {

    $target = "images/".basename($_FILES['image']['name']);
    $image = $_FILES['image']['name'];

    }
 ?>

    var target = "<?php echo $target ?>";
    var image = "<?php echo $image?>";
    var sessid = "<?php echo $_SESSION['id'] ?>";

        $.ajax({
            url: 'includes/profile/set_image.php',
            type: 'POST',
            data: {sessid: sessid, image: image, target: target},
            success: function(data) {
                console.log("successful image update");
            },
            error: function(requestObject, error, errorThrown) {
                console.log(error);
                console.log(errorThrown);
            }
        });
});
}

but it gives me this error:

<b>Notice</b>:  Undefined index: image in <b>C:\xampp\htdocs\Real Website\profile.php</b> on line <b>127</b><br />
<br />
<b>Notice</b>:  Undefined index: image in <b>C:\xampp\htdocs\Real Website\profile.php</b> on line <b>128</b><br />

Basically, I need to get the information from the $target and $image variables ($_FILES['image'], etc.) into a javascript variable. Is there a way I can do this?

This system originally worked when I was building my site with plain PHP, but since I've added AJAX, I'm having trouble editing the code to make it work.

Let me know if it would help to add more code or if I made a mistake while posting the code in.

  • 写回答

1条回答 默认 最新

  • douweiluo0600 2019-07-31 01:03
    关注

    A good way to send a file to the server in js is to use the formData: follow this https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

    when you make

    <?php
    if (isset($_POST['upload'])) {
    
    $target = "images/".basename($_FILES['image']['name']);
    $image = $_FILES['image']['name'];
    
    }
    

    ?>

    you try to retrieve the absolute name of the file (here a string) then on the server you get this text as an image file that's why PHP cranks a undefined on

    $_FILES["image"]

    because the value received is a string and not a file.

    $_FILES['image']['name'] contains the original name of the uploaded file.

    Exple:

    var form = $('form.img-form')[0];
    var formData = new FormData(form);
    

    or specify exact data for FormData()

    var formData = new FormData();
    formData.append('size', '1000000');
    //Attach file
    formData.append('image', $('input[type=file]')[0].files[0]);
    

    now call ajax function

    $.ajax({
        url: 'includes/profile/set_image.php',
        type: 'POST',
        data: formData,
        success: function(data) {
            console.log("successful image update");
        },
        error: function(requestObject, error, errorThrown) {
            console.log(error);
            console.log(errorThrown);
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题