$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>Implementing an AJAX POST API call in wordpress|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Implementing an AJAX POST API call in wordpress

matteradmin9PV0评论

I'm attempting to make a POST request to an API. I've created a javascript file in my theme and i have tried two approaches so far:

Approach 1:

$.ajax({
        headers:{  
            "Content-Type":"application/json"               
        },   
        data:{
            "command": "request",
            "data": {
                "api_key": "my_api_key",
                "api_username": "my_api_username",
                "vendor_type": 2,
                "from": {
                  "from_name": "",
                  "from_lat": "",
                  "from_long": "",
                  "from_description": ""
                },
                "to": {
                  "to_name": customerLocation,
                  "to_lat": cityLat,
                  "to_long": cityLng,
                  "to_description": ""
                },
                "recepient": {
                    "recepient_name": name,
                    "recepient_phone": phone,
                    "recepient_email": email,
                    "recepient_notes": ""
                },
                "delivery_details": {
                  "pick_up_date": pickupdate,
                  "collect_payment": {
                    "status": false,
                    "pay_method": 0,
                    "amount": amountTotal
                  },
                                      "return": true,
             "note": " Sample note",
              "note_status": true,
              "request_type": "quote"
            }
            },
            "request_token_id": requestToken
            },
        type: 'POST',
        url:"/",
        success: function(response){
           console.log('success');
           console.log(response);
        },
        error: function(response){
            console.log('error');
            console.log(response);
        }
    });

The above code will not return a response payload from the API as any call will be blocked because of CORS(Cross-Origin Resource Sharing)

Approach 2

I then attempt to pass the endpoint to my functions.php file as follows:

//make api call to sendy
function foo() 
{
     echo '/';
}
add_action('wp_ajax_foo', 'foo' );
add_action('wp_ajax_nopriv_foo', 'foo' );

I declare an ajaxUrl variable in my theme's header.php file:

<script type="text/javascript">
var ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

Then format my Ajax call as shown below:

$.ajax({
        headers:{  
            "Content-Type":"application/json"               
        },   
        data:{
            "action": 'foo',
            "command": "request",
            "data": {
                "api_key": "my_api_key",
                "api_username": "my_api_username",
                "vendor_type": 2,
                "from": {
                  "from_name": "",
                  "from_lat": "",
                  "from_long": "",
                  "from_description": ""
                },
                "to": {
                  "to_name": customerLocation,
                  "to_lat": cityLat,
                  "to_long": cityLng,
                  "to_description": ""
                },
                "recepient": {
                    "recepient_name": name,
                    "recepient_phone": phone,
                    "recepient_email": email,
                    "recepient_notes": ""
                },
                "delivery_details": {
                  "pick_up_date": pickupdate,
                  "collect_payment": {
                    "status": false,
                    "pay_method": 0,
                    "amount": amountTotal
                  },
                                      "return": true,
             "note": " Sample note",
              "note_status": true,
              "request_type": "quote"
            }
            },
            "request_token_id": requestToken
            },
        type: 'POST',
        url:ajaxurl,
        success: function(response){
           console.log('success');
           console.log(response);
        },
        error: function(response){
            console.log('error');
            console.log(response);
        }
    });

But this is giving me a 400 (Bad Request) error.

I should mention that i have correctly set up my javascript file in the functions.php file:

wp_enqueue_script('sendy', get_template_directory_uri() . '/assets/js/sendy.js', array('jquery'));
wp_localize_script('sendy', 'wc_checkout_params', array('ajaxurl' => admin_url('admin-ajax.php')));

Would like therefore to request for assistance in setting up my POST endpoint.

I'm attempting to make a POST request to an API. I've created a javascript file in my theme and i have tried two approaches so far:

Approach 1:

