skip to Main Content

I have a contact form on an external site and are trying to push the submissions to the contact forms 7 plugin in a wordpress site. I have managed to get it to work with a standard html form, but I want to submit it with ajax and load a error or success message below the send-button.

Working and lands on a successful json response from Contact Forms 7:

<form action="https://example.com/wp-json/contact-form-7/v1/contact-forms/256/feedback" method="post" enctype="multipart/form-data">

        <div class="row">
    <div class="col-md-6 mt-3">

<div class="row g-3">
  <div class="col-12">
    <label for="your-name" class="form-label">Fullt navn</label>
    <input type="text" class="form-control" id="your-name" name="your-name">
  </div>
  <div class="col-12">
    <label for="your-email" class="form-label">E-postadresse</label>
    <input type="email" class="form-control" id="your-email" name="your-email">
  </div>
  <div class="col-12">
    <label for="Firma" class="form-label">Firma</label>
    <input type="text" class="form-control" id="firma">
  </div>
  <div class="col-sm-4">
    <label for="zip" class="form-label">Postnummer</label>
    <input type="text" class="form-control" id="zip">
  </div>
  <div class="col-sm-8">
    <label for="city" class="form-label">Sted</label>
    <input type="text" class="form-control" id="city">
  </div>

</div>

    </div>
    <div class="col-md-6 mt-3">
  <div class="col-12">
    <label for="your-subject" class="form-label">Henvendelsen gjelder</label>
    <select id="your-subject" name="your-subject" class="form-select">
      <option selected>Choose...</option>
      <option>...</option>
    </select>
  </div>

<div class="form-floating mt-4">
  <textarea class="form-control" placeholder="Skriv din melding her" id="your-message" style="height: 170px"></textarea>
  <label for="your-message">Melding</label>
</div>

  <div class="col-12 mt-4">
    <button type="submit" class="btn btn-outline-dark">Send</button>
  </div>

    </div>
        </div>
</form>

This is what I have tried for ajax solution:

In header:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script type="text/javascript" language="javascript">
$(document).ready(function () {
$(".bin").click(function () {
var datastring = $("#Form").serialize();
$.ajax({
type: "POST",
enctype: "multipart/form-data",
url: "https://https://example.com/wp-json/contact-form-7/v1/contact-forms/256/feedback",
data: datastring,
dataType: "json",
success: function (data) {
var obj = JSON.stringify(data);
$(".result").append(
'</textarea></li><li class="list-group-item active">Result</li><li class="list-group-item">Name: ' +
data["form"]["name"] +
'</li><li class="list-group-item">Email: ' +
data["form"]["email"] +
'</li><li class="list-group-item">Gender: ' +
data["form"]["multiple"] +
'</li><li class="list-group-item">Comments: ' +
data["form"]["text"] +
"</li></ul></div>"
);
},
error: function () {
$(".result").append("Error occured");
},
});
});
});
</script>

Html:

<form id="Form">

        <div class="row">
    <div class="col-md-6 mt-3">

<div class="row g-3">
  <div class="col-12">
    <label for="your-name" class="form-label">Fullt navn</label>
    <input type="text" class="form-control" id="your-name" name="your-name">
  </div>
  <div class="col-12">
    <label for="your-email" class="form-label">E-postadresse</label>
    <input type="email" class="form-control" id="your-email" name="your-email">
  </div>
  <div class="col-12">
    <label for="Firma" class="form-label">Firma</label>
    <input type="text" class="form-control" id="firma">
  </div>
  <div class="col-sm-4">
    <label for="zip" class="form-label">Postnummer</label>
    <input type="text" class="form-control" id="zip">
  </div>
  <div class="col-sm-8">
    <label for="city" class="form-label">Sted</label>
    <input type="text" class="form-control" id="city">
  </div>

</div>

    </div>
    <div class="col-md-6 mt-3">
  <div class="col-12">
    <label for="your-subject" class="form-label">Henvendelsen gjelder</label>
    <select id="your-subject" name="your-subject" class="form-select">
      <option selected>Choose...</option>
      <option>...</option>
    </select>
  </div>

