Dave
Dave

Reputation: 1

Getting ajax POST php

I am trying to get an ajax file uploader to work, and to pass some additional form data to php. The php script is able to get $_FILES['fileToUpload'] but I'm getting Undefined Index for $_POST["fname"];

PHP

if(isset($_FILES['fileToUpload'])){

$fname = $_POST["fname"];

$name = htmlentities($_FILES['fileToUpload']['name']);
}

JAVASCRIPT

var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "uploader.php");
xhr.send(fd);

HTML

<form id="form1" name="form1" enctype="multipart/form-data">
                <div id="user">
                    <input type="text" id="fname" name="fname" />
                </div>
                <div id="fileInfo">
                    <div id="fileName"></div>
                    <div id="fileSize"></div>
                    <div id="fileType"></div>
                </div>
                <div class="row"></div>
                <div class="row">
                    <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
                </div>
                <div class="row">
                    <input type="button" onclick="uploadFile()" value="Upload" />

Upvotes: 0

Views: 136

Answers (1)

lafuzz
lafuzz

Reputation: 74

Because your using ajax to send the Post, you need to do something like

fd.append("fname", document.getElementById('fname').value);

Otherwise, there's nothing to tell the 'onclick' to send your fname input field.

Input fields are only sent if you use a submit button.

Upvotes: 1

Related Questions