S
S
SaDiSST2016-08-30 05:05:21
PHP
SaDiSST, 2016-08-30 05:05:21

AJAX: rendering received records on the fly. How?

Hello Toaster!
The time has come for me to ask my question, dear gentlemen.
I apologize in advance for possible stupidity: I'm just a novice coder (I have a programmer, with all my desire, the language will not yet turn itself to be called). If for you, dear, my situation will remind you of the proverb “to get lost in three pines”, then know that I have been wandering in these pines for 3 or 4 days, periodically knocking my head on them. So, to business:

I'll start with the code:

.js:
function makeRecord(id) {
    var name    = $('#recorderName_'    + id).val();
    var email   = $('#recorderEmail_'   + id).val();
    var phone   = $('#recorderPhone_'   + id).val();
    var specId  = $('#recordToSpec_'    + id).val();
    var recId   = $('#recordId_'        + id).val();
    var time    = $('#recordedToTime_'  + id).val();

    var postData = {
        name:   name,
        email:  email,
        phone:  phone,
        time:   time,
        specId: specId
    };
    $.ajax({
        type: 'POST',
        url: "/index/createnewrecord/",
        data: postData,
        dataType: 'json',
        success: function(data) {
            if(data['success']) {
                alert(data['message']);
            } else {
                alert(data['message']);
            }
        }
    });
}


HTML:
<div class="specialist">
    <table cellspacing="2" cellpadding="2" border="1" width="90%">
        <tr>
            <th>Специальность</th>
            <th>ФИО</th>
            <th>Запись</th>
        </tr>

    {*Показываем каждого специалиста*}
    {foreach $specialists as $specialist name=ppls}
        <form action="/index/createnewrecord/" method="POST" id="newRecord">
            <tr>
                <td>{$specialist['speciality']}</td>
                <td>{$specialist['name']}</td>
                <td><a href="#" onClick="startNewRecord('{$specialist['id']}'); return false;">Записаться на прием</a></td>
            </tr>

        {*Таблица для записи к специалисту*}
            <tr class="hideme" id="newRecordTo_{$specialist['id']}">
                <td colspan="3">
                    <table border="1" cellpadding="1" cellspacing="1" width="100%">
                        <tr>
                            <th>Ваше ФИО</th>
                            <th>Телефон</th>
                            <th>e-mail</th>
                            <th>Дата+Время записи</th>
                            <th>&nbsp;</th>
                        </tr>
                        <tr>
                            <td><input      type="text"     id="recorderName_{$specialist['id']}"></td>
                            <td>+7 <input   type="text"     id="recorderPhone_{$specialist['id']}"></td>
                            <td><input      type="email"    id="recorderEmail_{$specialist['id']}"></td>
                            <td><input      type="datetime" id="recordedToTime_{$specialist['id']}"></td>
                            <td>
                                <input      type="hidden"   value="{$specialist['id']}" id="recordToSpec_{$specialist['id']}">
                                <input      type="button"   value="Записаться!" onClick="makeRecord('{$specialist['id']}');">
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </form>
        {/foreach}
        </table>
    </div>
{/if}

{*Если есть записи, показываем*}
{if isset($records) && $records !== 0}
<div id="displayRecords">
    <table cellpadding="4" cellspacing="3" border="2" width="65%">
        <tr>
            <th>#</th>
            <th>Записан на</th>
            <th>Запись от</th>
            <th>Специалист</th>
        </tr>

        {*Показываем каждую запись*}
        {foreach $records as $record name=records}
            <tr>
                <td>
                    <a href="#" onClick="showInfo('{$record['id']}'); return false;">#{$smarty.foreach.records.iteration}</a>
                </td>
                <td>{$record['date_recorded']}</td>
                <td>{$record['when_recorded']}</td>
                <td>{$record['to_whom']}</td>
            </tr>

            {*Подробности записей*}
            <tr class="hideme" id="recordId_{$record['id']}">
                <td colspan="4">
                    <table border="1" cellspacing="4" cellpadding="4" width="100%">
                        <tr>
                            <th>Записавшийся</th>
                            <th>e-mail</th>
                            <th>Телефон</th>
                        </tr>
                        <tr>
                            <td>
                                <input type="hidden" name="recorderName_{$record['id']}" value="{$record['who']}">
                                {$record['who']}
                            </td>
                            <td>{$record['email']}</td>
                            <td>{$record['phone']}</td>
                        </tr>
                    </table>
                </td>
            </tr>
        {/foreach}
    </table>
