J
J
Johnny Show2018-06-07 23:23:22
PHP
Johnny Show, 2018-06-07 23:23:22

How can I pass edited data from a modal window using ajax and smarty?

There is a task to transfer the edited data from a modal window using ajax.
I did not make the modal window itself through ajax, but implemented it through bootstrap.
In response, ajax sends html instead of json.
I can do a separate task of implementing data transfer via json. But when you still need to use OOP and smart, then difficulties arise.
did not post data processing methods, tk. I think it's not about them, and it's not about the model, but most likely in the controller <-> ajax bundles.
I hope you can tell me the correct implementation.

Controller

class CabinetController
{
    /**
     * Action для страницы "Кабинет пользователя"
     */
    public function actionIndex()
    {
        // Получаем идентификатор пользователя из сессии
        $userId = User::checkLogged();

        //> Получаем информацию о пользователе из БД
        $user = User::getUserById($userId);
        //<

        $smarty = new Smarty();
        //>инициализация переменных
        // Заполняем переменные для полей формы
        //>инициализация переменных

        $name = $user['name'];
        $email = $user['email'];
        $password = $user['password'];
        $phone = $user['phone'];
        $address = $user['address'];

        // Флаг результата
        $result = false;
        $resData = array();
        // Обработка формы
        if (isset($_POST['submit'])) {
            // Если форма отправлена
            // Получаем данные из формы редактирования
            $name = $_POST['name'];
            $password = $_POST['password'];
            $phone = ($_POST['phone']) ? clearInt($_POST['phone']) : null;
            $address = ($_POST['address']) ? clearData($_POST['address']) : null;

            // Флаг ошибок
            $errors = false;

            // Валидируем значения
            if (!User::checkName($name)) {
                $errors[] = 'Имя не должно быть короче 2-х символов';
            }
            if (!User::checkPassword($password)) {
                $errors[] = 'Пароль не должен быть короче 6-ти символов';
            }


            if ($errors == false) {


                // Если ошибок нет, сохраняет изменения профиля
                $result = User::edit($userId, $name, $password, $phone, $address);


            }
;
            if($result){
                $resData['success'] = 1;
                $resData['message'] = 'Данные сохранены!';
            }else{
                $resData['success'] = 0;
                $resData['message'] = 'Ошибка сохранения данных!';

            }

            $smarty->assign('errors', $errors);
            echo json_encode($resData,JSON_UNESCAPED_UNICODE);

        }

        $smarty->assign('pageTitle', 'Кабинет');
        $smarty->assign('name', $name);
        $smarty->assign('email', $email);
        $smarty->assign('password', $password);
        $smarty->assign('phone', $phone);
        $smarty->assign('address', $address);
        $smarty->assign('result', $result);
        $smarty->assign('resData', $resData);

        $smarty->display(ROOT.'/views/default/header.tpl');
        $smarty->display(ROOT.'/views/default/cabinet.tpl');
        $smarty->display(ROOT.'/views/default/footer.tpl');
    }
}


view
{*Модальное окно редактирования данных пользователя*}
<div class="modal" id="modal-1">

    <div class="modal-dialog">

        <div class="modal-content">

            <div class="modal-header">
                <button class="close" type="button" data-dismiss="modal">
                    <i class="fa fa-close"><strong>x</strong></i>
                </button>

                {if $result}
                    <p class="regOk">Данные отредактированы!</p>
                {else}
                    {if isset($errors) && is_array($errors)}
                        <ul>
                            {foreach from=$errors item=$err}
                                <li> <span class="error"> - {$err}</span></li>
                            {/foreach}
                        </ul>
                    {/if}

                <div class="modal-4"> Редактирование данных</div>
            </div>


            <div class="modal-body">


                <form action="" method="post" id="modForm" role="form">
                    <div class="form-group">
                        <label for="name">Имя<span class="error">*</span></label>
                        <input type="text" name="name" class="form-control" id="name" placeholder="Введите имя" value="{$name}"/>
                        <p class="help-block">Например: John</p>
                    </div>

                    <div class="form-group">
                        <label for="password">Пароль<span class="error">*</span></label>
                        <input type="password" name="password" class="form-control" id="password"  placeholder="Введите пароль" value="{$password}"/>
                        <p class="help-block">Не меньше шести символов </p>
                    </div>

                    <div class="form-group">
                        <label for="phone">Телефон</label>

                        <input type="text"   name="phone" class="form-control" id="phone" placeholder="Введите ваш телефон" value="{$phone}"/>


                    </div>
                    <div class="form-group">
                        <label for="address">Адрес</label>
                        <input type="text" name="address" class="form-control" id="address" placeholder="Введите адрес" value="{$address}"/>
                    </div>

                    <div id='messageShow'></div>


                    <input type="submit" name="submit" id="done"  class="btn btn-default" value="Сохранить"/>
                    {*<input type="button" name="button" id="done"   class="btn btn-default"  value="Сохранить"/>*}

                </form>

            </div>
            {/if}

            <div class="modal-footer">
                <button class="btn btn-danger" type="button" data-dismiss="modal">Отмена</button>

            </div>

        </div>
    </div>

</div>

<section xmlns="http://www.w3.org/1999/html">
    <div class="container">
        <div class="row">

            <h3>Кабинет пользователя</h3>
            {if $name}
            <h4>Привет, {$name}!</h4>
            {else}
            <h4>Привет, {$email}!</h4>
            {/if}


            <ul>
                <li><a href="" data-toggle="modal" data-target="#modal-1">Редактировать данные</a></li>
            </ul>
{*Данные пользователя*}
            <div class="col-sm-4 col-sm-offset-4 padding-right">
                <h3>Ваши регистрационные данные:</h3>
                <table class="table table-bordered table-condensed" cellpadding="1" cellspacing="1">
                    <thead>

                    <tr class="success">
                        <th>Имя</th>
                        <th>Почта</th>
                        <th>Пароль</th>
                        <th>Телефон</th>
                        <th>Адрес</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td>{$name}</td>
                        <td>{$email}</td>
                        <td>{$password}</td>
                        <td>{$phone}</td>
                        <td>{$address}</td>
                    </tr>

                    </tbody>


                </table>

            </div>

        </div>

    </div>
</section>


model

public static function edit($id, $name, $password, $phone, $address)
    {
        // Соединение с БД
        $db = Db::getConnection();

        // Текст запроса к БД
        $sql = "UPDATE users 
            SET name = :name, password = :password, phone = :phone, address = :address 
            WHERE id = :id";

        // Получение и возврат результатов. Используется подготовленный запрос
        $result = $db->prepare($sql);
        $result->bindParam(':id', $id, PDO::PARAM_INT);
        $result->bindParam(':name', $name, PDO::PARAM_STR);
        $result->bindParam(':password', $password, PDO::PARAM_STR);
        $result->bindParam(':phone', $phone, PDO::PARAM_STR);
        $result->bindParam(':address', $address, PDO::PARAM_STR);
        return $result->execute();
    }

js

$("#modForm").submit(function(e){
        e.preventDefault();

                    $.ajax({
                        type: 'POST',
                        async: true,
                        url: '/cabinet/',
                        data: postData,
                        dataType: 'json',

                        success: function (data) {
                            if (data['success']) {
                                console.log(data);

                                alert(data[''message']);
                            } else {
                                alert(data['message']);
                            }
                        }
                    });
              
    });

    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2018-06-09
@ThunderCat

There is a task to transfer the edited data from a modal window using ajax.

so does it work? Judging by
Well then, the biggest problem is which one needs to be changed todataType: 'json',dataType: 'html',

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question