如何使用php和sql提交没有刷新的html表单?

时间:2015-07-01 18:03:14

标签: javascript php html ajax forms

这是一个上传图像的表单。它将url存储在sql数据库中,并将图像存储在文件夹中。 表单动作发送到postphoto.php,由postphoto表示。我的网站中删除了所有.php标记。该表单与PHP代码一起使用,但我需要一种方法来提交图像而不刷新页面。我的JavaScript没有提交表单。

HTML

<form action="postphoto" id="myForm" method="POST" enctype="multipart/form-data">
<input type="file" onchange="readURL(this);" name="profilepic" />
<br>
<img id="blah" src="#" alt="" height="300" width="400" />
<br>
<br>
<textarea class="form-control" name="description" rows="1" cols="40" placeholder="Description"></textarea>  
<br><input type="submit" class="form-control" id="sub" name="uploadpic" value="Upload">
</form>

    if (isset($_POST['uploadpic'])) {
            if (((@$_FILES["profilepic"]["type"]=="image/jpeg") || (@$_FILES["profilepic"]["type"]=="image/png") || (@$_FILES["profilepic"]["type"]=="image/gif"))&&(@$_FILES["profilepic"]["size"] < 1048576)) //1 Megabyte
      {
       $date = date("Y-m-d");
       $description = @$_POST['description'];
       $description = mysqli_real_escape_string($db_conx,$description);

       $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
       $rand_dir_name = substr(str_shuffle($chars), 0, 15);
       $rand_dir_name = mysqli_real_escape_string($db_conx,$rand_dir_name);

       mkdir("userdata/user_photos/$rand_dir_name");

       if (file_exists("userdata/user_photos/$rand_dir_name/".@$_FILES["profilepic"]["name"]))
       {
        echo @$_FILES["profilepic"]["name"]." Already exists";
       }
       else
       {
        move_uploaded_file(@$_FILES["profilepic"]["tmp_name"],"userdata/user_photos/$rand_dir_name/".$_FILES["profilepic"]["name"]);
        //echo "Uploaded and stored in: userdata/profile_pics/$rand_dir_name/".@$_FILES["profilepic"]["name"];
        $profile_pic_name = @$_FILES["profilepic"]["name"];
        $profile_pic_name = mysqli_real_escape_string($db_conx,$profile_pic_name);
        $img_id_before_md5 = "$rand_dir_name/$profile_pic_name";
        $img_id = md5($img_id_before_md5);
        $profile_pic_query = "INSERT INTO photos VALUES ('','test','$user','$date','$description','http://website.com/userdata/user_photos/$rand_dir_name/$profile_pic_name','no')";
        $profile_pic_query1 = $db_conx->query($profile_pic_query);
       }
    }
    }
    ?>

的JavaScript

$("#sub").click( function() {
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(), function(info) { $("#result").html(info); } );
clearInput();
});

$("#myForm").submit( function() {
return false;
});

function clearInput() {
$("#myForm :input").each ( function() {
   $(this).val('');
});
}

1 个答案:

答案 0 :(得分:-1)

您无需刷新即可提交Ajax调用

$('blah').on("change ", function (){
   $.ajax({ 
       url : submit_image.php,
       type: 'POST',
        data : {
            Imageurl: 'gdhsj.jpg',
            }
        success : function (){} 
       });
      });