• 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)
  • Plugin Author Shea Bunge

    (@bungeshea)

    Hi @mascot4m,

    You should be able to achieve a similar result using the WordPress AJAX API: https://help.codesnippets.pro/article/48-ajax-within-snippets

    Here’s an example of how you might convert your code into something more WordPress-compatible.

    The actual AJAX handler replaces your submit.php:

    $action_name = 'mascot4m_ajax_example';
    
    $handler = function () use ( $action_name ) {
    	check_ajax_referer( $action_name );
    
    	$url = add_query_arg(
    		array(
    			'first_name' => sanitize_title( $_POST['first_name'] ),
    		),
    		'https://my.fancy.website/call'
    	);
    
    	$response = wp_remote_get( $url );
    	$body = wp_remote_retrieve_body( $response );
    	wp_send_json_success( $body );
    };
    
    add_action( 'wp_ajax_' . $action_name, $handler );
    add_action( 'wp_ajax_nopriv_' . $action_name, $handler );

    I’ve also replaced your cURL request with wp_request_get, but you can use cURL just fine within WordPress if you prefer.

    As for the form itself, it’s probably simplest to use this as a shortcode:

    add_shortcode( 'submit_form', function () use ( $action_name ) {
    	ob_start();
    
    	?>
    	<div>
    		<div role="form">
    			<form id="form" method="POST" target="_blank">
    				<input type="hidden" name="action" value="<?php echo esc_attr( $action_name ); ?>" />
    				<input type="hidden" name="_ajax_nonce"
    				       value="<?php echo esc_attr( wp_create_nonce( $action_name ) ); ?>" />
    
    				<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()
    			const request = new XMLHttpRequest()
    
    			request.open('POST', data.ajaxurl, true)
    			request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    
    			request.onreadystatechange = () => {
    				if (XMLHttpRequest.DONE === request.readyState) {
    					if (200 === request.status) {
    						// 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'
    					}
    				}
    			}
    
    			const formData = new FormData(event.target)
    			request.send(formData)
    		})
    	</script>
    	<?php
    
    	return ob_get_clean();
    } );

    Though personally I’d probably just add the HTML as a content snippet instead.

Viewing 1 replies (of 1 total)
  • The topic ‘How to use PHP snippet in JavaScript’ is closed to new replies.