Can’t retrieve formData sent through AJAX to insert new wordpress post, PHP sees values as blank

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.

Read More

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');

Related posts

1 comment

  1. you need to serialize the form data and then pass it to the php code. Do this to your var new_data assignment.

    var new_data = $(this).serialize()
    

    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.

    var $element = $(this);
    var formdata = new FormData();
    var totalFiles = $element.files.length;    
    
    if (totalFiles > 0) {
        for (var i = 0; i < totalFiles; i++) {
            var file = $element.files[i];
    
            formdata.append("FileUpload", file);
        }
    
        $.ajax({
            type: "POST",
            url: Url,
            data: formdata,
            contentType: false,
            processData: false,
            success: function (result) {
                // make the server return a array of file names that has been saved.
                //Post your other form elements data a this point with the filename array.
            },
            error: function (error) {
                console.log("File Upload Failure");
            }
        });       
    }
    

Comments are closed.