Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress WpForm customize submit button to call external API (Json)

I wanted to change the submit button to be able to trigger ajax or whatever that can send POST request to another server (as I wanted to managed all data submit from wordpress in another server). Wordpress is just simple UI page with webform to create a record and send over to another server. I have no knowledge on PHP at all. How can I managed to modify the code in order to achieve it? Don't Worry about CORS issue as I can handle that

like image 653
Ah Hiang Avatar asked Mar 31 '26 21:03

Ah Hiang


1 Answers

This is what you need.

In your theme functions.php file you need to add this WPForms action this will trigger when you complete and submit the form.

add_action( 'wpforms_process_complete', 'sendingDataToJava', 10, 4 );

   function sendingDataToJava( $fields, $entry, $form_data, $entry_id) {
    
    //Specify WPForm ID you have there

    //if form ID is 1 (checking index id of $form_data array)
    if ($form_data['id'] == 1) {
        
      $api_url = 'http://some java end point.com';
      $body = array(
        'name'                => $fields['1']['value'],
        'email'               => $fields['2']['value'],
        'phone'               => $fields['3']['value'],

       );
       $request = wp_remote_post( $api_url, array( 'body' => $body ) );
        
     }
}

You will have to see the $fields id's in the form your using and change above accordindly. Also you need to figure to check how to get the data on your java end point file.

Another Way

Another way will be an ajax request by adding this action in your functions.php

add_action( 'wp_ajax_foobar', 'sendingDataToJava' );
add_action( 'wp_ajax_nopriv_foobar', 'sendingDataToJava' );
function sendingDataToJava() {
    // do something
    
    // avoids extra 0 at the end of the response
    die(); /
}

In your theme JS file add this code

jQuery(document).ready(function($) {

   $('#form_button_id').click( function() {
      
      //
      var data = {
         name: $('#field_1').val(),
         email: $('#field_2').val(),
         phone: $('#field_3').val()
      };

      var ajaxurl = 'http://some java end point.com';
      jQuery.post(ajaxurl, data, function(response) {
         alert('Data Sent to Sent +' response);
      }
      );
   }
   );
}
);

Refer to this WPForm action for more info: https://wpforms.com/developers/wpforms_process_complete/

Hope this helps

like image 109
Always Helping Avatar answered Apr 02 '26 11:04

Always Helping



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!