1

I am trying to make an ajax call and I am getting the error:

TypeError: $ is undefined

This is my function.php file:

<?php

// Add custom Theme Functions here
// 

function gear_guide_product_view( $atts ) {
    $a = shortcode_atts( array(
        'id' => '0'
    ), $atts );
    wp_register_script( 'load_product_info' , '/wp-content/themes/theme-child/js/test.js' , array( 'jquery' ) );
    wp_enqueue_script( 'load_product_info' );
    wp_localize_script( 'load_product_info' , 'para' , $atts);
}

add_shortcode( 'fsg' , 'gear_guide_product_view' );

this is the ajax:

function load_product_info() {
    console.log(para.id);
    $.ajax({
        type: 'POST',
        url: '/wp-content/themes/flatsome-child/js/controllers/get_product_info.php',
        data: para,
        dataType: 'json',
        success: function (data) {
            console.log(data);
        }
    });
}
load_product_info();

I have declared the use of jquery and from what I read on google it's all I need in order to make an ajax call.

If there is any more information needed tell me and I'll do my best to provide it.

Thanks!

  • 4
    WordPress jQuery is in noConflict mode, use jQuery instead of $. – Milo Jul 31 '18 at 15:37
  • don't forget to enqueue jquery either, and consider marking an answer as accepted if it contains the correct answer, else nobody will get reputation points from comments – Tom J Nowell Jul 31 '18 at 16:24
2

As Milo already said in comment, jQuery is in noConflict mode in WordPress. This way other JS libraries can also use $ character...

One way to solve it is using jQuery everywhere in your JS files.

Another is to create block and define $ variable in it:

jQuery(function ($) {

    $.ajax(...); // here you can use $ since it is already defined and won’t cause conflicts

});
0

You're using very specific URLs for ajax endpoint. When you change your theme your functionality WILL break. Do check how the WP codex how to make ajax calls properly and hook into wp_ajax actions.

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.