简体   繁体   中英

Why Ajax successful response is not accessible

I have a simple jQuery Ajax post call that works. A product is generated & added to cart. I did find many answers but none seem to apply here.

But I cannot access the response content (post id) itself in my JS code. In the code below - in comments - few more trials that I tried to no avail.

What am I missing??

Ajax post request:

    jQuery.post(
                ts_woo.ajax_url, 
                {'action': 'do_ts_woo',
                 'order': orderfilename, 
                 'tilesize': globalTileSize, 
                 'board': urlAtts,
                 'table': table
                },
                function(data) {
                   console.log("type of response="+ typeof data + " string=" + data); // data is a string but does not display it.
                   var response = jQuery.parseJSON(JSON.stringify(data));

                   console.log("do_ts_woo. Got id="+response); // undefined & so is response.id 
                      pid = response;
                      if(pid>0){
                         //pid = response['id'];
                         console.log("do_ts_woo. SUCCESS response="+pid);
                 alert('Add to cart: ' + response.id);
                         ts_iframe(shopdomain + "/cart/?add-to-cart="+pid);
                      } else {
                        // ALWAYS end up here while all was successful...
                         console.log("do_ts_woo. FAILURE response="+response.id);
                      }
                      return false;
                }
    ).done(function(response) {/* alert( "done:"+response );*/})
     .fail(function(msg) {alert( "error msg="+msg );})
     .always(function(response) {
//console.log("do_ts_woo. ALWAYS respone.id="+response.id); SAME PROBLEM HERE
     });

Here is the PHP code

    $pid = generate_woo_product("ts-".date("Ymd_His"), $product_price[1], $pimage, $allTable); // PRODUCT is GENERATED

    error_log("pid =". $pid);
    if ($pid > 0){
         error_log ("product pid=".$pid." generated successfully"); 
         echo $pid; 
    //tried wp_send_json_success($pid); 
    //tried wp_send_json_success(array('success' => true, 'id' => $pid));
    } else error_log("do_ts_woo: FAIL generate_woo_product returned".$pid);
    wp_die();   

Please, try to use

wp_send_json(['pid' => $pid]);
exit;

instead of echo

And then access your $pid in js with

data.pid 

Please, use data.pid without JSON.parse , cause data, in this case, needs to be object

If not - please, consider adding this code to you functions.php

add_action( 'rest_api_init', 'salient_child_rest_api_init' );
function salient_child_rest_api_init() {
    register_rest_route(
        'namespace/v1',
        '/example',
        [
            'methods'  => WP_REST_Server::CREATABLE,
            'callback' => 'salient_child_process_example_endpoint',
        ]
    );
}

function salient_child_process_example_endpoint() {

    // your logic ...

    $data = [
        'pid' => 1
    ]; // example data for testing if it is working

    return new WP_REST_Response( $data, 200 );
}

And change your jQuery.post with this

jQuery.post(
        {
            url: `${document.location.origin}/wp-json/namespace/v1/example`,
            data: {
                'action': 'do_ts_woo',
                'order': orderfilename,
                'tilesize': globalTileSize,
                'board': urlAtts,
                'table': table
            },
            xhrFields: {
                withCredentials: true
            }
        })
        .done(function (data) {
            const pid = data.pid;

            if (pid > 0) {
                console.log("do_ts_woo. SUCCESS response=" + pid);
                alert('Add to cart: ' + response.id);
                ts_iframe(shopdomain + "/cart/?add-to-cart=" + pid);
            } else {
                console.log("do_ts_woo. FAILURE response=" + response.id);
            }

            return false;
        })
        .fail(function (msg) {
            alert("error msg=" + msg);
        })
        .always(function (response) {

        });

If not - maybe there are PHP warnings modifying your response output with enexpected messages and breaking your response data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM