0

I have a main plugin file that requires getuser.php (also plugin file). In getuser.php I have written a function getuser()

Now in the main plugin file I'm trying to call this function with the following code:

main plugin file:

<?php
/*
Plugin Name: FixFormData
Description: If you want to autocomplete a form with existing data, this plugin is for you.
Version: 1.1
Author: Stijn Aerts
Author URI: http://stijnaerts.be
License: GPL2
*/

require( plugin_dir_path( __FILE__ ) . 'menu.php');
//require_once( plugin_dir_path( __FILE__ ) . 'getuser.php');

add_action( 'wp_footer', 'ajax_lookup_userdata' );

function ajax_lookup_userdata(){

    if (!is_admin()) {
            wp_enqueue_script('jquery');
        }
    ?>
<script type="text/javascript">
    jQuery(document).ready(function($){
    jQuery('#input_1_2').change(function(){showUserName(this.value);});
        function showUserName(str){
            if(str==''){jQuery('#input_1_3').val('');}
        jQuery.get("<?php echo plugins_url() . '/FixFormData/getuser.php'; ?>", { q: str }, function(response){
                    var parsed = JSON.parse(response);
                    var arr = [];
                    for(var x in parsed){ arr.push(parsed[x]);}
                    jQuery('#input_1_3').val(arr[1]);
                    jQuery('#input_1_4').val(arr[2]);
            });
        }
    });
</script>
<?php
}
?>

getuser.php:

<?php
    if (isset($_POST['q']) && !empty($_POST['q'])) {
        getuser($_POST['q']);
        exit;
    }

 function getuser($str)
{
    //$q = intval($_GET['q']);
    //include "../../../wp-load.php";
    global $wpdb;

    $myoption =  get_option( 'fixformdata_options' );
    $myoptionValue = maybe_unserialize( $myoption );    

    $result2 = $wpdb->get_row
    (
        $wpdb->prepare
        (
            "SELECT * FROM {$myoptionValue[tablename]} WHERE personeelsNummer = %d", $str
        )
    );

    if($result2) 
    {
        echo  json_encode( $result2 );
    }
}
?>

This still doesn't work.

stijn.aerts
  • 6,026
  • 5
  • 30
  • 46
  • You are trying to call a php function with javascript? You can't do that – QuinnFTW Aug 28 '14 at 19:31
  • Yes I know, i also tried among other things – stijn.aerts Aug 28 '14 at 19:33
  • What does `getuser()` do? Does it return a variable? – ndiego Aug 28 '14 at 19:43
  • It returns json data – stijn.aerts Aug 28 '14 at 19:44
  • Well you might want to try out `wp_localize_script`. This way you can pass the json information to jQuery. A great reference for this is: [https://pippinsplugins.com/use-wp_localize_script-it-is-awesome/](https://pippinsplugins.com/use-wp_localize_script-it-is-awesome/). The comments are useful as well. – ndiego Aug 28 '14 at 19:48
  • Observations: 1) `wp_footer` only runs on frontend, so you don't need `is_admin()`. 2) Instead of `wp_footer`, use `wp_enqueue_scripts`. 3) Check [this](http://stackoverflow.com/questions/13498959/how-to-use-ajax-in-a-wordpress-shortcode/) for an AJAX example (Federico's tip for Pippin's article is quite good too). – brasofilo Aug 28 '14 at 21:10

3 Answers3

2

You need to send the data to the url where your function is located

$(function() {

function showUserName(str) {
    if (str === '') {
        $('#input_1_3').val('');
    }

    $.ajax({
        type: 'post',
        url: 'getuser.php', //where your function is located
        data: { whatever: value }, //post data $_POST['whatever'] = value
        success: function(data) {
            var data = JSON.parse(data); //whatever the server echoes will end up in data
            $('#input_1_3').val(data[0]);
            $('#input_1_4').val(data[1]);
        }
    });
}

$('#input_1_2').change(function() {
    showUserName($(this).val());
});
});

You should also make sure your php code is ready to respond to that request.

    <?php 

    if (isset($_POST['whatever']) && !empty($_POST['whatever'])) {
        getuser($_POST['whatever']);
        exit;
    }

    function getuser($str) {
        // logic and stuff

        echo json_encode(["whatever", "you want to return"]);
    } 

    ?>
  • Thanks for the help, I edited my code and all of my code is now in the OP, it still doesn't work though... – stijn.aerts Aug 28 '14 at 20:20
  • also, please keep in mind that this is for wordpress and I need correct hooking, I had a good solution that was working but it didn't had corredt hooking. – stijn.aerts Aug 28 '14 at 20:25
  • Sorry, I forgot to add a type to the ajax request. To be completely honest, I don't know anything about wordpress, but this should work. What exactly are you returning? Can I see the php? –  Aug 28 '14 at 20:28
  • Is "getuser.php" in a subdirectory? That needs to be specified in the url. Also, have you tried alerting the data that is returned from the server to see what it contains? –  Aug 28 '14 at 20:32
  • I'm just returning some database data, text. What php do u want to see? – stijn.aerts Aug 28 '14 at 20:36
  • Whatever is relevant. What do you get when you alert(data)? –  Aug 28 '14 at 20:38
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/60196/discussion-between-dandan-and-stijn26). –  Aug 28 '14 at 20:40
2

I think wp_localize_script is what you're looking for. http://codex.wordpress.org/Function_Reference/wp_localize_script

You can keep javascript and php separated by passing json data to javascript files and wordpress will do that in a clean and elegant way.

But if what you have to do needs to be done with a ajax request and not on page load than you have to use the wp_ajax_ hook a good tutorial here: http://www.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/

Federico Vezzoli
  • 696
  • 1
  • 5
  • 9
  • Hi I have made a new question, as I edited my code totally. http://stackoverflow.com/questions/25566254/getting-data-from-database-and-use-it-to-complete-a-form-wordpress – stijn.aerts Aug 29 '14 at 10:26
1

It sounds like your getuser() function is coded in PHP, correct? Assuming so, you won't be able to call it via jQuery. PHP is a server-side language. Once it has ran, that's it, it can't be accessed again without reloading the page, and still only by server-side languages. jQuery is client-side scripting, something done on the users computer.

Basically, you'd need the getuser() function to be in some form of JavaScript, or to output what you want it to display and have the jQuery display the page.

brasofilo
  • 25,496
  • 15
  • 91
  • 179