AJAX запрос не публиковать данные из события / формы нажатия кнопки - PullRequest
1 голос
/ 12 марта 2020

Я пытаюсь использовать AJAX запрос для соединения с моим сервером. Я попытался передать значение с помощью события click на кнопке «Редактировать», которая содержит значение для публикации. Я продолжаю получать сообщения о том, что мой «пользователь» не указан, хотя кнопка и код кажутся правильными.

Мой код - переведенная версия этого сообщения StackOverflow для sqlsrv и MS SQL: Как передать значение с помощью кнопки в bootstrap модальное и обновить значения в базе данных mysql, используя только php

Моя кнопка содержит правильное значение, но не отправляет сообщение получателю . php. Пример кода моего ajax запроса:

$('#editModal').on('show.bs.modal', function (event) {
                    var modal = $(this);

                    // Extract the user id from the modal triggering button.
                    var editButton = $(event.relatedTarget);
                    var userId = editButton.val();

                    // Set the user id in the modal (read prior to update
operation).
                    modal.find('#userId').val(userId);
                    modal.find('#biography').val(biography);
                    modal.find('#degreesobtained').val(degreesobtained);
                    modal.find('#aoi').val(aoi);
                    modal.find('#schwrk').val(schwrk);

                    // Fetch the user details and update the modal's content with them.
                    $.ajax({
                        method: 'post',
                        dataType: 'json',
                        async: false,
                        url: 'get-user.php',
                        data: {
                            'userId': userId

                        },
                        success: function (response, textStatus, jqXHR) {
                            modal.find('.modal-title').text('Edit user ' + response.id);
                            modal.find('#degreesobtained').val(response.degreesobtained);
                            modal.find('#aoi').val(response.aoi);
                            modal.find('#schwrk').val(response.schwrk);

                            switch (response.approve) {
                                case 'N':
                                    modal.find('#approveOptionNo').prop('checked', true);
                                    break;
                                case 'Y': // No break.
                                default:
                                    modal.find('#approveOptionYes').prop('checked', true);
                                    break;
                            }

                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            /*
                             * If the status code of the response is a custom one, defined by 
                             * the developer - here 420, then the corresponding error message 
                             * is displayed. Otherwise, the displayed message will be a general 
                             * user-friendly one - so, that no system-related infos will be shown.
                             */
                            var message = (jqXHR.status === 420)
                                    ? jqXHR.statusText
                                    : 'An error occurred during your request. Please try again.';

                            displayModalAlert(modal, 'danger', message);
                            disableModalControls(modal);
                        },
                        complete: function (jqXHR, textStatus) {
                            //...
                            var message = (jqXHR.status === 600)
                                    ? jqXHR.statusText
                                    : 'What the hell.';
                        }
                    });
                });

Соответствующий код для get-user. php:

    // Get the user id.
    $userId = $_POST['userId'];

    /*
     * The SQL statement to be prepared. 
     */
    $sqluserGrab = 'SELECT * 
        FROM myTable
        WHERE ID = ?';
    $statement = sqlsrv_prepare( $conn, $sqluserGrab, array( &$userid));

     /*
     * Bind variables for the parameter markers (?) in the 
     * SQL statement that was passed to prepare().
     */

    sqlsrv_execute( $statement );

 /*
 * Fetch data and save it into an array:
 * 
 */
$user = sqlsrv_fetch_array( $statement, SQLSRV_FETCH_ASSOC);

 /*
 * When no records are found, fetch_array() 
 * returns NULL. In this case throw an error.
 */
    if (!isset($user)) {
        header('HTTP/1.1 420 No user found by the given criteria.');
        exit();
    }

echo json_encode($user);
...