How a HTML form can trigger a PHP function?

Question

It sounds like you want an AJAX request of some sort.

In your functions.php file, enqueue some JavaScript to handle the form.

wp_reigster_script( 'my-scripts', get_stylesheet_directory_uri() . '/[path to your scripts]/myscripts.js', array( 'jquery' ), '1.0', true );

See this link for reference.

Right under that, add a JavaScript variable for your AJAX URL.

wp_localize_script( 'my-scripts', 'data', array( 'ajax_url' => admin_url( 'admin-ajax.php' );

Reference on wp_localize_script and admin_url.

After the script is registered, add it to the queue so it can be loaded.

wp_enqueue_script( 'my-scripts' );

Under that, add in your code for getting the response from your API.

// your function, set up for AJAX
function get_api_response() {
    $response = wp_remote_get('http://localhost:9000/shortcode/'.$sc);

    if (is_array($response)) {
        $body = $response['body'];
        $data = json_decode($body);
        echo $data;
        if (! is_wp_error($data)) {
            echo "error";
        }
    }

    wp_die(); // make sure you do this
}
add_action( 'wp_ajax_get_api_response', 'get_api_response' );
add_action( 'wp_ajax_nopriv_get_api_response', 'get_api_response' );

Reference here.

And finally, in your JavaScript file (myscripts.js in this example), handle the form submission.

jQuery(document).ready(function($) {
    $('#myform').on('submit', function(e) {
        e.preventDefault(); // stop the form from submitting
        $.post(
            data['ajax_url'], // passed in from wp_localize_script
            {
                'input' : $('#input').val()
            },
            function( response ) {
                // do what you want to do here
                // the response will be what's echoed by the
                // get_api_response function
            }
        );
    });
});

If you don’t want to use AJAX, the “shortcode” you’re using will need to be made into a real shortcode and used on the page you’re posting your form to. Info on that here.

Your shortcode would then need to grab the $_POST values from your form and do something with them. In either case, make sure you sanitize all values coming from the outside world.

Hope this helps.

Cheers!

0
dsenese 2 months 2021-10-15T15:31:27-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse