2

I’m new to WP and not overly familiar with AJAX either but I’m trying to get a very simple AJAX call to work, I think I’m nearly there but I can’t get any results to return back from the AJAX call, I’ve stripped everything down to the bare bones to get it working and am just returning the string ‘This is AJAX data results’ from the PHP Ajax function but even that does not appear to be working. At the moment I get my test alerts…

alert('jquery step 1'); - Works OK

alert('jquery step 2'); - Works OK

alert('ajax result: '.response); - ** NOT DISPLAYED **

alert('jquery step 3'); - Works OK

I've created a custom plugin and custom js and php files as follows...

********* c4l-custom-functions.php ********

<?php
/**
* Plugin Name: C4L Custom Functions Plugin
* Description: This plugin contains C4l custom functions, scripts and css 
styles.
* Author: C4L
* Version: 1.0
*/

function c4l_custom_script_and_style_includer() {
    wp_enqueue_script( 'c4l-js', plugins_url( 'js/c4l-custom-scripts.js' , __FILE__ ) );
    wp_enqueue_style( 'c4l-css', plugins_url( 'css/c4l-custom-styles.css' , __FILE__ ) );
}

add_action( 'wp_enqueue_scripts', 'c4l_custom_script_and_style_includer' );

add_action( 'wp_ajax_wps_get_time', 'wps_get_time' );
add_action( 'wp_ajax_nopriv_wps_get_time', 'wps_get_time' );

function wps_get_time() {
    // $format = $_POST['format'];
    echo('This is AJAX data results');
    //echo date($format);
   die();
}
?>

********* c4l-custom-scripts.js ********

document.addEventListener("DOMContentLoaded", function(event) {
    jQuery('#pulldown1').change(function(){ 
        alert('jquery step 1');
        var timeformat = 'U';
        alert('jquery step 2');
        jQuery.ajax({
            type: "POST",
            url: "admin-ajax.php",
            data: { action: 'wps_get_time', format: timeformat },
            success: function ( response ) {
                alert('ajax result: '.response);
            }
        });
        alert('jquery step 3');
    }); 
});
2
  • use the network monitor to see if the AJAX call works, e.g. with firefox : developer.mozilla.org/en-US/docs/Tools/Network_Monitor
    – mmm
    Apr 10, 2018 at 16:53
  • if the call fails, it won't call the success callback, but you never specified a failure callback. btw have you considered the REST API endpoints? They're much more straight forward, and when they fail they give you error messages that make more sense. Also console.log() ftw
    – Tom J Nowell
    Apr 10, 2018 at 17:21

1 Answer 1

1

There's two problems:

  1. You're not sending the AJAX request to the correct URL.
  2. You're using PHP-style concatenation instead of JavaScript.

For the first issue, a relative URL "admin-ajax.php" is not going to work. If you are on a page like /about-us/ then jQuery is going to send the request to /about-us/admin-ajax.php, which doesn't exist.

The most reliable way to set the URL is to get the URL with PHP using the admin_url() function and use wp_localize_script() to send the value to your script:

function c4l_custom_script_and_style_includer() {
    wp_enqueue_style( 'c4l-css', plugins_url( 'css/c4l-custom-styles.css' , __FILE__ ) );
    wp_enqueue_script( 'c4l-js', plugins_url( 'js/c4l-custom-scripts.js' , __FILE__ ) );
    wp_localize_script( 'c41-js', 'c41', ['ajaxurl' => admin_url('admin-ajax.php')] );
}
add_action( 'wp_enqueue_scripts', 'c4l_custom_script_and_style_includer' );

What that extra line does is: If the c4l-js (the first arugment) is enqueued, create a global JS variable called c41 (the second argument) with the keys and values passed to the 3rd argument. We have provided the correct URL to admin-ajax.php.

So now in your script, set the URL to:

url: c41.ajaxurl,

The other issue is how you're concatenating the response to a string in JavaScript:

alert('ajax result: '.response);

. is the character used to concatenate strings in PHP, but in JavaScript you need to use +:

alert('ajax result: ' + response);
1
  • That's great thx, yes I adapted the code to use admin_url(), and corrected the + concatenator, all working now thx very much
    – mdirect
    Apr 11, 2018 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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