0

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>
4
  • can you please post HTML DOM ? Commented Feb 28, 2015 at 4:43
  • 1. Check what actually was sent (network tab in chrome dev toolbar) 2. var_dump($_POST); Commented Feb 28, 2015 at 4:52
  • var_dump gives the following: array(1) { ["------WebKitFormBoundarylltcGU2lxnTiY4FC Content-Disposition:_form-data;_name"]=> string(61) ""username" 1 ------WebKitFormBoundarylltcGU2lxnTiY4FC-- " } Commented Feb 28, 2015 at 4:54
  • Or, is there some other way I can send files (images) from the form to the PHP, without having to use a FormData object? Like ajax.send("username=something&file=" + file); Commented Feb 28, 2015 at 5:11

2 Answers 2

1

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

}
Sign up to request clarification or add additional context in comments.

4 Comments

I wanted to stay away from JQuery AJAX. I've never used it before. How, in my PHP, can I upload the file to a specific folder on the server? Likewise, how can I send a string from the PHP back to the success: function(data)?
yes f'crs, you don't need to send back from success, you can handle this in single PHP file. check my next update please
This works well enough. I'm handling the file upload in the PHP a little differently, but everything else is working alright. Any idea why this is working with the JQuery AJAX call, and not what I had before? Either way, I'll accept this one since it worked. But would still like to figure the other one out.
this is not a javascript answer... it is a JQUERY answer
0

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.

3 Comments

sending a simple string, or even dynamic variables, is not a problem. I am trying to use FormData Objects because I need to also send a file (image). How do I do that with this method?
Sorry about that, I read the first few lines and saw POST and no headers being set, and then skimmed the rest of your post, as well as the replies. I didn't realize the real problem you needed help with was at the end of your post. I'll take another look and edit my post to try and get you a better answer.
use ajax.responseText or view your response data in console.log(JSON.stringify(ajax)) inside of ajax.onload

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.