wp enqueue script - Ajax is not defined

admin2025-01-07  6

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');

Now the console shows:

================================++++= 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">

Console:


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">

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');

Now the console shows:

================================++++= 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">

Console:


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">
Share Improve this question edited Mar 13, 2020 at 16:54 Daniel Nebert asked Mar 12, 2020 at 16:04 Daniel NebertDaniel Nebert 431 silver badge7 bronze badges 12
  • Just curious, but you used the old fashioned Admin AJAX rather than the modern REST API endpoints for your AJAX query, why? – Tom J Nowell Commented Mar 12, 2020 at 16:28
  • It is what I found while looking up "how-to" information. I'm more comforatable with backend coding (OO and SQL), but I was asked to help with a Wordpress site, which is way beyond my capabilities. To answer that question, I do not know of anything else. – Daniel Nebert Commented Mar 12, 2020 at 17:08
  • Can you link us to what you found and tried to follow? – Tom J Nowell Commented Mar 12, 2020 at 17:12
  • I have viewed many pages, but here is the most recent page I had been using: sitepoint.com/how-to-use-ajax-in-wordpress-a-real-world-example – Daniel Nebert Commented Mar 12, 2020 at 17:16
  • Since this is an inline script and not a traditional enqueue, you cannot use localize_script. The enqueue_script function is meant for external scripts, in their own JS files. Is it possible to move your code into it's own JS file and enqueue it properly? – Howdy_McGee Commented Mar 12, 2020 at 17:25
 |  Show 7 more comments

2 Answers 2

Reset to default 0

jQuery is not defined because you've not referred jQuery as dependency for your script so wp isn't aware it should load it for your script.

wp_localize_script should be called on script that is already linked via wp_enqueue_script, so you first run wp_enqueue_script then wp_localize_script as you do in your UPD.

Another thing about wp_localize_script is it takes 3 arguments (see https://developer.wordpress.org/reference/functions/wp_localize_script/), and last one is associative array.

So if in your JS code you want to get ajaxurl via myAjax.ajaxurl you need to call wp_localize_script( 'zip_js', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));

Code below takes into account your new naming of script as zip_js and global js variable is now Zip_JS, so you will access your ajaxurl in js code like Zip_JS.ajaxurl instead of myAjax.ajaxurl .

Here's how you need to do to fix jQuery missing error, and also use localize script properly:

function my_load_scripts() {
    wp_enqueue_script( 'zip_js', get_template_directory_uri() . '/js/zip_search.js', array('jquery') );
    wp_localize_script( 'zip_js', 'Zip_JS', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
        #try this
    function wpb_adding_scripts() {
        wp_register_script('my_amazing_scripts', plugins_url('jquery.js', __FILE__), array('jquery'), '3.4.1', true);
        wp_enqueue_script('my_amazing_scripts');
    }


        <form id="article_form" name="article_form" class="wordpress-ajax-form" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>" enctype="multipart/form-data" >
        <input type="hidden" name="action" value="custom_action">
        </form>

<script>
jQuery(document).ready(function(evt) {
  $(".wordpress-ajax-form").submit(function(evt){  

            $.ajax({
                url: $('#article_form').attr('action'),
                type: 'POST',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                enctype: 'multipart/form-data',
                processData: false,
                success: function (response) {
                 alert(response);

                }
              });
    });  
  });  

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736259734a611.html

最新回复(0)