<div class="form-floating mt-4">
  <textarea class="form-control" placeholder="Skriv din melding her" id="your-message" style="height: 170px"></textarea>
  <label for="your-message">Melding</label>
</div>

  <div class="col-12 mt-4">
    <button type="button" class="btn btn-outline-dark bin">Send</button>
  </div>

    </div>
        </div>
</form>
<div class="result"></div>

I have tried the above described, but only get the error occured as response from the form.

UPDATE: I have tried some more and successfully sending messages with the approach below. But now I only need to insert the "message" response from the api below the submit button. As for now I only get "[object Object]" as output from the json-response that looks like this:

{
    "contact_form_id": 256,
    "status": "mail_sent",
    "message": "Takk for din melding. Den har nå blitt sendt.",
    "posted_data_hash": "551bea1f0cbe640218909efcf2f68a32",
    "into": "#",
    "invalid_fields": []
}

FORM:

<form method="POST" enctype="multipart/form-data" id="my-form">

        <div class="row">
    <div class="col-md-6 mt-3">

<div class="row g-3">
  <div class="col-12">
    <label for="your-name" class="form-label">Fullt navn</label>
    <input type="text" class="form-control" id="your-name" name="your-name" required>
  </div>
  <div class="col-12">
    <label for="your-email" class="form-label">E-postadresse</label>
    <input type="email" class="form-control" id="your-email" name="your-email" required>
  </div>
  <div class="col-12">
    <label for="Firma" class="form-label">Firma</label>
    <input type="text" class="form-control" id="your-company" name="your-company" required>
  </div>
  <div class="col-sm-4">
    <label for="zip" class="form-label">Postnummer</label>
    <input type="text" class="form-control" id="your-zip" name="your-zip" required>
  </div>
  <div class="col-sm-8">
    <label for="city" class="form-label">Sted</label>
    <input type="text" class="form-control" id="your-city" name="your-city" required>
  </div>

</div>

    </div>
    <div class="col-md-6 mt-3">
  <div class="col-12">
    <label for="your-subject" class="form-label">Henvendelsen gjelder</label>
    <select id="your-subject" name="your-subject" class="form-select">
      <option selected>Choose...</option>
      <option>...</option>
    </select>
  </div>

<div class="form-floating mt-4">
  <textarea class="form-control" placeholder="Skriv din melding her" id="your-message" name="your-message" style="height: 170px"></textarea>
  <label for="your-message">Melding</label>
</div>

  <div class="col-12 mt-4">
    <button type="submit" class="btn btn-outline-dark" id="btnSubmit">Send</button>
  </div>

    </div>
        </div>
</form>
    <span id="output"></span>

SCRIPT:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script> 
<script type="text/javascript">
    $(document).ready(function () {
        $("#btnSubmit").click(function (event) {
            //stop submit the form, we will post it manually.
            event.preventDefault();
     
            // Get form
            var form = $('#my-form')[0];
     
            // FormData object 
            var data = new FormData(form);
     
            // If you want to add an extra field for the FormData
            data.append("CustomField", "This is some extra data, testing");
     
            // disabled the submit button
            $("#btnSubmit").prop("disabled", true);
     
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: "https://example.com/wp-json/contact-form-7/v1/contact-forms/256/feedback",
                data: data,
                processData: false,
                contentType: false,
                cache: false,
                timeout: 800000,
                success: function (data) {
                    $("#output").text(data);
                    console.log("SUCCESS : ", data);
                    $("#btnSubmit").prop("disabled", true);
                },
                error: function (e) {
                    $("#output").text(e.responseText);
                    console.log("ERROR : ", e);
                    $("#btnSubmit").prop("disabled", false);
                }
            });
        });
    });
</script>

2

