简体   繁体   English

AJAX(JavaScript / PHP),FormData不发送

[英]AJAX (JavaScript / PHP), FormData not sending

I have an AJAX call ( not using JQuery), set up in the following way: 我有一个AJAX调用( 使用JQuery),它是通过以下方式设置的:

<script type="text/javascript">

var ajax = new XMLHttpRequest();
ajax.open("POST", "testing.php", true);

ajax.onreadystatechange = function(){
    if(ajax.readyState == 4 && ajax.status == 200){
        var returnVal = ajax.responseText;

        if(returnVal == "upload_success"){
            $('#display').html("WORKING!");
        }else{
            $('#display').html("NOPE");
        }
    }
}

</script>

And I pair it with the following test PHP: 我将其与以下测试PHP配对:

<?php

if(isset($_POST['username'])){
    echo "upload_success";
    exit();
}

?>

If I send the send the AJAX data in the following way: 如果我通过以下方式发送发送AJAX数据:

ajax.send("username=1");

then everything works perfectly. 那么一切都会完美地进行。 The inner HTML of the display div is set to the expected "WORKING!" display div的内部HTML设置为预期的“ WORKING!”。

But if I send the AJAX this way: 但是,如果我以这种方式发送AJAX:

var formData = new FormData();
formData.append("username", 1);
ajax.send(formData);

it sets the HTML to "NOPE" - meaning that the post variable $_POST['username'] was not set. 它将HTML设置为“ NOPE” ,这意味着未设置发布变量$_POST['username']

How do I check in my PHP function for this specific AJAX call? 如何为这个特定的AJAX调用检入PHP函数? I need to be able to differentiate between different AJAX calls. 我需要能够区分不同的AJAX调用。

I will eventually be appending a file to formData , but I was just testing this out first, as I have never used it before. 我最终将文件追加到formData ,但是我只是首先对其进行测试,因为我以前从未使用过它。

Thank you in advance. 先感谢您。

EDIT 1 - HTML 编辑1-HTML

<?php ... PHP from above goes here ... ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="robots" content="noindex, nofollow"/>

<title>Title</title>

<link href="../CSS/styles.css" rel="stylesheet" type="text/css" />
<link href="../CSS/UI/jquery-ui.min.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="../scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="../scripts/UI/jquery-ui.min.js"></script>

<script type="text/javascript"> ... AJAX script from above goes here ... </script>
</head>

<body>

<div id="wrapper">

  <form enctype="multipart/form-data" onsubmit="return false;">
    <input type="file" name="fileField" id="fileField" />
    <br/><br/>
    <input class="button" type="submit" value="Upload"/>
  </form>

  <div id="display"></div>

</div> <!-- End wrapper -->
</body>
</html>

I think you should use this way to upload file using formdata by ajax, 我认为您应该使用这种方式通过ajax使用formdata上传文件,

Javascript 使用Javascript

$(document).ready(function(){
      $('#id_of_form').on('submit',function(e){

          e.preventDefault();
    var formdata = new FormData($(this)[0]);      
    $.ajax({
        url: "test.php", 
        type: "POST",    
        data: formdata, 
        contentType: false,
        cache: false,      
        processData:false, 
    success: function(data){
        console.log(data);
        }
      });
  });

PHP (test.php) PHP(test.php)

if(isset($_FILES)){

    if(isset($_FILES["fileField"]["type"])){

        $validextensions = array("jpeg", "jpg", "png","JPEG","JPG","PNG");
        $temporary = explode(".", $_FILES["add-file"]["name"]);
        $file_extension = end($temporary);
        if ((($_FILES["add-file"]["type"] == "image/png") || ($_FILES["add-file"]["type"] == "image/jpg") || ($_FILES["add-file"]["type"] == "image/jpeg")
        ) && in_array($file_extension, $validextensions)) {

            $sourcePath = $_FILES['add-file']['tmp_name']; // Storing source path of the file in a variable
            $targetPath = "/photos/".$_FILES['add-file']['name'];
            move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
            /* you can add this taget path to database if required here */
            echo "file uploaded successfuly";
        } 
    }

}

If you wish to POST the form data you need to send the the correct header information. 如果您希望过POST表单数据,则需要发送正确的标题信息。

Here is sample of what I use, slightly modified to match your code sample. 这是我使用的示例,经过略微修改以匹配您的代码示例。

var ajax = new XMLHttpRequest();

var params = "username=test";

ajax.onload = function(aEvent)
{
    if (aEvent.target.responseText == 'upload_success')
    {
        alert('success');
    }
    else
    {
        alert('failed');
    }
};
ajax.onerror = function(aEvent)
{
    alert('failed');
};
ajax.open('POST', 'testing.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.setRequestHeader('Content-length', params.length);
ajax.setRequestHeader('Connection', 'close');
ajax.send(params);

It doesn't use any jQuery as there isn't any reason to use it. 它没有使用任何jQuery,因为没有任何理由使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM