WordPress Development Asked on December 12, 2021
I created a JS and PHP code to query a database and display matching rows on a page. It was messing up other pages on WP, so I wanted to know how to target a single page so the JS doesn’t run on other pages.
JS:
jQuery(document).ready( function() {
console.log("Document loaded");
jQuery("#searchButton").click( function(e) {
console.log("Search button clicked");
e.preventDefault();
var zipCode = document.getElementById("inputField").value;
var data = {
'action' : "zip_code",
'zip_code' : zipCode
};
console.log("Zip code entered: " + data.zip_code);
console.log("WP AJax URL: " + data.action);
jQuery.ajax({
type : "post",
dataType : "json",
url : data.action,
data : data,
success: function(response) {
console.log(response.data);
if(response.success) {
console.log("response.type == success");
jQuery("#results").html(response.data.data);
}
else {
console.log("response.type == else");
console.log(response.data);
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
})
})
});
PHP:
<?php
add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );
function enqueue_parent_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
}
add_action('wp_ajax_zip_search', 'zip_search');
add_action('wp_ajax_nopriv_zip_search', 'zip_search' );
function zip_search()
{
global $wpdb;
// Functional code omitted for now. Just need to get "here" paragraph return (for now)
$output = "<p>here</p>";
$response = array(
'data' => $output,
);
wp_send_json_success($response);
}
add_action( 'wp_enqueue_scripts', 'my_load_scripts' );
function my_load_scripts() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'zip_js',
get_template_directory_uri() . '-child-agent_search/js/zip_search.js',
array('jquery')
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'zip_js',
'myAjax',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
}
?>
Here, the code operates on anything that matches the #searchButton
element:
jQuery("#searchButton")
If there is a searchButton
on other pages, it will match it, soo you need to be more specific.
For example, on the homepage, the <body>
tag will have the home
class, here is my sites homepage body tag:
<body class="home blog logged-in admin-bar no-customize-support">
So to make it target only the search button on the home page, you could try something like this:
jQuery(".home #searchButton")
Alternatively, only enqueue the JS on that particular page, but the selector method is superior. Make sure there is only one element on the page with that ID as IDs need to be unique
Answered by Tom J Nowell on December 12, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP