nimrod
nimrod

Reputation: 5732

How to transmit file from JavaScript via Ajax to PHP

I have a form where a user enters his name and selects a profile picture. These information and the avatar should be added to the mysql db via ajax and php.

HTML:

<form id="addWorkerForm" action="addWorker.php" method="post">
  Prename:<input type="text" name="prename" id="prename">
  Lastname:<input type="text" name="lastname" id="lastname">
  Image:<input type="file" id="file_input" name="file_input" >
</form>

Javascript:

var prename = $('#prename').val();    
var lastname = $('#lastname').val();    
var workerAvatar = $('#file_input').val();

var url = 'xyz/addWorker.php?prename=' + prename + '&lastname=' + lastname + '&avatar=' + workerAvatar;

$.ajax({
    url: url,
    dataType: 'json',
    async: false,
    success: function(data) {

    }
});

Is this the proper way to access the file in order to get its content in javascript? Furthermore, how can I access the file in the php file?

Upvotes: 2

Views: 451

Answers (3)

Jonline
Jonline

Reputation: 1747

I had a very similar problem recently, had my question answered (JQuery1.8.0: Sending files from forms via AJAX).

Long story short, you can send files via AJAX, but you need to use FormData() to do it because the file needs to be encoded into "multipart/form-data" which XmlHttpRequest has only recently become able to do (https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData).

Should be something like:

<button id="ajaxUploadSubmit"> Submit </button>
<script>
var data    = new FormData(document.forms.namedItem("workerAddForm"));

$( "#ajaxUploadSubmit" ).click(function() {
    var oReq    = new XMLHttpRequest();
    oReq.open("POST", "xyz/addwrker.php", true);
    oReq.setRequestHeader("X-Requested-With", "XMLHttpRequest"); //necessary for my application, might not be for you, I'm using CakePHP

    oReq.onload = function(oEvent) {   
        //whatever you want with oReq.responseText
        }
    oReq.send(data);
    };
</script>

Upvotes: 1

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

You can try this AjaxFileUpload plugin

Upvotes: 1

romo
romo

Reputation: 1990

No, you cannot upload a file by passing the value of the file to php unfortunately. You will either have to upload the file yourself or if you want to stay with the AJAX approach, use something like Plupload

What you can hope to get is a reference to the name of the file uploaded, and then store that in a <input type="hidden" value="XXXXXXXX.jpg"/> and pass that along as your workerAvatar. Then when you load the page, just reference that in the <img src="XXXXX.jpg"/>

Upvotes: 1

Related Questions