Answers


  1. Chosen as BEST ANSWER

    I solved it:

    HTML:

    <form method="POST" enctype="multipart/form-data" id="my-form">
    
            <div class="row">
    <div class="col-md-6 mt-3">
    
    <div class="row g-3">   <div class="col-12">
        <label for="your-name" class="form-label">Fullt navn</label>
        <input type="text" class="form-control" id="your-name" name="your-name" required>
        <div class="invalid-feedback">
          Please enter a message in the textarea.
        </div>   </div>   <div class="col-12">
        <label for="your-email" class="form-label">E-postadresse</label>
        <input type="email" class="form-control" id="your-email" name="your-email" required>   </div>   <div class="col-12">
        <label for="Firma" class="form-label">Firma</label>
        <input type="text" class="form-control" id="your-company" name="your-company" required>   </div>   <div class="col-sm-4">
        <label for="zip" class="form-label">Postnummer</label>
        <input type="text" class="form-control" id="your-zip" name="your-zip" required>   </div>   <div class="col-sm-8">
        <label for="city" class="form-label">Sted</label>
        <input type="text" class="form-control" id="your-city" name="your-city" required>   </div>
    
    </div>
    
        </div>  <div class="col-md-6 mt-3">   <div class="col-12">
        <label for="your-subject" class="form-label">Henvendelsen gjelder</label>
        <select id="your-subject" name="your-subject" class="form-select" required>
          <option selected>Velg...</option>
          <option>...</option>
        </select>   </div>
    
    <div class="form-floating mt-4">   <textarea class="form-control" placeholder="Skriv din melding her" id="your-message" name="your-message" style="height: 170px"></textarea>   <label for="your-message">Melding</label> </div>
    
      <div class="col-12 mt-4">
        <button type="submit" class="btn btn-outline-dark" id="btnSubmit">Send</button>   </div>
    
        </div>      </div> </form>
        <span class="" id="output"></span>
    

    SCRIPT in footer:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script> 
    <script type="text/javascript">
        $(document).ready(function () {
            $("#my-form").submit(function (event) {
                //stop submit the form, we will post it manually.
                event.preventDefault();
         
                // Get form
                var form = $('#my-form')[0];
         
                // FormData object 
                var data = new FormData(form);
         
                // If you want to add an extra field for the FormData
                data.append("CustomField", "This is some extra data, testing");
         
                // disabled the submit button
                $("#btnSubmit").prop("disabled", true);
         
                $.ajax({
                    type: "POST",
                    enctype: 'multipart/form-data',
                    url: "https://fsenergi-admin.webdemo.no/wp-json/contact-form-7/v1/contact-forms/256/feedback",
                    data: data,
                    processData: false,
                    contentType: false,
                    cache: false,
                    timeout: 800000,
                    success: function (data) {
            $('#output').addClass('mt-4 p-3 bg-white d-block fw-bold');
                        $("#output").text(data.message);
                        console.log("SUCCESS : ", data);
                        $("#btnSubmit").prop("disabled", false);
                    },
                    error: function (e) {
                        $("#output").text(e.responseText);
                        console.log("ERROR : ", e);
                        $("#btnSubmit").prop("disabled", false);
                    }
                });
            });
        });
    </script>
    

  2. To send a form submission to Contact Form 7 in WordPress from an external URL using a hook, you can follow these steps:

        // Create a custom endpoint for form submissions
        add_action('rest_api_init', 'create_form_submission_endpoint');
    
        function create_form_submission_endpoint() {
            register_rest_route('myplugin/v1', '/form-submission', array(
                'methods' => 'POST',
                'callback' => 'handle_form_submission',
            ));
        }
    
        function handle_form_submission($request) {
            // Retrieve the form data from the request
            $form_data = $request->get_params();
    
            // Example: Log the form data
            error_log(print_r($form_data, true));
    
            // Example: Use the Contact Form 7 function to send the form submission
            wpcf7_mail_callback($form_data);
    
            return rest_ensure_response('Form submission received.');
        }
    

    On your external site, when the form is submitted, send a POST request to the endpoint you created in the previous step. The request body should include the form data you want to send to the WordPress site

    const form = document.querySelector('your-form-selector');
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
    
        const formData = new FormData(form);
        const endpointUrl = 'https://your-wordpress-site.com/wp-json/myplugin/v1/form-submission';
    
        try {
            const response = await fetch(endpointUrl, {
                method: 'POST',
                body: formData,
            });
    
            const responseData = await response.json();
            console.log(responseData);
        } catch (error) {
            console.error(error);
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search