I’m developing a WordPress theme and I have a PHP function that is supposed to handle and asynchronous request that gives the server both JSON and an image. My form (for readability, stripped of a bunch of inner HTML) looks like
<form method="POST" action="member-update" enctype="multipart/form-data" id="member-form">
9">
<input type="text" name="fullname" value="">
<input type="text" name="title" value="">
<textarea rows="4" name="bio" form="member-form"></textarea>
<input type="text" name="sord" value="">
<input type="file" name="pic">
<input type="hidden" name="memberAction" value="" />
</form>
and my JavaScript for making the AJAX request is
jQuery('.member-update-button').click( function() {
var parentForm = jQuery(this).closest('form');
var postData = parentForm.serializeArray();
jQuery.post( ajaxurl,
{'action': 'member_update', 'formStuff' : postData},
function(response) { alert('Got this from the server: ' + response); }
);
});
and my PHP function that, through a WordPress hook, handles the request starts out like
function member_update ( )
{
// there must be a more elegant way of getting those values out ....
$name = $_POST['formStuff'][0]['value'];
$title = $_POST['formStuff'][1]['value'];
$bio = $_POST['formStuff'][2]['value'];
$sord = $_POST['formStuff'][3]['value'];
$targetFileName = basename($_FILES['pic']['name']);
$targetFileNameAndPath = 'assets/' . $targetFileName;
I’m getting values out of the $_POST['formStuff']
array, but I am getting nothing for the $_FILES['pic']['name']
. Any idea what I’m doing wrong?
You need to use an instance of
FormData
.Make following changes in your code.
Add id attribute in your html
Changes in js code
Finally changes in php function