I get a
ReferenceError: ajax is not defined
error in browser console when I try to make an ajax call.
I’m pretty sure I properly loaded the jQuery library, therefore I don’t understand how can the $.ajax function not be defined.
Here is the HTML (without irrelevent css and markup):
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div>
<a class="getUsersA">Get users</a>
<div id="gridD"></div>
</div>
</body>
</html>
Here is the script.js file:
$(document).ready(function() {
$(".getUsersA").click(function() {
$.ajax({
url:ajax/getUsers.php,
type:POST,
data:({
id:0
}),
success:function(results) {
$("#gridD").html(results);
}
});
});
});
Thank you for any help!
asked Sep 23, 2013 at 15:22
2
You need to wrap ajax/getUsers.php,
in quotes. or else it would look for a local variable ajax
rather than treating it as a string.
url: "ajax/getUsers.php",
Something like this:
$.ajax({
url: 'ajax/getUsers.php',
type: 'POST',
data:({
id: 0
}),
success:function(results) {
$("#gridD").html(results);
}
});
answered Sep 23, 2013 at 15:24
karthikrkarthikr
96.8k26 gold badges196 silver badges188 bronze badges
2
You have a syntax error on this line:
url:ajax/getUsers.php,
Change this to:
url:"ajax/getUsers.php",
answered Sep 23, 2013 at 15:24
CurtisCurtis
101k65 gold badges269 silver badges351 bronze badges
You’re supposed to be passing a string (or a variable containing a string) as the url
option, but you’re instead doing:
url:ajax/getUsers.php,
Change it to:
url:'ajax/getUsers.php',
What you have right now is looking for the variable ajax
(which doesn’t exist) then trying to divide it by the php
property of the object referenced by getUsers
(which also doesn’t exist), and then set the result as the value for the url
option.
answered Sep 23, 2013 at 15:24
Anthony GristAnthony Grist
38.1k8 gold badges62 silver badges75 bronze badges
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:
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">
$ is not defined в jQuery: что это значит и что делать
Новая рубрика — «Типичные ошибки». Будем разбираться, что означают разные ошибки в программах и как с ними быть.
Новая рубрика — «Типичные ошибки». Будем разбираться, что означают разные ошибки в программах и как с ними быть.
Где можно встретить $ is not defined и что это значит
Скорее всего, эту ошибку вы встретите в сообщениях консоли браузера, когда будете подключать к своему сайту какую-нибудь JavaScript-библиотеку, которая использует jQuery. Например, это может быть листалка фотографий или форма обратной связи.
$ is not defined означает, что на момент, когда ваша библиотека пыталась сделать что-то с помощью jQuery, сама jQuery либо не была загружена, либо загрузилась некорректно.
Что делать с ошибкой $ is not defined
Сделайте так, чтобы сначала у вас корректно загружалась jQuery, и только потом — остальной код, который использует эту библиотеку. Обычно для этого достаточно поставить вызов jQuery раньше всех других вызовов.
Было:<script src="ВАШ СКРИПТ"></script>
<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js"></script>
Стало:<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js"></script>
<script src="ВАШ СКРИПТ"></script>
Если перемещение вызова jQuery не помогло
Проверьте, откуда вы берёте библиотеку jQuery. Может быть, вы берёте её с удалённого сайта, до которого ваш браузер не может дозвониться (Роскомнадзор постарался или просто сайт лежит). Тогда скачайте jQuery на компьютер и вызовите локально:
<script src="script/jquery.min.js"></script> <!--при этом не забудьте скачать и положить сюда библиотеку jQuery-->
<script src="ВАШ СКРИПТ"></script>
Простой способ убедиться, что jQuery загружается нормально, — скопировать её адрес из кода и вставить в адресную строку браузера. Если вам выведется программный код, значит, jQuery вам доступна и загружается. Если что-то пойдёт не так — вы увидите это на экране.
Например, попробуйте перейти по этой ссылке: https://yastatic.net/jquery/3.3.1/jquery.min.js — если она у вас открывается и вы видите месиво из кода, значит, jQuery для вас открылась.
Знак $ в JavaScript — это название сущности, через которую мы делаем всевозможные запросы с помощью jQuery.
jQuery — это дополнительная библиотека, которая упрощает работу с элементами на веб-странице. Например, если нам нужно с помощью JavaScript на лету поменять какую-то надпись на странице, то без jQuery нам бы пришлось сделать так:
document.getElementById('someElement').innerHTML='Some New Text';
А через jQuery всё то же самое делается так:
$("#someElement").html("Some New Text");
Знак доллара при отладке JS (то есть в консоли) — признак того, что в коде используется jQuery, это её фирменный знак.
jQuery настолько распространена, что на её основе уже делают другие библиотеки: всевозможные галереи, переключалки, интерфейсные штуки, формы и т. д. Чтобы такие библиотеки работали, сначала в браузере должна быть загружена сама jQuery, а уже потом — нужная вам библиотека.
Технически с точки зрения браузера $ — это просто объект в языке JavaScript. У него есть методы, которые должны быть прописаны, прежде чем браузер сможет их исполнить. И если на момент вызова этих методов они не были нигде прописаны, браузер справедливо возмутится. А они не будут прописаны только в одном случае: при загрузке jQuery что-то пошло не так.
Возможные причины незагрузки jQuery:
- Её просто забыли добавить в код.
- Она загружается с удалённого сайта, который сейчас для вас недоступен. Отключён интернет, сайт лежит, заблокирован или в его адресе опечатка.
- При загрузке что-то пошло не так, и вместо jQuery прилетело что-то другое.
- Уже после загрузки jQuery какой-то другой скрипт переопределил объект $ (и всё сломал).
- Браузер запретил загрузку скрипта с другого сайта.
- Она загружается после того, как её вызывают (а не до).
- Загружается какая-то испорченная версия jQuery (маловероятно).
xbat
-4
Junior Poster in Training
Banned
10 Years Ago
Dani
3,632
The Queen of DaniWeb
Administrator
Featured Poster
Premium Member
10 Years Ago
Mark this closed!!!!!
![]()
In the future, you can mark a question solved by clicking the link that appears beneath the reply editor.
xbat
-4
Junior Poster in Training
Banned
10 Years Ago
future, you can mark a question solved by clicking
thank you miss dani
8 Years Ago
thanks alot i spent 4 hours in serchin my error
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
185
Часто встречаются ошибки BX.ajax is not a function и BX is not defined.
Решается проблема добавлением следующих строк в начало файла вашего шаблона header.php:
CUtil::InitJSCore(); CJSCore::Init(array("fx")); CJSCore::Init(array('ajax')); CJSCore::Init(array("popup"));
Помощь проекту
Привет, меня зовут Вика! Я являюсь автором сайта Weblim.
Если Вам помогла данная статья, вы можете отблагодраить меня перечислив любую денежную сумму. Заранее спасибо!