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 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效