За последние 24 часа нас посетили 18493 программиста и 1687 роботов. Сейчас ищет 1531 программист ...

Отправка формы на сервер через AJAX

Тема в разделе "JavaScript и AJAX", создана пользователем Serega_123, 21 мар 2017.

  1. Serega_123

    Serega_123 Новичок

    С нами с:
    24 фев 2017
    Сообщения:
    4
    Симпатии:
    0
    Всем привет! Очень нужна помощь. Не пойму почему форма не отправляется

    Вот форма, которую нужно отправить:

    <h3>Добавить комментарий</h3>
    <table>
    <form id="form_add_comment" action="" method="POST" />
    <tr>
    <td>Имя</td>
    </tr>
    <tr>
    <td>
    <input type="text" name="user_name" id="user_name" />
    </td>
    </tr>
    <tr>
    <td>Текст комментария</td>
    </tr>
    <tr>
    <td>
    <textarea id="text_comment" name="text_comment" rows="10" cols="70"></textarea>
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <input type="hidden" name="page_id" value='%id%' />
    <input name="add_comment" id="add_comment" type="submit" value="Добавить комментарий к статье"/ >
    </td>
    </tr>
    </form>
    </table>
    <div id="result_form"><div>


    Вот скрипт Аякса:


    $( document ).ready(function() {
    $("#add_comment").click(
    function(){
    sendAjaxForm('result_form', 'form_add_comment', '/lib/function_comment.php');
    return false;
    }
    );
    });

    function sendAjaxForm(result_form, ajax_form, url) {
    jQuery.ajax({
    url: "/lib/function_comment.php", //url страницы (action_ajax_form.php)
    type: "GET", //метод отправки
    dataType: "html", //формат данных
    data: jQuery("#form_add_comment").serialize(), // Сеарилизуем объект
    success: function(response) { //Данные отправлены успешно
    result = jQuery.parseJSON(response);
    document.getElementById(result_form).innerHTML = "Имя: "+result.user_name+"<br>Текст: "+result.comment_text+"<br>id: "+result.page_id;
    },
    error: function(response) { // Данные не отправлены
    document.getElementById(result_form).innerHTML = "Ошибка. Данные не отправленны.";
    }
    });
    }

    А вот файл обработчик:

    <?require_once "comment_class.php";


    if(isset($_POST["user_name"]) && isset($_POST["text_comment"]) && isset($_POST["page_id"]))
    {

    // Формируем массив для JSON ответа
    $result = array(
    'name' => $_POST["user_name"],
    'text_comment' => $_POST["text_comment"],
    'page_id' => $_POST["page_id"]
    );

    // Переводим массив в JSON
    echo json_encode($result);
    }
    ?>

    А вот что показывает консоль Храм при отправке:

    functions.js:4 Uncaught SyntaxError: Unexpected identifier
    Navigated to http://localhost/site/?view=articlecontent&id=72


    А вот что приходит в качестве ответа на страницу:

    {"name":"\u042f \u0412\u0430\u0441\u044f ","text_comment":"\u0412\u0441\u0435\u043c \u043f\u0440\u0438\u0432\u0435\u0442","page_id":"72"}
    Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at Z:\domains\localhost\site\lib\function_comment.php:15) in Z:\domains\localhost\site\lib\modules_class.php on line 25
     
  2. MouseZver

    MouseZver Суперстар

    С нами с:
    1 апр 2013
    Сообщения:
    7.799
    Симпатии:
    1.331
    Адрес:
    Лень
    и тут приходит добрый модератор Деонис и пишет:
    Отладка
    Дебаг
    Мануал
    что там еще забыл
     
  3. Drema

    Drema Новичок

    С нами с:
    20 фев 2017
    Сообщения:
    117
    Симпатии:
    30
    Подключая comment_class.php вы подключаете портал в ад, который неверно инициализирует сессии при именно таком вашем подключении (видимо). Уберите require_once, либо сделайте error_reporting(0); первой строкой (на худой конец).