Как решить "Uncaught ReferenceError: $ не определено" в подпрограмме цикла - PullRequest
0 голосов
/ 11 мая 2019

Погуглил все подобные вопросы здесь, но без полезного ответа.Я получаю сообщение об ошибке «Uncaught ReferenceError: $ не определено» при попытке передать некоторые данные в файл update.php с помощью ajax.

Мой код (php) получает данные из SELECT (MySQL) и создаеттаблицы while ($ row = mysqli_fetch_assoc ($ result) . Внутри каждой динамически генерируемой таблицы я помещаю поле редактирования для каждой строки результата, чтобы пользователь мог просматривать данные результата, вводить некоторые примечания и сохранятьКороче говоря, когда пользователь нажимает на значок в таблице, щелчок вызывает функцию updateNotes (), где я использую ajax для передачи в файл update.php заметок, написанных пользователем.Вложенная динамическая структура построенных таблиц, я поместил здесь часть кода (упрощенная без динамических переменных и вложенности) с действительной частью AJAX.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<?php
// get all data from a SELECT and "while($row = mysqli_fetch_assoc($result)" I set $count to a number that increases for each row of result
//then show some things
//let's say that every table has a suffix "_n" for all its elements, where "n" is the value of $count
// to focus on my issue, hereafter I don't put the dynamic generation of names, but simply will use the suffix "_n"

echo "<form method='post' id='form_edit_n' name='form_edit_n' action='update.php'>";
    // echo some data from the SELECT query
    // also echo some hidden data from the SELECT query, among them there's "type_a_data_n" hidden field (same id and name)
    echo "<img src='showEditorField.png' id='showEditorField_n' name='showEditorField_n' onclick='editor_n()'/>";
    // to have a different editing field for each recurrence found with the SELECT
echo "</form>";
?>

<script type="text/javascript">

// do some things non relevant as far as my issue is concerned, such as show and hide icons and fields
// among the rest, the function "editor_n()" shows an input field dynamically named let's say 'note_n'
// "editor_n()" also shows the icon "iconEditConfirm.png" with id and name "iconEditConfirm", that has "onclick='updateNotes()'"
// file update.php listens for $_POST["data_type_a"] and $_POST["note"]
// now the following is the function updateNotes()

function updateNotes() {
    var note_x = 'note_n';
    var type_a_data_x = 'type_a_data_n';
    $.ajax({
        type: 'POST',
        url: 'update.php',
        data: {'data_type_a': type_a_data_x, 'note': note_x},
        success:function(){
            // here I don't know how to get the return from update.php
        }
    });
}

// and this is the update.php code

<?php 

// make a connection to db, result is $conn

$note = $_POST["note"];
$data_type_a = $_POST["data_type_a"];

$sqlupdatenote = "UPDATE table SET note='$note' WHERE column='$data_type_a'";
if (mysqli_query($conn, $sqlupdatenote)) {
    echo "Updated note";
    return;
} else {
    echo "Error updating";
    return;
}

mysqli_close($conn);

?>

Как я могу исправить «Uncaught ReferenceError: $ is"не определено" проблема? Кроме того, правильно ли передавать данные в js-переменные, используя приведенный выше синтаксис?

Просто обновление: посмотрите наСетевой анализ в Firebug, jQuery не загружен, несмотря на правильную ссылку.

1 Ответ

0 голосов
/ 13 мая 2019

$ не определено означает, что вы пропустили ссылку на вашу библиотеку jquery. Эта ссылка на CDN поможет вам ""

...