Ajax jquery html success

ajaxSuccess event

.on( «ajaxSuccess», handler ) Returns: jQuery

Description: Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.

version added: 1.7 .on( «ajaxSuccess», handler )

This page describes the ajaxSuccess event. For the deprecated .ajaxSuccess() method, see .ajaxSuccess() .

Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all registered ajaxSuccess handlers are executed at this time.

To observe this method in action, set up a basic Ajax load request:

div class="trigger">Trigger div>
div class="result"> div>
div class="log"> div>

Attach the event handler to any element:

$( document ).on( "ajaxSuccess", function( )
$( ".log" ).text( "Triggered ajaxSuccess handler." );
> );

Now, make an Ajax request using any jQuery method:

$( ".trigger" ).on( "click", function( )
$( ".result" ).load( "ajax/test.html" );
> );

When the user clicks the element with class trigger and the Ajax request completes successfully, the log message is displayed.

All ajaxSuccess handlers are invoked, regardless of what Ajax request was completed. If you must differentiate between the requests, you can use the parameters passed to the handler. Each time an ajaxSuccess handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, you can restrict the callback to only handling events dealing with a particular URL:

$( document ).on( "ajaxSuccess", function( event, xhr, settings )
if ( settings.url == "ajax/test.html" )
$( ".log" ).text( "Triggered ajaxSuccess handler. The Ajax response was: " +
xhr.responseText );
>
> );

Note: You can get the returned Ajax contents by looking at xhr.responseXML or xhr.responseText for xml and html respectively.

Additional Notes:

  • As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with .on( "ajaxSuccess", . ) , must be attached to document .
  • If $.ajax() or $.ajaxSetup() is called with the global option set to false , the ajaxSuccess event will not fire.

Example:

Show a message when an Ajax request completes successfully.

  • Ajax
    • Global Ajax Event Handlers
    • Helper Functions
    • Low-Level Interface
    • Shorthand Methods
    • Deprecated 1.3
    • Deprecated 1.7
    • Deprecated 1.8
    • Deprecated 1.9
    • Deprecated 1.10
    • Deprecated 3.0
    • Deprecated 3.2
    • Deprecated 3.3
    • Deprecated 3.4
    • Deprecated 3.5
    • Basics
    • Custom
    • Fading
    • Sliding
    • Browser Events
    • Document Loading
    • Event Handler Attachment
    • Event Object
    • Form Events
    • Keyboard Events
    • Mouse Events
    • Class Attribute
    • Copying
    • DOM Insertion, Around
    • DOM Insertion, Inside
    • DOM Insertion, Outside
    • DOM Removal
    • DOM Replacement
    • General Attributes
    • Style Properties
    • Collection Manipulation
    • Data Storage
    • DOM Element Methods
    • Setup Methods
    • Properties of jQuery Object Instances
    • Properties of the Global jQuery Object
    • Attribute
    • Basic
    • Basic Filter
    • Child Filter
    • Content Filter
    • Form
    • Hierarchy
    • jQuery Extensions
    • Visibility Filter
    • Filtering
    • Miscellaneous Traversing
    • Tree Traversal
    • Version 1.0
    • Version 1.0.4
    • Version 1.1
    • Version 1.1.2
    • Version 1.1.3
    • Version 1.1.4
    • Version 1.2
    • Version 1.2.3
    • Version 1.2.6
    • Version 1.3
    • Version 1.4
    • Version 1.4.1
    • Version 1.4.2
    • Version 1.4.3
    • Version 1.4.4
    • Version 1.5
    • Version 1.5.1
    • Version 1.6
    • Version 1.7
    • Version 1.8
    • Version 1.9
    • Version 1.11 & 2.1
    • Version 1.12 & 2.2
    • Version 3.0
    • Version 3.1
    • Version 3.2
    • Version 3.3
    • Version 3.4
    • Version 3.5
    • Version 3.6
    • Version 3.7

    Books

    Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath

    Источник

    Примеры отправки AJAX JQuery

    AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

    Полное описание функции AJAX на jquery.com.

    GET запрос

    Запрос идет на index.php с параметром « text » и значением « Текст » через метод GET.
    По сути это то же самое что перейти в браузере по адресу – http://site.com/index.php?text=Текст

    В результате запроса index.php вернет строку «Данные приняты – Текст», которая будет выведена в сообщении alert.

    $.ajax(< url: '/index.php', /* Куда пойдет запрос */ method: 'get', /* Метод передачи (post или get) */ dataType: 'html', /* Тип данных в ответе (xml, json, script, html). */ data: , /* Параметры передаваемые в запросе. */ success: function(data) < /* функция которая будет выполнена после успешного запроса. */ alert(data); /* В переменной data содержится ответ от index.php. */ >>);

    Код можно сократить используя функцию $.get

    $.get('/index.php', , function(data)< alert(data); >);

    Код файла index.php

    echo 'Данные приняты - ' . $_GET['text'];

    GET запросы могут кэшироваться браузером или сервером, чтобы этого избежать нужно добавить в функцию параметр – cache: false .

    POST запросы

    $.ajax(< url: '/index.php', method: 'post', dataType: 'html', data: , success: function(data) < alert(data); >>);

    Или сокращенная версия – функция $.post

    $.post('/index.php', , function(data)< alert(data); >);

    Код файла index.php

    echo 'Данные приняты - ' . $_POST['text'];

    POST запросы ни когда не кэшироваться.

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

    При отправке формы применяется функция serialize() , подробнее на jquery.com.

    Она обходит форму и собирает названия и заполненные пользователем значения полей и возвращает в виде массива – .

    • Кнопки формы по которым был клик игнорируются, в результате функции их не будет.
    • serialize можно применить только к тегу form и полям формы, т.е. $('div.form_container').serialize(); – вернет пустой результат.

    Пример отправки и обработки формы:

    Код файла handler.php

    if (empty($_POST['login'])) < echo 'Укажите логин'; >elseif (empty($_POST['password'])) < echo 'Укажите пароль'; >else

    Работа с JSON

    Идеальный вариант когда нужно работать с массивами данных.

    Короткая версия

    $.getJSON('/json.php', function(data) < alert(data.text); alert(data.error); >);

    $.getJSON передает запрос только через GET.

    Код файла json.php

    header('Content-Type: application/json'); $result = array( 'text' => 'Текст', 'error' => 'Ошибка' ); echo json_encode($result);

    Возможные проблемы

    При работе с JSON может всплыть одна ошибка – после запроса сервер отдал результат, все хорошо, но метод success не срабатывает. Причина кроется в серверной части (PHP) т.к. перед данными могут появится управляющие символы, например:

    Управляющие символы в ответе JSON

    Из-за них ответ считается не валидным и считается как ошибочный запрос. В таких случаях помогает очистка буфера вывода ob_end_clean (если он используется на сайте).

    . // Очистка буфера ob_end_clean(); header('Content-Type: application/json'); echo json_encode($result, JSON_UNESCAPED_UNICODE); exit();

    Выполнение JS загруженного через AJAX

    В JQuery реализована функция подгруздки кода JS через AJAX, после успешного запроса он будет сразу выполнен.

    Или

    Дождаться выполнения AJAX запроса

    По умолчанию в JQuery AJAX запросы выполняются асинхронно. Т.е. запрос не задерживает выполнение программы пока ждет результатов, а работает параллельно. Простой пример:

    var text = ''; $.ajax( < url: '/index.php', method: 'get', dataType: 'html', success: function(data)< text = data; >>); alert(text); /* Переменная будет пустая. */

    Переменная text будет пустая, а не как ожидается текст который вернул index.php Чтобы включить синхронный режим нужно добавить параметр async: false .
    Соответственно синхронный запрос будет вешать прогрузку страницы если код выполняется в страницы.

    var text = ''; $.ajax( < url: '/index.php', method: 'get', dataType: 'html', async: false, success: function(data)< text = data; >>); alert(text); /* В переменной будет результат из index.php. */

    Отправка HTTP заголовков

    $.ajax(< url: '/index.php', method: 'get', dataType: 'html', headers: , success: function(data) < console.dir(data); >>);

    В PHP они будут доступны в массиве $_SERVER , ключ массива переводится в верхний регистр с приставкой HTTP_ , например:

    Обработка ошибок

    Через параметр error задается callback-функция, которая будет вызвана в случаи если запрашиваемый ресурс отдал 404, 500 или другой код.

    $.ajax(< url: '/index.php', method: 'get', dataType: 'json', success: function(data)< console.dir(data); >, error: function (jqXHR, exception) < if (jqXHR.status === 0) < alert('Not connect. Verify Network.'); >else if (jqXHR.status == 404) < alert('Requested page not found (404).'); >else if (jqXHR.status == 500) < alert('Internal Server Error (500).'); >else if (exception === 'parsererror') < alert('Requested JSON parse failed.'); >else if (exception === 'timeout') < alert('Time out error.'); >else if (exception === 'abort') < alert('Ajax request aborted.'); >else < alert('Uncaught Error. ' + jqXHR.responseText); >> >);

    Комментарии 4

    В примере Отправка формы через AJAX страница перезагружается. Видимо нужно добавить return false после $.ajax(<>);

    $("#form").on("submit", function() $.ajax( url: '/handler.php', 
    method: 'post',
    dataType: 'html',
    data: $(this).serialize(),
    success: function(data) $('#message').html(data);
    >
    >);
    return false;
    >);
    $("#form").on("submit", function(e). 
    e.preventDefault();
    >)

    У меня вообще не работали POST запросы, особенно для меня, для начинающего было очень сложно, работали только GET, очень долго голову ломал почему так происходит. Нашёл пример на другом сайте, который работал долго сравнивал и думал почему так. Здесь пример не работает, а на другом сайте рабочий пример оказался.
    Так вот:
    $.ajax( url: '/index.php',
    method: 'post',
    dataType: 'html',
    data: ,
    success: function(data) alert(data);
    >
    >);
    Оказывается чтобы у меня заработали именно POST запросы надо было поменять строчку:
    "method: 'post'," на:
    "type: 'post'," и всё сразу заработало после этого. А я ведь ни один день ломал голову из-за этой ошибки!

    Источник

    Читайте также:  text-transform
Оцените статью