I am developing a website and I have created a Wordpress plugin for a search bar. The plugin has a js folder and file but the changes made to that file are not appearing on the website.
I have cleared my browser's data, my server's cache (Cloudways Varnish), and have installed a plugin to clear Wordpress cache (Cloudways' Breeze). None seem to work.
I can see on the Wordpress Plugin file editor that the JS file is updating, but the changes are not appearing on the live website.
dynamic-search-plugin.php file:
<?php
function enqueue_ajax_scripts() {
wp_enqueue_script( 'dynamic-search-ajax', plugin_dir_url( __FILE__ ) . 'js/dynamic-search.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'dynamic-search-ajax', 'dynamicSearchAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'dynamic-search-nonce' )
) );
}
function dynamic_search_handler() {
check_ajax_referer( 'dynamic-search-nonce', 'nonce' );
// Retrieve the search query from the AJAX request
$query = sanitize_text_field( $_POST['query'] );
$results = array(
array( 'name' => 'Test 1' ),
array( 'name' => 'Test 2' )
);
// Return the search results as a JSON response
wp_send_json( $results );
}
add_action( 'wp_enqueue_scripts', 'enqueue_ajax_scripts' );
add_action( 'wp_ajax_dynamic_search', 'dynamic_search_handler' );
add_action( 'wp_ajax_nopriv_dynamic_search', 'dynamic_search_handler' );
The dynamic-search.js file:
jQuery(document).ready(function($) {
// Event handler for search form submission
$('#search-form').on('submit', function(e) {
console.log("On submit in JS called");
e.preventDefault();
var query = $('#search-input').val();
// Make AJAX request to the server
$.ajax({ //only this is run for some reason
url: dynamicSearchAjax.ajaxurl,
type: 'POST',
data: {
action: 'dynamic_search',
nonce: dynamicSearchAjax.nonce,
query: query
},
success: function(response) {
displayResults(response);
},
error: function() {
alert('Error');
}
});
});
// Function to display search results
function displayResults(results) {
var container = $('#results');
container.empty();
// Loop through the results and create buttons
results.forEach(function(result) {
var button = $('<button>').text("Test"); //changing this code doesn't correspond to changes on website
container.append(button);
// Add click event handler to the button
button.on('click', function() {
// Perform an action when the button is clicked
alert('Button clicked:');
});
});
}
});
It happens in WordPress sometimes when it caches your script, Try adding time()
param to your script file like below,
wp_enqueue_script( 'dynamic-search-ajax', plugin_dir_url( __FILE__ ) . 'js/dynamic-search.js?time='.time(), array( 'jquery' ), '1.0', true );