skip to Main Content

I have a function which is triggered via AJAX and will run the following when successful:

wp_send_json_success();

I am then doing a console log of the response and trying to detect if success = true:

.done(function (response) {

if( response['success'] == true ) {

    console.log('add to cart successful');

} else {
    
    console.log('add to cart failed');

}

Currently I am getting "add to cart failed" despite the output of response looking like it should be successful:

console.log(response);

// Response in the browser console:

{"success":true}

Am I detecting the true response incorrectly?

Update – PHP function the AJAX is triggering. Removed most code just as a test.

function fbpixel_add_to_cart_event_conversion_api() {

    echo 'hello world';

    wp_send_json_success();

    die();

}
add_action('wp_ajax_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\fbpixel_add_to_cart_event_conversion_api');
add_action('wp_ajax_nopriv_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\fbpixel_add_to_cart_event_conversion_api');
$.ajax({
    url: MyAjax.ajaxurl,
    type: 'POST',
    dataType: 'json',
    data: {
        action: 'fbpixel_add_to_cart_event_conversion_api',
        product_id: productId,
        variation_id: variationId,
    },
    })
    .done(function (response) {

    console.log(response);
    console.log(productId);
    console.log(variationId);
    console.log(response.success);

    if( response.success === true ) {

2

Answers


  1. Chosen as BEST ANSWER

    I should have pasted the entire code sorry. I had the wrong dataType set within $.ajax:

    Before

    $.ajax({
        url: MyAjax.ajaxurl,
        type: 'POST',
        dataType: 'html',
      })
    

    After

    $.ajax({
        url: MyAjax.ajaxurl,
        type: 'POST',
        dataType: 'json',
      })
    

  2. I always use dot notations to check the response returned from wp_send_json_success, and it always works. So use it like this:

    if( response.success === true ) {
    
        console.log('add to cart successful');
    
    } else {
        
        console.log('add to cart failed');
    
    }
    

    Give it a shot and let me know if you were able to get it to work!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search