How can AJAX be utilized to send data from a PHP script to an external system without causing a page redirection?

To send data from a PHP script to an external system without causing a page redirection, AJAX can be utilized. AJAX allows for asynchronous communication between the client-side and server-side, enabling data to be sent without refreshing the page. By making an AJAX request from the PHP script to the external system, data can be transmitted and received in the background without disrupting the user experience.

// PHP script
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$external_system_url = 'https://external-system.com/api';
$ch = curl_init($external_system_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);

echo $response;