0

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:

Developer Tool console with error message

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: jQuery error

================================++++= 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: New console error with status 200 and statusText of "OK"


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">
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
    Mar 12 '20 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. Mar 12 '20 at 17:08
  • Can you link us to what you found and tried to follow?
    – Tom J Nowell
    Mar 12 '20 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 Mar 12 '20 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
    Mar 12 '20 at 17:25
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');
5
  • Hello! Yes, I actually did add that part in before learning work yesterday, but didn't work. This morning, I made a few new changes which did finally see jquery and get past that error. Now, the response status is 200 and statusText is "OK". But in JS, it reaches "error: function(errorThrown)". Allow me a little bit today to work with it and double check all my syntax. Mar 13 '20 at 13:04
  • Yes. I have now learned how to fix that missing jQuery error. I'm getting better at Wordpress everyday and I actually think I could keep using this for my own sites. Mar 13 '20 at 13:32
  • Thanks for the help! I am posting the working code as an edit above. Mar 13 '20 at 16:48
  • @DanielNebert one thing to improve $zip = $_REQUEST['zipCode']; should be sanitized like $zip = sanitize_text_field( isset($_REQUEST['zipCode']) ? $_REQUEST['zipCode'] : '') );
    – Mikhail
    Mar 14 '20 at 9:15
  • That is a good heads up. Thank you. I was going to start working on making it better, so I'm happy for the info. I'll make that change and account for the zip code being an empty string and returning the HTML to inform the user accordingly. Mar 16 '20 at 13:08
0
        #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);

                }
              });
    });  
  });  

2
  • Hi there, I will try this next. I feel I am so close with the other code that I've been receiving help with above and didn't want to bounce between as to confuse myself or make mistakes. What does enctype: 'multipart/form-data' do? Mar 13 '20 at 13:00
  • Thanks for the help! I am posting the working code as an edit above. Mar 13 '20 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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