Because you want to run JS code, using WordPress post
action handler will not give you the solution.
You will need to use ajax for that.
I have created a small example you can copy/paste.
<form method="post" class="myform">
<input type="hidden" name="action" value="add_foobar">
<input type="hidden" name="data" value="foobarid">
<input type="submit" value="Submit">
</form>
For our form I removed the action (no need for it because we will use ajax).
Also added a class for easier targeting.
($ => {
$('.myform').on('submit', e => {
// prevent form from submit
e.preventDefault();
// get current element (form)
const $this = $(e.currentTarget);
// get form values
const action = $this.find('[name="action"]').val();
const data = $this.find('[name="data"]').val();
// send the form data to our ajax action,
// and handle the response
// btSystemGlobals.ajaxUrl = http://localhost/timber/wp-admin/admin-ajax.php
// I have a property that contains the ajax endpoint
// you can copy the url but change it accordingly
$.ajax({
type: "post",
dataType: "json",
url: btSystemGlobals.ajaxUrl, // btSystemGlobals.ajaxUrl = http://localhost/timber/wp-admin/admin-ajax.php
data: {
action,
data
},
success: res => {
if (res.status) location.href = res.redirectTo;
else console.log(res);
}
});
});
})(jQuery);
The JS that will handle the request/response.
I used ajax to keep it simple but you can use axios for a modern approach, plus it will make the code much shorter and easier to read (I could add it if thats something you want).
add_action('wp_ajax_nopriv_add_foobar', 'add_foobar');
function add_foobar () {
// get and sanitize the passed data
$data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING);
// do what ever logic you need here with $data
// create the response
$res = [
'status' => true,
'data' => $data,
'redirectTo' => 'http://example.com/'
];
// return the response as json object
echo json_encode($res);
// die, stop any other code from running after this point
die;
}
And finally our action that will handle the data and return a response.
I didn’t use nonce to keep it as simple as possible but consider adding it (also something I can add if you want).
Using the code you provided I created this short example for handling JS code with ajax and a form.
If you ever need to run JS code for form submission and PHP logic you will need to use a XHR request, so ajax/axios/fetch would be the correct approach.