• Hi, I’m am a developper and I wonder how to submit my form. I’ve created it in my function.php file that is linked to my template page with a shortcode. The form works, I can fill it, but I can’t verify if it works, I don’t know why. I’m new to wordpress AND ajax and I don’t understand how wordpress manages it. Also, in my template, I have created two script tags (one for the phone number input and the second one to verify the form: the one I think it doesn’t work)). So, my form is visible, fillable, but I try to verify the submission and to save my data in a data table I have also created. Here is what I have done:

    functions.php:

    function registration_form() {
            ob_start();?>
            <form action="" id="registration_form" method="post">
                    <input class="gauche" name="nom" type="text" placeholder="Nom*" required><input class="droite" name="prenom" type="text" placeholder="Prénom*" required>
                    <input name="mail" type="email" placeholder="E-mail" required>
                    <input name="login" type="text" placeholder="Identifiant*" required>
                    <input class="gauche" name="mdp" type="password" placeholder="Mot de passe*" required><input class="droite" name="mdp2" type="password" placeholder="Confirmez le mot de passe*" required>
                    <input name="societe" type="text" placeholder="Société*" required>
                    <input name="fonction" type="text" placeholder="Fonction*" required>
                    <input name="adresse" type="text" placeholder="Adresse*" required>
                    <input name="complement" type="text" placeholder="Complément d'adresse">
                    <input name="ville" type="text" placeholder="Ville*" required>
                    <label id="pays">Pays <span style="color: red;">*</span></label>
                    <input class="gauche" name="code" type="text" placeholder="Code postal*"><select class="droite" name="pays" required>
                            <option value="Afghanistan">Afghanistan</option>
                            <option value="Åland Islands">Åland Islands</option>
                            <option value="Albania">Albania</option>
                           </select>
                    <label>Téléphone <span style="color: red;">*</span></label><br>
                    <input id="phone" style="margin-top:5px;" name="telephone" type="text" required><br>
                    <input class="bouton_submit" type="submit" name="user_send_registration" value="S'inscrire" style="background-color:#3498db; color:white; width:100px; height:35px;">
            </form>
            <?php
            return ob_get_clean();
    }
    add_shortcode( 'register', 'registration_form' );
    
    

    my wordpress page:

    <!--my shortcode-->
    [register]
    
    <script>
    function getIp(callback) { fetch('https://ipinfo.io/json?token=<your token>', { headers: { 'Accept': 'application/json' }}).then((resp) => resp.json()).catch(() => { return { country: 'fr',};}).then((resp) => callback(resp.country));}
       const phoneInputField = document.querySelector("#phone");
       const phoneInput = window.intlTelInput(phoneInputField, { preferredCountries: ["fr", "us", "uk"], utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",});
    </script>
    <script>
    $("#registration_form").validate({
    rules:{
       nom:{required:true}, 
       prenom:{required:true}, 
       mail:{required:true, email:true, emailExt:true}, 
       login:{required:true}, 
       mdp:{required:true}, 
       mdp2:{required:true}, 
       societe:{required:true}, 
       fonction:{required:true}, 
       adresse:{required:true}, 
       complement:{required:false}, 
       ville:{required:true}, 
       code:{required:true}, 
       pays:{required:true}, 
       telephone:{required:true, minlength: 10, maxlength: 15, number: true} 
    }, 
    submitHandler: function(form) {
        if(isReqInprogress){
            return;
           }
            $.ajax({
            url:"/wp-content/themes/themename/process.php",
            type: "post",
            data:$('#registration_form').serialize(),           
            dataType:"JSON",
            success: function(response) {
                alert("Your message has been received and we will be contacting you shortly to follow-up.");
                isReqInprogress = false;
            }
        });
    }
    });
    </script>

    And then my process.php file:

    <?php
    define('BLOCK_LOAD', true);
    require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
    require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
    $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
    
    global $wpdb;
    $data = $_POST;
    
    $form_url = wp_get_referer();
    
    $query = $wpdb->insert('wp_clients_user',
            array(
                    'nom'                => $data['nom'],
                    'prenom'             => $data['prenom'],
                    'email'              => $data['email'],
                    'login'              => $data['login'],
                    'mdp'                => $data['mdp'],
                    'societe'            => $data['societe'],
                    'fonction'           => $data['fonction'],
                    'adresse'            => $data['adresse'],
                    'complement_adresse' => $data['complement'],
                    'code_postal'        => $data['code'],
                    'ville'              => $data['ville'],
                    'pays'               => $data['pays'],
                    'telephone'          => $data['telephone'],
                    'actif'              => false
            ),
            array(
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    '%d',
                    '%s',
                    '%s',
                    '%d',
            )
    );
    
    if ($query) {
            $response['error'] = "true";
    }else{
            $response['error'] = "false";
    }
    echo json_encode($response);
            // $wpdb->show_errors();
    // Redirect  user to the welcome page if everything is okay
    wp_safe_redirect(wp_siteurl);
    exit();
    ?>
    

    I forgot to mention it but process.php and functions.php are in the same folder, located at /wp-content/themes/industrial-child/

    Thanks for the help.

Viewing 8 replies - 1 through 8 (of 8 total)
  • Moderator bcworkz

    (@bcworkz)

    You cannot really directly request any .php file through any means (Ajax or otherwise) if the file uses WP functions. Instead the request needs to go through some WP specific mechanism like admin-ajax.php or admin-post.php. The request needs to include an action query string value which is used to construct an action hook that your PHP would hook to in order to execute your PHP.

    For more detail on using Ajax in WP, see the related sections in the Plugin Handbook. Since you’re new, you may want to peruse other sections of the handbook to get better oriented. A good understanding of action and filter hooks is essential if you wish to customize how WP works.

    Thread Starter tfouchet

    (@tfouchet)

    Thanks for your reply. I don’t understand clearly what you expect me to do. Do I have to redirect my form to one of those files (admin-ajax.php or admin-post) in the action=””?

    Then, the ajax query I added in my template, do I have to cut and paste it in the admin file (admin-ajax.php or admin-post), and link it to the template with a shortcode?

    Also what do you mean by “action query string”? Are you talking about an “add_action”? Where does it have to be? In functions.php or in admin file?

    By the way, which file do I have to choose between admin-ajax and admin-post?

    Moderator bcworkz

    (@bcworkz)

    See if this article clears things up for you. If things are still unclear after that, ask again and I’ll try to clarify.

    Thread Starter tfouchet

    (@tfouchet)

    I’ve read the article, but I still don’t understand where I have to write the add_action(). Is it in my theme functions.php (in which I have created my form) or in admin_post.php?

    I understand that I have to add the admin-post url in the action of the form and the hidden input, but there is no bcw_dyno action in the admin-post.php.

    Finally, I don’t understand the purpose of wp_enqueue_script.

    By the way, I won’t be able to work on this project next week, so sorry if I can’t reply, I won’t be able to use the advices you’ll give me.

    Moderator bcworkz

    (@bcworkz)

    Here are some explanations FYI, whenever you may be able to make use of them.

    Call add_action() on any .php file that you’re developing that loads along with WP. functions.php or the main plugin file is typical. Never attempt to modify admin-post.php or any other core file.

    The action you actually hook is composed in part from the “action” value you pass with the request. This part of admin-post.php:

    $action = ! empty( $_REQUEST['action'] ) ? $_REQUEST['action'] : '';
    //...
    do_action( "admin_post_{$action}" );

    The article passes “bcw_dyno” as an example. You pass your own unique action value and alter the action hook name accordingly.

    The enqueue script scheme is the WP way of getting external script file references in the page’s head (or footer) section to appear on the page. Crucially, it includes a dependency scheme to help ensure the references all appear in the correct order so errors like “undefined function ‘foo'” do not occur. (Assuming foo() does exist but hadn’t been loaded yet.) A common example is specifying ['jquery'] as the dependency arg when you enqueue your script file. Doing so ensures the requisite jQuery library files get loaded prior to your jQuery script file.

    Thread Starter tfouchet

    (@tfouchet)

    Hi, sorry for the delay. Thanks for your explanation. I have a few new questions. If I pass my “own unique action”, where do I create it? You said I should never attempt to modify admin_post.php, so is it in functions.php?

    Also, the “do_action(“admin_post{$my_action}”);” is called in functions.php but $my_action is in admin_post right? Does my own action already exist? (If I can’t add a new one)

    But articles I’ve read don’t mention where I have to add code and this is frustrating… They are talking about a lot of files but say “add this” and that’s it. That is what I want to understand. I have my functions coded, but I don’t understand how to make them work

    Moderator bcworkz

    (@bcworkz)

    Which are you developing? A theme or a plugin? There really are no other choices in WP.

    my “own unique action”, where do I create it?

    Answered already, have I misunderstood what you’re asking?
    I repeat. Call add_action() on any .php file that you’re developing that loads along with WP. functions.php or the main plugin file is typical. Never attempt to modify admin-post.php or any other core file.

    the “do_action(“admin_post{$my_action}”);” is called in functions.php

    I don’t know why that would be in functions.php. While you could do so, it doesn’t make sense. It’s already in admin-post.php. admin-post.php is where the action is created and applied or done. In your file that you’re creating or modifying you use add_action() to add your callback function that will be called when admin-post.php executes do_action( "admin_post_{$action}" ).

    People say “add this” because it can typically go in any number of places, as I’ve answered previously. Most people adding a brief snippet will often use functions.php, but that is not always optimal. Modifying a theme file that is subject to periodic updates from WP is nearly as bad as modifying core files. With such a theme, people really need to create their own child theme for their custom code, or use a custom plugin. It’s actually easier to create a custom plugin than a child theme. The one drawback of a plugin is using it for custom templates can get a little complicated. Templates in a child theme work much better. Of course if you’ve developed your own theme, you’re free to modify it as you like.

    admin-post.php might not always be the best choice for form submissions. The best choice depends on what sort of user experience you want after submission. An admin-post.php response is completely unthemed unless you take measures yourself to utilize theme templates. If the user is intended to see the same page after submission, even if it’s somewhat altered by JavaScript, Ajax and admin-ajax.php would be a good choice.

    You could instead have the form submit back to the page that it’s on and contain the form processing code where the form’s output code is. You can conditionally either output the form or process the form based on request type. If it’s GET, output the form. If it’s POST, process the form data. This option doesn’t have to involve any action hooks. You might like that 🙂 All the same, fully understanding action and filter hooks is a very important concept to grasp if you intend to continue developing for WP.

    Similar to submitting to the same page, your form could submit to a different page whose template contains the form processing code.

    Thread Starter tfouchet

    (@tfouchet)

    Hi, to answer, I am modifying my child theme from the beginning.

    About “my own unique action”, you said that I should not modify the admin files, so I can write “add_action”, but I was asking if I could add a “do_action” with my action as parameter in the admin file. Also, you said that “admin-post.php is where the action is created and applied or not” so I was wondering how my action was created if I only write “add_action”. But maybe it is created automatically by writing add_action.

    From what you said about the way to choice for submission, since i don’t succeed to understand how this works, I just gave up this morning and did it in all php. And now it works.

    Thanks for the help you gave me, but i think I won’t try again ajax.

Viewing 8 replies - 1 through 8 (of 8 total)

The topic ‘How to submit a form’ is closed to new replies.