Ajax $.Load Method Example of Loading Data from External File

jQuery Ajax Load HTML Page or External Html Page in div

Dynamically load HTML page in div tag using jquery; In this tutorial, you will learn how to load html page or external page content in div tag using jquery.

How to Load External Html Page into Div using jQuery

Using the jQuery ajax $.load method, you can load external html page or html page into a div.

jQuery Ajax $.load Method

Ajax $ .load () method is fetch the data or content, another page into a div, external HTML into div from the other pages or server. Ajax $ .load method sends asynchronous requests from server, retrieves the data from server and replaces content without refreshing/reloading the entire webpage or to load an external webpage into a div of a html page.

Syntax of jQuery Ajax $.load Method

Parameters of jQuery Ajax $.load Method

  • url: This is the required parameter. This is specifies the URL of the file you want to load.
  • data: This is used to sent some to the server with request.
  • success : This function to be executed when request succeeds.

Example – How to load external html page into a div using jquery

This example will demonstrate to you how to send HTTP load requests to the server and get the data from the server.

We need to create a html file name “load.html” and store into your web server and replace the below code here.

This is Ajax Loading Demo Example

You click on load content button, After that appear from other file

After that we need to create one file name load-demo.html and put the below code here.

       .formClass 
Click button to load new content inside DIV box

Output

Click button to load new content inside DIV box

Example demonstration

  • In this above ajax post() method example. The url parameter is first parameter of the $.load method and it help to retrieve the content or text from the web server.
  • The Next parameter data is a data to submit form data in JSON format, In pair of key value.
  • Success is a callback function that is executed when the request completes.
  1. jQuery | Event MouseUp () By Example
  2. Event jQuery Mouseleave By Example
  3. jQuery Event Mouseenter Example
  4. Event jQuery MouseOver() & MouseOut By Example
  5. keyup jquery event example
  6. Jquery Click() Event Method with E.g.
  7. Event jQuery. Blur By Example
  8. jQuery form submit event with example
  9. keydown function jQuery
  10. List of jQuery Events Handling Methods with examples
  11. Jquery Selector by .class | name | #id | Elements
  12. How to Get the Current Page URL in jQuery
  13. jQuery Ajax Get() Method Example
  14. get radio button checked value jquery by id, name, class
  15. jQuery Set & Get innerWidth & innerHeight Of Html Elements
  16. jQuery Get Data Text, Id, Attribute Value By Example
  17. Set data attribute value jquery
  18. select multiple class in jquery
  19. How to Remove Attribute Of Html Elements In jQuery
  20. How to Checked Unchecked Checkbox Using jQuery
  21. jQuery removeClass & addClass On Button Click By E.g.
  22. To Remove whitespace From String using jQuery
  23. jQuery Ajax Post() Method Example
  24. jQuery Ajax Get() Method Example
Читайте также:  Test driven development python django

Author Admin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Источник

.load()

.load( url [, data ] [, complete ] ) Returns: jQuery

Description: Load data from the server and place the returned HTML into the matched elements.

version added: 1.0 .load( url [, data ] [, complete ] )

Note: Prior to jQuery 3.0, the event handling suite also had a method named .load() . Older versions of jQuery determined which method to fire based on the set of arguments passed to it.

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is «success» or «notmodified»), .load() sets the HTML contents of the matched elements to the returned data. This means that most uses of the method can be quite simple:

If no element is matched by the selector — in this case, if the document does not contain an element with — the Ajax request will not be sent.

Callback Function

If a «complete» callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.

$( "#result" ).load( "ajax/test.html", function( )
alert( "Load was performed." );
>);

In the two examples above, if the current document does not contain an element with an ID of "result," the .load() method is not executed.

Request Method

The POST method is used if data is provided as an object; otherwise, GET is assumed.

Loading Page Fragments

The .load() method, unlike $.get() , allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html , but then jQuery parses the returned document to find the element with an ID of container . This element, along with its contents, is inserted into the element with an ID of result , and the rest of the retrieved document is discarded.

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , , or elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

Script Execution

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:

Here, any JavaScript loaded into #a as a part of the document will successfully execute.

However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

$( "#b" ).load( "article.html #target" );

Additional Notes:

  • Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

Examples:

Load another page's list items into an ordered list.

Источник

Примеры отправки 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'," и всё сразу заработало после этого. А я ведь ни один день ломал голову из-за этой ошибки!

Источник

Оцените статью