1

Hi i'm just begining with wordpress so any help would be appreciated. I trying to get this working but the response data is undefined because of the 400 error. I've tried everything. Here's my code.

function simokydesigns_translate_scripts() {

   wp_enqueue_script('customjquery', get_template_directory_uri() 
   .'/js/customjquery.js', array('jquery'));
   wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin- 
   ajax.php' ) );
}
add_action( 'wp_enqueue_scripts', 'simokydesigns_translate_scripts' );

function get_ajax_sidebar(){

  get_sidebar();
}

add_action('wp_ajax_get_ajax_sidebar', 'get_ajax_sidebar');
add_action('wp_ajax_nopriv_get_ajax_sidebar', 'get_ajax_sidebar');

//js/customjquery.js

(function($) {

  $.ajax({
        type: 'POST', // use $_POST method to submit data
        dataType: "html",
        url: ajaxurl,
        data: {
            'action': 'get_ajax_sidebar',   
        },
        success:function(data) {

            alert('Got this from the server: ' + data);
            //$( '#widget-top' ).html( data );
        },
        error: function (data) {
            console.log('error' + data);
        }

    });  



     /*$( '#widget-top').append( "<?php echo get_sidebar();?>" );*/


 })( jQuery );
1

You have two problems in PHP you need change this

is bad:

wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin- 
   ajax.php' ) );

change to:

wp_localize_script( 'customjquery', 'my_custom_vars', ['ajax_url' => admin_url('admin-ajax.php')] );

and your javascript need this changes

is bad:

$.ajax({
        type: 'POST', // use $_POST method to submit data
        dataType: "html",
        url: ajaxurl,

change to:

$.ajax({
        type: 'POST', // use $_POST method to submit data
        dataType: "html",
        url: my_custom_vars.ajax_url,
0

This line break here:

wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin- 
   ajax.php' ) );

Means that the AJAX URL isn't correct. Make sure there's no line break:

wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin-ajax.php' ) );

When I made this fix and tested your code worked just fine.

But just as an aside, a POST request is inappropriate for this use case. You're getting data (in this case HTML for a sidebar), not submitting data, so a GET request should be used.

  • Thanks for the swift reply, I did not have a line break and I compared your line with mine and they looked the same, but there was something wrong with it because when I retyped that it worked. :) Much appreciated. – Simoky Jul 14 '18 at 13:09
  • Possibly had an issue with cross-platform line endings, and the line break didn't become obvious until pasting into a different system. – Jacob Peattie Jul 14 '18 at 13:43

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.