$.ajax({
        headers:{  
            "Content-Type":"application/json"               
        },   
        data:{
            "command": "request",
            "data": {
                "api_key": "my_api_key",
                "api_username": "my_api_username",
                "vendor_type": 2,
                "from": {
                  "from_name": "",
                  "from_lat": "",
                  "from_long": "",
                  "from_description": ""
                },
                "to": {
                  "to_name": customerLocation,
                  "to_lat": cityLat,
                  "to_long": cityLng,
                  "to_description": ""
                },
                "recepient": {
                    "recepient_name": name,
                    "recepient_phone": phone,
                    "recepient_email": email,
                    "recepient_notes": ""
                },
                "delivery_details": {
                  "pick_up_date": pickupdate,
                  "collect_payment": {
                    "status": false,
                    "pay_method": 0,
                    "amount": amountTotal
                  },
                                      "return": true,
             "note": " Sample note",
              "note_status": true,
              "request_type": "quote"
            }
            },
            "request_token_id": requestToken
            },
        type: 'POST',
        url:"https://apitest.sendyit/v1/",
        success: function(response){
           console.log('success');
           console.log(response);
        },
        error: function(response){
            console.log('error');
            console.log(response);
        }
    });

The above code will not return a response payload from the API as any call will be blocked because of CORS(Cross-Origin Resource Sharing)

Approach 2

I then attempt to pass the endpoint to my functions.php file as follows:

//make api call to sendy
function foo() 
{
     echo 'https://apitest.sendyit/v1/';
}
add_action('wp_ajax_foo', 'foo' );
add_action('wp_ajax_nopriv_foo', 'foo' );

I declare an ajaxUrl variable in my theme's header.php file:

<script type="text/javascript">
var ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

Then format my Ajax call as shown below:

$.ajax({
        headers:{  
            "Content-Type":"application/json"               
        },   
        data:{
            "action": 'foo',
            "command": "request",
            "data": {
                "api_key": "my_api_key",
                "api_username": "my_api_username",
                "vendor_type": 2,
                "from": {
                  "from_name": "",
                  "from_lat": "",
                  "from_long": "",
                  "from_description": ""
                },
                "to": {
                  "to_name": customerLocation,
                  "to_lat": cityLat,
                  "to_long": cityLng,
                  "to_description": ""
                },
                "recepient": {
                    "recepient_name": name,
                    "recepient_phone": phone,
                    "recepient_email": email,
                    "recepient_notes": ""
                },
                "delivery_details": {
                  "pick_up_date": pickupdate,
                  "collect_payment": {
                    "status": false,
                    "pay_method": 0,
                    "amount": amountTotal
                  },
                                      "return": true,
             "note": " Sample note",
              "note_status": true,
              "request_type": "quote"
            }
            },
            "request_token_id": requestToken
            },
        type: 'POST',
        url:ajaxurl,
        success: function(response){
           console.log('success');
           console.log(response);
        },
        error: function(response){
            console.log('error');
            console.log(response);
        }
    });

But this is giving me a 400 (Bad Request) error.

I should mention that i have correctly set up my javascript file in the functions.php file:

wp_enqueue_script('sendy', get_template_directory_uri() . '/assets/js/sendy.js', array('jquery'));
wp_localize_script('sendy', 'wc_checkout_params', array('ajaxurl' => admin_url('admin-ajax.php')));

Would like therefore to request for assistance in setting up my POST endpoint.

Share Improve this question asked Jan 26, 2019 at 12:35 suosuo 1131 silver badge5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

You got the error 400 Bad Request because the Content-Type header is application/json:

$.ajax({
  headers:{
    "Content-Type":"application/json"
  },
  data: {
    ...
  },
  ...
});

And when the request content is a JSON string, the $_REQUEST['action'] which WordPress uses to identify the proper AJAX action (which is foo in your code) is not available (i.e. it's a NULL).

So based on your code, and with your second approach, you can just omit the headers part.

$.ajax({
  // No "headers" here.
  data: {
    ...
  },
  ...
});

UPDATE

You can use wp_remote_post() to make the external API request from the foo() function; example:

function foo() {
    if ( empty( $_POST['data'] ) ) {
        wp_die( 'Missing data' );
    }

    $post_data = wp_unslash( $_POST['data'] );
    $post_data['command'] = wp_unslash( $_POST['command'] );
    $post_data['request_token_id'] = wp_unslash( $_POST['request_token_id'] );

    $api_url = 'https://apitest.sendyit/v1/';
    $response = wp_remote_post( $api_url, array(
        // Set the Content-Type header.
        'headers' => array(
            'Content-Type' => 'application/json',
        ),
        // Set the request payload/body.
        'body'    => json_encode( $post_data ),
    ) );

    $res_body = wp_remote_retrieve_body( $response );
    echo $res_body;

    wp_die();
}

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far