使用AJAX和PHP上传图片?

时间:2022-08-28 07:43:00

I am trying to upload image using PHP and AJAX.

我正在尝试使用PHP和AJAX上传图像。

Without AJAX, my image/file gets uploaded perfectly but when I try to using the AJAX so the page doesn't refresh, I get no image/file uploaded!

没有AJAX,我的图像/文件上传得很完美但是当我尝试使用AJAX以便页面不刷新时,我没有上传图像/文件!

Here is my code:

这是我的代码:

My PHP code, as I stated above, this works fine without AJAX:

我的PHP代码,如上所述,没有AJAX,这可以正常工作:

if (isset($_POST['u_id_im'])) {
if ($_FILES['fileField']['tmp_name'] != "") {   
    //$details = mysql_real_escape_string($_POST['details']);
        $newname = "$askeru23.jpg";
        move_uploaded_file($_FILES['fileField']['tmp_name'], "users_fav/".$_GET['id']."/$newname");
    }
}

HTML form:

<form id="imguploader" method="post" action="" enctype="multipart/form-data">
<label style="font-size:22px; color:#666; font-weight:bold; margin-top:50px; width:100%; height:50px; padding-top:50px;">Upload Photo</label><br  /><br />
<?php echo $usersupload; ?>
<input type="hidden" name="askeruim" id="askeru"  value="<?php echo $askeru23; ?>"/><br  />

<input type="hidden" value="<?php echo $u_id; ?>" name="u_id_im"  />

<input type="file" name="fileField" id="fileField" />

<input type="submit" name="submit" id="closethebox" class="submit"  value="UPLOAD" />
</form>

jQuery code:

$(function(){
    $('#imguploader').on('submit', function(e){
        // prevent native form submission here
        e.preventDefault();

        // now do whatever you want here
        $.ajax({
            type: $(this).attr('method'), // <-- get method of form
            url: $(this).attr('action'), // <-- get action of form
            data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
            beforeSend: function(){

            },
            success: function(data){
            }
        });
    });
});

As a side note, the AJAX code is within a document ready function.

作为旁注,AJAX代码在文档就绪函数中。

Could someone please advise on this?

有人可以就此提出建议吗?

Thanks

1 个解决方案

#1


0  

form action="" ... you need to set the url for ajax to send to, else its sending to a blank address.

form action =“”...你需要设置ajax发送到的URL,否则发送到空白地址。

<form id="imguploader" method="post" action="<?=basename($_SERVER['PHP_SELF'])?>" enctype="multipart/form-data">

#1


0  

form action="" ... you need to set the url for ajax to send to, else its sending to a blank address.

form action =“”...你需要设置ajax发送到的URL,否则发送到空白地址。

<form id="imguploader" method="post" action="<?=basename($_SERVER['PHP_SELF'])?>" enctype="multipart/form-data">