</div>
{/if}


PHP:
function createnewrecordAction() {

    $resData = null;

    $name   = isset($_POST['name'])     ? trim($_POST['name'])          : null;
    $email  = isset($_POST['email'])    ? trim($_POST['email'])         : null;
    $phone  = isset($_POST['phone'])    ? trim(intval($_POST['phone'])) : null;
    $time   = isset($_POST['time'])     ? $_POST['time']                : null;
    $specId = isset($_POST['specId'])   ? $_POST['specId']              : null;

    $resData    = checkRecordParams($name, $email, $phone, $time, $specId);


    if(!$resData) {
        $record = makeNewRecord($name, $email, $phone, $time, $specId);

        if($record['success']) {
            $resData['success'] = true;
            $resData['message'] = 'Заявка подана';
        } else {
            $resData['success'] = false;
            $resData['message'] = 'Пожалуйста, проверьте поля ввода';
        }
    }

    echo json_encode($resData);
}


In general, I need to render fresh records with AJAX, without reloading. Of course, I heard about .append() and .html(). Moreover, he tried to act through them, but either because of a lack of intelligence, or because of an overabundance of chromosomes, he could not create anything sensible. Help, huh?

PS: Suggestions for code optimization are also accepted. They will suddenly appear.

Thank you in advance.
Sincerely,
SaDiSST.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
trushka, 2016-08-30
@trushka

Let PHP return not json, but banal html - use the same code as {*Show each entry*}. And then you insert it into the table $('#displayRecords').append(data). Only dataType: 'json' in the request is not needed then

S
SaDiSST, 2016-09-01
@SaDiSST

trushka : I partially implemented what you suggested, however, I left the json. I redid the logic of rendering pages and ajaxes a bit, and in connection with this, a question arose, but first the code. Notice the input="button" .display :
HTML:

spoiler
<table cellpadding="4" cellspacing="3" border="2" width="65%"  class="displayRecords">
        <tr>
            <th>show</th>
            <th>Заявка на</th>
            <th>К специалисту</th>
        </tr>

        {*Показываем каждую запись*}
        {foreach $records as $record name=records}
            <tr>
                <td>
                    <!--<input type="hidden" id="record_{$record['id']}" value="{$record['id']}">-->
                    <input type='button' onClick="displRec();" value='info' class="display">
                </td>
                <td>{$record['date_recorded']}</td>
                <td>{$record['to_whom']}</td>
            </tr>

            {*Подробности записей*}
            <tr class="hideme" id="addInfo">
                <td colspan="4">
                    <table border="1" cellspacing="4" cellpadding="4" width="100%">
                        <tr>
                            <th>Записавшийся</th>
                            <th>e-mail</th>
                            <th>Телефон</th>
                        </tr>
                        <tr>
                            <td>
                                <input type="hidden" name="" value="">
                                {$record['who']}
                            </td>
                            <td>{$record['email']}</td>
                            <td>{$record['phone']}</td>
                        </tr>
                    </table>
                </td>
            </tr>
        {/foreach}
    </table>

JS:
spoiler
function displRec() {
    $('.display').on('click', function() {
        if($(this).next('#addInfo').css('display') != 'table-row'){
            $(this).next('#addInfo').show();
        } else {
            $(this).next('#addInfo').hide();
        }
    });
}

In general, I'm trying to extract data from the record without passing the ID to the button. You can ignore .next() - an unsuccessful experiment, like .parent().parent(), and so on. The question is how it can be implemented. Can you help?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question