使用jQuery对外部域的AJAX POST请求

I'm trying to do an AJAX POST request to an external domain from a post metabox in WordPress. I know that it's not possible to do it directly because of cross domain access errors. As far as I know it's also not possible to do it simply by using PHP code like

if ( isset ( $_POST( 'button_name' ) ) ) { .. }

since all the metaboxes are inside the wordpress post form.

So this is what I came up with:

  1. I use the wp_localize_script() function to make the php variables available in the js-file (this works). The localized variable is ajax_request_args.

  2. The javascript file looks like this:

    jQuery(document).ready(function($) {
    
        $('#button').click( function() {
    
            $.ajax({
                type: "POST",
                url: php_post.php,
                data: ajax_request_args,
                success: function(data) {
                alert(data["success"] + " " + data["code"]);
                },
                dataType: 'json'
            });
        });
    });
    
  3. The php_post.php looks similar to this:

    if (is_ajax()) {
    
        ...
    
        if (isset($_POST["arg_1"]) && !empty($_POST["arg_1"])) {
            $response = wp_remote_post( $external_url, array(
                'method' => 'POST',
                'body' => $args,
                'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded' ),
                'timeout' => 90,
                'blocking' => true
            ) ); 
    
        $return = $_POST; 
        $return['success_message'] = $response['success_message'];
        $return['code'] = $response['code'];
    
        $return["json"] = json_encode($return);
        echo json_encode($return); 
        }
    }
    

The AJAX request works without the POST request in the php file, for example when I set

$response['success_message'] = 'success';
$response['code'] = '1234';

and delete the wp_remote_post()part.

The POST request to the external domain also works when I call it directly using a button click like

<?php
if (isset( $_POST['test-maintenance-btn'])){

    ...

    $response = wp_remote_post( $external_url, array(
                'method' => 'POST',
                'body' => $args,
                'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded' ),
                'timeout' => 90,
                'blocking' => true
            ) ); 

}

?>
<form method="post">
    <input type="submit" id="test-btn" name="test-btn" value="<?php _e('Execute', 'textdomain'); ?>">
</form>

The weird thing is that it doesn't work in connection. The Javascript should post to the php file which posts to the external server and returns the result to the ajax post request.

When I try to do the wp_remote_post (even if I don't use the result) I always get "NetworkError: 500 Internal Server Error" in the console.

Could you help me find the problem and help me with the correct approach? Thanks in advance for your help.