-1

I'm trying to make an AJAX call for the first time in wordpress. I followed some tutorial and have came to this point so far. But when I'm trying to console.log the data I get from database inside my AJAX call, I get this error:

Uncaught ReferenceError: data is not defined

Code:

functions.php

function my_ajax_handler(){
    global $wpdb;
    $name = $wpdb->get_results("SELECT * FROM username");

        echo $name;
}

add_action( 'wp_ajax_call_my_ajax_handler', 'my_ajax_handler' );
add_action( 'wp_ajax_nopriv_call_my_ajax_handler', 'my_ajax_handler' );

function enqueue_styles() {
    wp_enqueue_style("child-style", get_template_directory_uri() .'/style.css');
    wp_enqueue_style("parent-style", "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css");
    wp_enqueue_script("jquery", 'https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous');
    wp_enqueue_script( 'my-ajax-script', get_stylesheet_directory_uri() . '/path/to/script.js', array('jquery') );
    wp_localize_script( 'my-ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}

add_action("wp_enqueue_scripts", "enqueue_styles");

quiz-loged-page.php

<script>
jQuery.ajax({
    type:"POST",
    url: my_ajax_object.ajax_url,
    data: { 'action': 'call_my_ajax_handler' }
}).done(function() {
  console.log(data);
});

</script>
1

Pass data as an argument in done(function(data) funtion.

<script>
jQuery.ajax({
    type:"POST",
    url: my_ajax_object.ajax_url,
    data: { 'action': 'call_my_ajax_handler' }
}).done(function(data) {
  console.log(data);
});

  • Thanks, that works. The only problem that I have now is that it returns Array0 in console.log, but I want it to return string. My database has only names of strings. Do you know how I can do that? Now I just select *, but putting a string doesn't help. – Limpuls Nov 13 '18 at 14:20

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.