Birrel
Birrel

Reputation: 4834

AJAX (JavaScript / PHP), FormData not sending

I have an AJAX call (not using JQuery), set up in the following way:

<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

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

?>

If I send the send the AJAX data in the following way:

ajax.send("username=1");

then everything works perfectly. The inner HTML of the display div is set to the expected "WORKING!"

But if I send the AJAX this way:

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.

How do I check in my PHP function for this specific AJAX call? I need to be able to differentiate between different AJAX calls.

I will eventually be appending a file to formData, but I was just testing this out first, as I have never used it before.

Thank you in advance.

EDIT 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>

Upvotes: 0

Views: 723

Answers (2)

Krik
Krik

Reputation: 445

If you wish to POST the form data you need to send the the correct header information.

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.

Upvotes: 0

rut2
rut2

Reputation: 706

I think you should use this way to upload file using formdata by ajax,

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)

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";
        } 
    }

}

Upvotes: 1

Related Questions