I am trying to build a webform with autocompletion. The user can fill in a personal code and the related fields will be shown in the form fields.

How can I fetch the results into my form fields?

What I tried so far:

  1. Lookup the code in Javascript.
  2. Use AJAX to send the code to PHP.
  3. PHP looks up the code in the SQL query and fetches the result.
  4. When I use the console and check the var_dump in the lookup_code() function I see the array from the user I want.

Here is my code:

add_action( 'wp_head', 'ajax_lookup_userdata' );
 * Ajax_lookup_userdata
 * Will check the string on the input field for the code.

function ajax_lookup_userdata() {

<script type="text/javascript">
    jQuery(document).ready(function( $ ) {

        /*Lookup the field value.*/
        var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
        var codeValue = jQuery('li.code input');
        var data;

        /* Limit the  keyup function... min characters and max characters. */

            data = {
                'action': 'lookup_code',
                'codevalue': jQuery(this).val()

            // This gives me the output of the values you insert into the code-textfield.

            jQuery.post(ajax_url, data, function(response) {
                //alert('Got this from the server: ' + response);

add_action('wp_ajax_nopriv_lookup_code', 'lookup_code'); // for not logged in users

function lookup_code() {

global $wpdb;

$searchQuery = $_POST['codevalue'];

$results = $wpdb->get_results('SELECT * FROM wp_contacts WHERE code LIKE "'.$searchQuery.'" ');

update_post_meta( $id, '_wp_page_template', 'new_template.php' );
// Here are my values that I want to receive.
// How to pass them to the field values?


The var_dumps($results[0]); gives me the following output:

object(stdClass)#277 (8) {
  string(1) "1"
  string(2) "1a"
  string(4) "Bert"
  string(7) "Gibbers"
  string(15) "Lazy Berry Edge"
  string(2) "35"
  string(18) "stone@meekness.com"
  string(12) "202-555-0102"

Thanks a lot for the support.


You could fill in the form as shown below:

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // assign inputs[index] element values from the response.

This is pure JavaScript, unless I miss something.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.