Home » Jquery » javascript – Why is the Ajax response adding the post details WP-Exceptionshub

javascript – Why is the Ajax response adding the post details WP-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

For some reason the below Ajax response is adding the post details, and that is not the intended application.

I want to use only the post id that returns in the end.
Furthermore I tried to figure out why is my Ajax returning the details in text type and not in JSON type as I wished for?.

This is the outcome of the response

Here is my JS code:

createRate(){
    var ourNewPost = {
        'title': $(".new-rate-title").val(),
        'content': $('.new-rate-body').val(),
        'rate': $('.custom-star:checked').val(),
        'productId': $('.submit-rate').data('id')
    }

    $.ajax({
        // adding nonce key to make wordpress know we are looged in and has the permision to do that method.
        beforeSend: (xhr) => {
            xhr.setRequestHeader('X-WP-Nonce', ylsData.nonce);
        },
        url: ylsData.root_url + '/wp-json/yls/v1/rating/',
        type: 'POST',
        data: ourNewPost,
        dataType:"text",
        success: (response) => {

            console.log('congrats');
            console.log(response);
        },
        error: (response) => {
            console.log('failed');
            console.log(response);

        }
    }); 
}

and here is my php route code:

add_action('rest_api_init','ylsRateRoute');


function ylsRateRoute(){
    register_rest_route('yls/v1','rating',array(
        'methods' => 'POST',
        'callback'=> 'createLike'
    ));

}

function createLike($data){
    if(is_user_logged_in()){
        $title = sanitize_text_field($data['title']);
        $content = sanitize_text_field($data['content']);
        $rateNum = sanitize_text_field($data['rate']);
        $productId = sanitize_text_field($data['productId']);
        if(get_post_type($productId) == 'product'){
            return wp_insert_post(array(
                'post_title' => $title,
                'post_type' => 'rate',
                'post_content' => $content,
                'post_status' => 'publish',
                'meta_input' => array(
                    'rate_related_product' => $productId,
                    'rating_rate' => $rateNum
                )
              ));
        }else{
            die("Invalid product id");
        }
      }else{
        die("you must be logged in first");
      }
}
How to&Answer:

So to answer your question about ‘why is my Ajax returning the details in text type and not in JSON`

It is because you are asking for an array to be returned (not JSON)

return wp_insert_post(array(...

If you want a response in JSON format use json_encode()

Answer:

Solved!, the problem was the name ‘rate’ of my custom post type.. probably one of my plugins uses the same name so it affects the outcome of the ajax.