I have the following files:
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_enqueue_scripts', 'ffd_load_scripts' );
function ffd_load_scripts()
{
wp_register_script('ffd_js_script', WP_PLUGIN_URL.'/FixFormData/js/ffd_js_script.js', array('jquery'));
wp_localize_script('ffd_js_script', 'myAjax', array(
'ajaxurl' => admin_url('admin-ajax.php')
)
);
wp_enqueue_script('jquery');
wp_enqueue_script('ffd_js_script', plugin_dir_url(__FILE__) . 'js/ffd_js_script.js');
}
getuser.php:
<?php
function getuser($str)
{
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 );
}
}
?>
ffd_js_script.js:
jQuery(document).ready(function($){
jQuery('#input_1_2').change(function()
{
jQuery.ajax({
type : 'post',
dataType : 'json',
url : myAjax.ajaxurl,
data : {action: 'getuser', this.value},
succes: 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]);
}
})
});
});
How do I properly implement this? First time I'm making a plugin and I have read much about it and saw alot of examples, but I'm failing to implement this correctly.
EDIT:
IF I replace the sql statement with the following:
"SELECT * FROM {$myoptionValue[tablename]} WHERE personeelsNummer = %s", 1
I get my results in the console due to following code:
echo json_encode( $result2 );
So following code is not executing properly:
succes: 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]);
}
ok, you're getting there. 1st When you localize the script add a nonce for better security:
Then, you need to place getuser.php somewhere where the plugin can see it, so be sure to include it or place it in the main file of the plugin
Than, to make the funciont getuser callable from ajax you need to do the proper hooking:
In the js, you need to pass the nonce as well:
the rest of the js seems good, forgive me for some typos, I wrote it right here so it's not tested.