Ajax is not defined
Stack Exchange long time listener, first time caller.
I have found examples on the developer.wordpress site but I have been still struggling.
Localizing scripts: wp_localize_script()
In my theme's functions.php file, I have:
function wp_my_ajax_script() {
wp_localize_script( 'ajax_handle_agent_search', 'myAjax', admin_url( 'admin-ajax.php' ));
wp_enqueue_script( 'ajax_handle_agent_search' );
}
add_action( 'wp_enqueue_scripts', 'wp_my_ajax_script' );
And on my page, I've added a HTML code wdiget that contains:
script
jQuery(document).ready( function() {
console.log("Document loaded");
jQuery("#searchButton").click( function(e) {
console.log("Search button clicked");
console.log("Ajax: " . myAjax);
e.preventDefault();
var zipCode = document.getElementById("inputField").value;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
action: "zip_search_action",
zip_code : zipCode
},
success: function(response) {
if(response.type == "success") {
console.log("In success");
document.getElementById("results").html = response.data;
}
else {
console.log("In success, in else!");
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
})
});
});
/script
input type="text" id="inputField"
input type="button" value="Search" id="searchButton"
Then I load the page, enter a zip code in to the input field and click the button. The developer tools console shows:
I've been working on this for a few weeks now and I've gotten much better at developing for Wordpress, but web dev isn't my forte, so after I feel I've reached my limit, I'm reaching out for help. Any insight to get me moving forward would be much appreciated.
Thanks in advance!
================================= EDIT 3/12/20 at 1342 CST
I've moved the JS code to it's own file in the theme's JS directory with the permissions 0755. Then I've added a new function to my functions.php file with the enqueue and localize function calls (as seen below)
function my_load_scripts() {
wp_enqueue_script( 'zip_js', get_template_directory_uri() . '/js/zip_search.js' );
wp_localize_script( 'zip_js', 'Zip_JS', null);
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
================================++++= EDIT 3/13/20 at 0806 CST
I have gotten further. Atleast I believe so. Below is the code as it currently is in Wordpress followed by a screenshot of the console error.
In my JS file ():
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;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
action: "zip_search",
zip_code : zipCode
},
success: function(response) {
if(response.type == "success") {
console.log("In success");
//jQuery("#results").html(response.data);
document.getElementById("results").html = response.data;
}
else {
console.log("In success, in else!");
console.log(response);
}
},
error: function(errorThrown){
console.log("In error, error thrown!");
console.log(errorThrown);
}
});
});
});
In functions.php including my DB query this time:
function my_load_scripts() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'zip_js',
get_template_directory_uri() . '/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( 'ajax_url' = admin_url( 'admin-ajax.php' ) )
);
}
add_action( 'wp_enqueue_scripts', 'my_load_scripts' );
function zip_search()
{
global $wpdb;
$output = '';
$zip = $_REQUEST['zipCode'];
$query = 'SELECT county FROM Agent WHERE zip = %s';
$result = $wpdb-get_var( $wpdb-prepare($query, $zip) );
$output .= "p";
$output .= $result;
$output .= "/p";
$query = 'SELECT zip, county, zone, agent FROM Agent WHERE county = %s';
$results = $wpdb-get_results( $wpdb-prepare($query, $result) );
$output .= "ul";
foreach( $results as $result )
{
$output .= "li".$result-zip." - ".$result-zone." - ".$result-agent."/li";
}
$output .= "/ul";
$result['type'] = "success";
$result['data'] = $output;
return json_encode($result);
die();
}
add_action('wp_ajax_zip_search_action', 'zip_search');
add_action( 'wp_ajax_nopriv_zip_search_action', 'zip_search' );
On my Wordpress page:
input type="text" id="inputField"
input type="button" value="Search" id="searchButton"
EDIT: 3/13/2020 at 11:52am CST
Adding working code. Hopefully anyone that is having close to the same issue can see what I did to make this work and it will help somehow.
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;
console.log("Zip code entered: " + zipCode);
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {
'action': "zip_search",
'zip_code' : zipCode
},
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);
}
})
})
})
functions.php:
add_action('wp_ajax_zip_search', 'zip_search');
add_action('wp_ajax_nopriv_zip_search', 'zip_search' );
function zip_search()
{
global $wpdb;
$output = '';
$zip = $_REQUEST["zip_code"];
$query = 'SELECT county FROM Agent WHERE zip = %s';
$result = $wpdb-get_var( $wpdb-prepare($query, $zip) );
$output .= "p";
$output .= $result;
$output .= "/p";
$query = 'SELECT zip, county, zone, agent FROM Agent WHERE county = %s';
$results = $wpdb-get_results( $wpdb-prepare($query, $result) );
$output .= "ul";
foreach( $results as $result )
{
$output .= "li".$result-zip." - ".$result-zone." - ".$result-agent."/li";
}
$output .= "/ul";
$response = array(
'data' = $output,
);
wp_send_json_success($response);
//return json_encode($response);
//die();
}
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() . '/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' ) )
);
}
HTML:
input type="text" id="inputField" placeholder="Enter zip code here"
input type="button" value="Search" id="searchButton"
Topic wp-localize-script ajax wp-enqueue-script Wordpress
Category Web