Home » Jquery » javascript – My ajax request fails, but did upload my post-Exceptionshub

javascript – My ajax request fails, but did upload my post-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

Why is my ajax request failing, and yet uploading my post.
how can i prevent the failure.

my ajax request code in:

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,
        success: (response) => {

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

        }
    }); 
}

my php custom rest api 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_type' => 'rate',
                'post_status' => 'publish',
                'post_title' => $title,
                'post_content' => $content,
                'meta_input' => array(
                    'rate_related_product' => $productId,
                    'rating_rate' => $rateNum
                )
              ));
        }else{
            die("Invalid product id");
        }
      }else{
        die("you must be logged in first");
      }
}

uploaded image of the failure:

the fail message in the console

If i add dataType:’text’, it does success but yet the endpoint returns all this details about the post i want to prevent. i want to remain just with the id that the method wp_insert_post() returns. and it comes in the end of the responseText in the ajax response.

appriciate all help.

How to&Answer:

well after many hours trying to fix this question i figured out the problem was in the post type name which was ‘rate’ probably its some saved post type from woocommerce or some other thing I use on my wordpress site. yet i changed it from ‘rate’ to anything else it worked completely fine.