0

I'm new to the Wordpress/PHP world. I want my page be able to communicate with an API that I build myself. So for this I have a form on my Wordpress Page using a HTML code widget which looks like this:

<html>
<body>
    <div>
        <form id="myform" action="submit_shortcode">
            <input type="text" id="input" placeholder="Input" required>
            <input type="submit" value="Enter">
        </form>
    </div>
</body>
</html>

And I have added this code to functions.php of the current theme:

function get_shortcode($sc) {
    $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";
        }
    }

    return;
}

add_action('submit_shortcode', 'get_shortcode');

But I can't see how to integrate the function with the form. When I submit my form, it sends me to mypage/submit_shortcode. How can I trigger the function get_shortcode when submitting the form?

PS: This "shortcode" has nothing to do with the Shortcode widget of Elementor

0

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

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

wp_register_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!

5
  • I see you've recommended the old admin-ajax.php rather than the modern REST API endpoint. Was there a reason for explaining with the older API rather than its replacement? admin-ajax.php is notorious for being difficult to debug as its only error message is a 0 whereas the REST API has pretty URLs and does a lot of the heavy lifting for you out of the box, as well as human readable error messages if things go wrong
    – Tom J Nowell
    Oct 16 at 1:22
  • Hi Tom - the OP posted an example with their function echoing the response. admin-ajax.php is pretty simple in that case... though I suppose that's possible with the REST API as well. I didn't include a nonce in the example either. Oct 18 at 18:51
  • The REST API wouldn't be much different, it's the same issue anybody building a shortcode faces
    – Tom J Nowell
    Oct 18 at 20:53
  • Hey, Sean, thank you for your answer but it's not working. With the parameters of my form described in the question, my page it's still leading me to /submit_shortcode. Do I need to alter something on the HTML form to make this trigger the Javascript/PHP script? When I change the tags to <form id="myform" onsubmit="myFunction()" method="POST"> I also get the POST to admin-ajax.php 400 (Bad Request) error
    – dsenese
    Oct 21 at 14:36
  • Hi @dsenese - If the form is still submitting for some reason, you'll need to do a little troubleshooting on why the jQuery function isn't interrupting it like it should. Are you seeing any errors in your console? Can you verify that jQuery and your script are being enqueued in your page? You could drop a console.log( 'THIS WORKED' ); right after the e.preventDefault(); and remove the rest. Use the browser console to look for that as a start. Oct 21 at 17:34
0

If you're comfortable with JavaScript, one way to approach what I think you're trying to do here would be to enqueue a JavaScript version of your function and then just call it from the form as an onSubmit attribute. So along the lines of:

Enter name:

and you've enqueued myFunction either in function.php or in a plugin:

function load_my_script() {
    wp_enqueue_script( 'myFunction', get_template_directory_uri() . '/js/myFunction.js');
}
add_action( 'wp_enqueue_scripts', 'load_my_script' );
1
  • Robert, I managed to try your solution and it kinda works. The script is called, but from the client side. The API is hosted in the same machine that the Wordpress (which is not my machine) and should be invisible to the user. When I submit the form, it's the Chrome that executes it. I want that the server connects to the API and then responds to the client.
    – dsenese
    Oct 20 at 17:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.