Search code examples
phpmysqlwordpressgravity-forms-plugingravityforms

Gravity Forms post/get to get data from mysql database


sadly i have no success retrieving data with a simple ajax request from my mysql database.

I have a gravity from set up with ajax in the shortcode enabled. When i change the selection of the first field, i want a ajax request to be done to retrieve data from the database and to load it into another field depending on the selection of the first field.

The alerts are working so i guess there is something wrong with the jquery request.

Edit: Solution down below!


Solution

  • Update: This is the current solution i am using which is imo the best one. Instead of creating a seperate connection in the php file i am accessing the wordpress functionality.

    Here is the code for a gravity form ajax request to get data from a mysql database after a change on a select box has been done.

    add_filter("gform_pre_render_2", "getdbdata");
        function getdbdata($form){
            ?>
                <script type="text/javascript">
                jQuery(document).ready(function(){
                    jQuery('#input_2_1').bind('change', function()
                    {
                      var vdepot_id = jQuery("#input_2_1").val();   
    
                      jQuery.ajax({
                        async: 'false',
                        type: 'post',
                        global: 'false',
                        dataType: 'json',
                        url: 'yoursite.com/yourscript.php',
                        data: {
                          virtuellesdepot_id:vdepot_id,
                        },
                        success: function (response) {  
                            jQuery("#input_2_28").val(response.status);
                        }
                      });                       
                    });
                });
                </script>
            <?php
            return $form;
            }
    

    and that is the php code you need on your server:

    <?php
    if( isset( $_POST['virtuellesdepot_id'] ) )
    {
    $vdepot_id = $_POST['virtuellesdepot_id'];
    
    define( 'WP_USE_THEMES', false ); // Don't load theme support functionality
    require_once("../wp-load.php");  //now you can use wp functions
    $user_id = get_current_user_id();
    
    //make a security check if user has access to the entry
    $user_check = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM usertable WHERE vdepot_id= %d ",  $vdepot_id));
        if($user_check != $user_id){
        header("Location: https://yoursite/no-access/");
        exit();
    }
    
    //use any sql query you want
    $status = $wpdb->get_var($wpdb->prepare("SELECT status_id FROM table WHERE user_id= %d ",  $user_id));
    $arr = array ('status'=>$status);
    echo json_encode($arr);
    
    }else{
    echo "Fehler bei if isset";
    }
    
    ?>