Javascript 表单提交以使用ajax上载文件和其他字段

Javascript 表单提交以使用ajax上载文件和其他字段,javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,我已经测试了这里的每个问题,也在谷歌上搜索了很多,但没有发现有用的东西 这是我的HTML: <div id="createarea"> <form id="createform" action="index/create/createcontrols.php" method="post" enctype="multipart/form-data"> <input id="title" type="text" name="title" size="

我已经测试了这里的每个问题,也在谷歌上搜索了很多,但没有发现有用的东西

这是我的HTML:

<div id="createarea">
    <form id="createform" action="index/create/createcontrols.php" method="post" enctype="multipart/form-data">
      <input id="title" type="text" name="title" size="30" value="Title"><br><br>
      <input id="description" type="text" name="description" size="30" value="Description"><br><br>
      <input id="keywords" type="text" name="keywords" size="30" value="Keywords"><br><br>
      <input id="link" type="text" name="link" size="30" value="Link"><br><br>
      <input id="file" type="file" name="file"><br><br>
      <input id="submit" type="button" name='submit' value="Create" onclick="myFunction()">
    </form>
    <div id="createformresults">
    </div>
</div>  
我的PHP代码:

 <?php





$db=mysql_connect('','','') or die(mysql_error());
mysql_select_db("", $db) or die(mysql_error());




$title = $_POST["title"];
$description = $_POST["description"];
$keywords = $_POST["keywords"];
$link = $_POST["link"];
        $image=$_FILES["file"]["name"];


        $allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {

    if ($_FILES["file"]["error"] > 0) {

        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";

        }

        else {

                if (file_exists("temp/" . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists. ";
                }

            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "temp/" . $_FILES["file"]["name"]);
            }
        }
}

else { 

    echo "Invalid file"; 

             }


            $qry="insert createcontent values('null','$title','$description','$keywords','$link','$image')";

            $res=  mysql_query($qry) or die(mysql_error());

            if(mysql_affected_rows()==1) {

                    echo "Success"; 

            }  

else {

    echo "Not Saved";                    

}



 ?> 

我将使用
FormData
完成此任务

以下是使用FormData的代码示例:

$(function () { //On dom ready:

$("#createform").submit(function (e) { //will be triggered on submit:

     e.preventDefault();

     if( window.FormData !== undefined ) 
     //make sure that we can use FormData ie>9, chrome > 7, opera > 12 safari >5, android > 3  gecko mobile > 2, opera mobile >12 <- wil support XHR too
     {

         var formData = new FormData($('#createform')[0]); // use "[0]" <- important
    // you can append aditional values (regular text): formData.append("be","some value");
         $.ajax({
                 url: 'index/create/createcontrols.php',  //Server script to process data
                 type: 'POST',
                 data: formData,
                 xhr: function() {  },
                 success: function(response){ $("#createformresults").text("SUCCESS"); },
                 error: function (jqXHR, textStatus, errorThrown) { $("#createformresults").text(errorThrown); },
                 //Options to tell jQuery not to process data or worry about content-type.
                 cache: false,
                 contentType: false,
                 processData: false
          });
      } else {

          //Fallback

      }

      return false;
});

});
$(dom就绪时的函数(){//
$(“#createform”).submit(函数(e){//将在提交时触发:
e、 预防默认值();
if(window.FormData!==未定义)

//请确保我们可以使用FormData ie>9、chrome>7、opera>12 safari>5、android>3 gecko mobile>2、opera mobile>12ajax根本不支持文件上传。不过,有一些解决方法。其中之一是名为Iframe Post Form的jQuery插件,请阅读以下内容:

显然,您必须在
form
标记中指定url操作和
enctype=“multipart/form data”

希望这有帮助!

终于完成了

将此源添加到x.html

//Program a custom submit function for the form
$("form#data").submit(function(event){

  //disable the default form submission
  event.preventDefault();

  //grab all form data  
  var formData = new FormData($(this)[0]);

  $.ajax({
    url: 'formprocessing.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (returndata) {
      alert(returndata);
    }
  });

  return false;
});

用户名:
个人资料图像:
显示图像:
并将其保存到一个PHP文件(formprocessing.PHP):

我是在这个链接的帮助下完成的

为什么在
myFunction()的内部调用onload?出现了什么错误?@13ruce1337内部没有加载function@mega6382我在
$(function(){})引用JQuery onload;
@MjrKusanagi没有错误,如果我添加了任何
警报()
或成功之外的任何其他代码。不工作我添加了
document.getElementById('createarea')。innerHTML=“成功”
此行成功,但不起作用。您需要向我们展示更多-php代码-错误是什么。请确保使用我编辑的代码,并告诉我们您遇到了什么错误。我已经测试了您编辑的代码。成功块起作用,但数据库中没有添加任何内容。让我们来看看
$('form').iframePostForm({
      complete : function (response) {
           $('#createarea').text("SUCCESS");
    }
});
//Program a custom submit function for the form
$("form#data").submit(function(event){

  //disable the default form submission
  event.preventDefault();

  //grab all form data  
  var formData = new FormData($(this)[0]);

  $.ajax({
    url: 'formprocessing.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (returndata) {
      alert(returndata);
    }
  });

  return false;
});
$id = $_POST['id'];
$username = $_POST['username'];
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];