I’m sending formData through jQuery.ajax(), however the PHP function that is processing all this can’t properly retrieve and recognize the DATA being sent. I’ve went through many questions on stackoverflow and also tried this in many different ways all to no avail and finally gave up.
This is all done in WORDPRESS.
I can’t use serialize because I’m also sending files, but I left them out below for the sake of simplicity.
This is the simplified version of the form:
<form id="newForm" method="post" enctype='multipart/form-data'>
<div>
<label>Title</label>
<input name="title" type="text" value=""/>
</div>
<div>
<label>Content</label>
<input name="content" type="text" value=""/>
</div>
<button type="submit" id="submit_button">SUBMIT</button>
</form>
This is the jQuery:
jQuery(document).ready(function(){
$('#newForm').submit(function(e){
e.preventDefault();
var new_data = new FormData($(this)[0]);
$.ajax({
url:ajaxurl,
type: "POST",
data: {
'action': 'upload_function',
new_data //I've tried new_data: new_data
},
cache:false,
processData:false,
dataType: 'json', //tried not sending it as json dataType, still didn't work
success:function(response){
console.log(response);
if(response.success == 1){
alert("Post inserted");
}else{
alert("Post not inserted");
}
},
error:function(){
alert("Ajax request hasn't passed");
}
});
});
});
This is the PHP that handles the post insert(it’s getting called properly, I’ve checked by inserting static values in post title and content), I left out the nonce and other stuff for the sake of simplicity:
function upload_function(){
$json_result=array();
$json_input=$_POST['new_data'];
$post_vars=json_decode($json_input,true);
$submit_post_data = array (
'post_title' => $post_vars['title'],
'post_content' => $post_vars['content'],
'post_status' => 'draft'
);
$post_id = wp_insert_post($submit_post_data);
if($post_id){
$json_result['success']=1;
}else{
$json_result['success']=0;
}
wp_send_json($json_result);
exit();
}
add_action('wp_ajax_upload_function','upload_function');
you need to serialize the form data and then pass it to the php code. Do this to your
var new_data
assignment.EDIT 1: As you stated you have files you need use FormData object to pass the files to sever in ajax. refer the code below.