I am making a newsletter integration with external api , and it works fine but on submit my entire page redirects to admin post php , i have tried to use it without action and adding ajax script to footer but don’t exactly know how to use my wp_remote method to send data without refreshing or redirecting my page
<?php
namespace SalesManago;
if (!defined('ABSPATH')) {
die;
}
/**
* Class ZH_SalesmanagoNewsletter
*/
class ZH_SalesmanagoNewsletter extends ZH_Salesmanago {
public function __construct() {
add_shortcode( 'sm_newsletter', array($this, 'newsletter_form' ));
add_action('admin_post_nopriv_newsletter', array($this, 'saveDataNewsletter'));
add_action('admin_post_newsletter', array($this, 'saveDataNewsletter'));
}
public function newsletter_form() {
return "
<div style='height: 300px; display: block; position: relative'></div>
<form id='ajax-newsletter-form' action='". esc_url( admin_url('admin-post.php') ) . "' method='post'>
<label for='email'>Email</label>
<input type='email' name='email' id='email' required>
<input type='hidden' name='action' value='newsletter'>
<input type='submit' name='sm-submit' value='>'>
</form>";
}
public function prepareDefaultNewsletterData()
{
$clientId = SALESMANAGO_CLIENTID;
$apiKey = SALESMANAGO_APIKEY;
$apiSecret = SALESMANAGO_APISECRET;
$data = [
'clientId' => $clientId,
'apiKey' => $apiKey,
'requestTime' => time(),
'sha' => sha1($apiKey . $clientId . $apiSecret),
];
return $data;
}
public function parseNewsletterData(){
$email = $_POST['email'];
$set[0]['contact'] = array(
'email' => $email,
);
return $set;
}
public function saveDataNewsletter(){
if (isset($_POST['sm-submit'])) {
$set = $this->parseNewsletterData();
$params = array(
"upsertDetails" => $set,
"owner" => SALESMANAGO_OWNER,
);
$data = array_merge($this->prepareDefaultSalesData(), $params);
$headers = [
'Content-Type' => 'application/json'
];
$result = wp_remote_post( SALESMANAGO_ENDPOINT .'/api/contact/batchupsertv2',
array(
'method' => 'POST',
'headers' => $headers,
'sslverify' => false,
'body' => json_encode($data)
)
);
}
}
}