How to use PHP snippet in JavaScript
-
I have HTML form with some JavaScript on submit. The Javascript calls PHP file
submit.php
. It works on my non-Wordpress site. I would like to use this in WordPress as well. I was thinking to use Code Snippets for the PHP, but I don’t know how to reference the PHP snippet from my Javascript.My form.html
<META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8"> <div> <div role="form"> <form id="form"method="POST" target="_blank"> <p> <input id="first_name" maxlength="40" name="first_name" type="text" /> </p> <input type="submit" name="submit" value="Send"> </form> <div> <div id="success-message" style="display:none;"> <p>Success</p> </div> <div id="failure-message" style="display:none;"> <p>Failure</p> </div> </div> </div> </div> <script> document.getElementById("lead-form").addEventListener("submit", function(event) { event.preventDefault(); var formData = new FormData(event.target); fetch("submit.php", { method: "POST", body: formData }) .then(response => { if (response.ok) { // Show the success message document.getElementById("success-message").style.display = "block"; document.getElementById("lead-form").style.display = "none"; } else { // Handle the error document.getElementById("failure-message").style.display = "block"; } }) .catch(error => { console.error("Error:", error); }); }); </script>
My submit.php
<?php $firstName = $_POST["first_name"]; $url = "https://my.fancy.website/call?"; $url .= "&first_name=" . urlencode($firstName); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response; ?>
How should I create the snippet correctly and reference it from Javascript?
Thanks
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘How to use PHP snippet in JavaScript’ is closed to new replies.