- AJAX with POST and PHP
- How to Create a jQuery Ajax Post with PHP
- jQuery Post Form Data with .Ajax() Method
- JQuery Post Form Data with .Post() Method
- jQuery Post JSON Data with .Post() Method
- Why to Use jQuery for Ajax Requests?
- About jQuery Ajax Get() and Post() Methods
- Примеры отправки AJAX JQuery
- GET запрос
- Код можно сократить используя функцию $.get
- Код файла index.php
- POST запросы
- Или сокращенная версия – функция $.post
- Код файла index.php
- Отправка формы через AJAX
- Код файла handler.php
- Работа с JSON
- Короткая версия
- Код файла json.php
- Возможные проблемы
- Выполнение JS загруженного через AJAX
- Или
- Дождаться выполнения AJAX запроса
- Отправка HTTP заголовков
- Обработка ошибок
- Комментарии 4
AJAX with POST and PHP
Another way to send data from a Web page to the server is via POST method.
With Ajax, the request for sending data with POST uses the open() method of the XMLHttpRequest object, its syntax is:
— the «POST «is the method of transfer
— the URL represents the address of the PHP file
— bool is a Boolean value (true or false)
The difference from GET, in sending data via POST, consists of two things:
1. After creating the request with «open()» and before calling the «send()» method, it is used another method of the XMLHttpRequest object, namely setRequestHeader() , using the syntax:
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
— This function indicate what type of content we are including, it sends a header to tell the server to recognize the sent data as if they were sent with POST (like data from Forms).
2. The data we want to transmit to the PHP script, value pairs «index=value», are added as a string parameter in the send() method.
Processing the server response is the same as with the GET.
— To understand how to send data with AJAX using POST, apply and study the following example:
1) Create on the server a PHP file, named «test_post.php», and add into it the following code:
— This is a relatively simple PHP script. If it receives data via POST, with index of ‘test’, takes its value in the $str variable and, with «echo» returns a string that contains the received text and the number of characters and words in that text.
2) Create an HTML file on the server (for example, named «ajax_post.html») in the same directory where the file «test_post.php» is, and add the following code into it.
Click
— The Ajax script is executed when the user click on the «Click» word. It calls the ajaxrequest() function with two parameters. The first parameter represents the name of the php file where the data will be sent, and the second parameter is the ID of the tag where the server response will be displayed.
— The ajaxrequest() function gets the text from the tag with and add it in the «the_data» variable, as the pair of the index «test».
— The open() contain the sending method (POST), the name of the php file and true to handle the request asynchronously ( request.open(«POST», php_file, true); ).
— The setRequestHeader() method is added to the request, to indicate that we send data as a content of a Form (with POST)
— After the request is sent with data we want to transmit to PHP ( request.send(the_data); ), when the response is completely received ( request.readyState==4 ), it displays it with the document.getElementById(tagID).innerHTML = request.responseText; instruction.
— When you open the «ajax_post.html» file from the server, will display the falowing result. Test it yourself.Click
The advantage of using POST is that you can send more data content than with the GET method (which is limited to a total of 1024 characters).
How to Create a jQuery Ajax Post with PHP
In this short tutorial, we are going to share with you how to create a jQuery Ajax post request with PHP.
Also, you can see how to post JSON data with jQuery easily and quickly.
After checking out this tutorial, you will be able to create ajax post requests much more easily. What you need is looking through the options below.
jQuery Post Form Data with .Ajax() Method
Using the .ajax() method is one of the best solutions to the problem. Here is how you should act to create a jQuery post request with this method:
html> html> head> title>jQuery post form data with .ajax() method by codeofaninja.com title> style> div < margin: 10px; > style> head> body> h1>jQuery post form data with the .ajax() method h1> div>Filling out and submitting the form below to receive a response. div> form id="userForm" action="/form/submit" method="post"> div> input type="text" name="firstname" placeholder="Firstname" /> div> div> input type="text" name="lastname" placeholder="Lastname" /> div> div> input type="email" name="email" placeholder="Email" /> div> div> input type="submit" value="Submit" /> div> form> div id="response"> div> script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "> script> script> $(document).ready(function( ) < $('#userForm').submit(function( ) < // showing that something is loading $('#response').html("Loading response. "); /* * 'post_receiver.php' - where you will be passing the form data * $(this).serialize() - for reading form data quickly * function(data) <. - data includes the response from post_receiver.php */$.ajax(< type: 'POST', url: 'post_receiver.php', data: $(this).serialize() >) .done(function(data) < // demonstrate the response $('#response').html(data); >) .fail(function( ) < // if posting your form failed alert("Posting failed."); >); // to restrain from refreshing the whole page, it returns false; >); >); script> body> html>
JQuery Post Form Data with .Post() Method
The .post method is considered a shorthand for the .ajax method. Its syntax is more descriptive. See how to use it correctly:
html> html> head> title>jQuery post form data using .post() method by codeofaninja.com title> style> div < margin: 15px; > style> head> body> h1>jQuery post form data using .post() method h1> div>Filling out and submitting the form below to receive a response. div> form id="userForm" action="/form/submit" method="post"> div> input type="text" name="firstname" placeholder="Firstname" /> div> div> input type="text" name="lastname" placeholder="Lastname" /> div> div> input type="email" name="email" placeholder="Email" /> div> div> input type="submit" value="Submit" /> div> form> div id="response"> div> script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "> script> script> $(document).ready(function( ) < $('#userForm').submit(function( ) < // showing that something is loading $('#response').html("Loading response. "); /* * 'post_receiver.php' - where you will be passing the form data * $(this).serialize() - for reading form data quickly * function(data) <. - data includes the response from post_receiver.php */$.post('post_receiver.php', $(this).serialize(), function(data) < // demonstrate the response $('#response').html(data); >).fail(function( ) < //if posting your form fails alert("Posting failed."); >); // to restrain from refreshing the whole page, the page returns false; >); >); script> body> html>
jQuery Post JSON Data with .Post() Method
As an additional information, here, we provide you with an example on how to post JSON data. For that purpose, you need to generate a JSON string and post it as shown below:
html> html> head> title>jQuery post JSON data using .post() method by codeofaninja.com title> head> body> h1>jQuery post JSON data with .post() method h1> div>Click the button below to receive a response. div> input type="button" value="Post JSON" id="postJson" /> div id="response"> div> script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "> script> script> $(document).ready(function( ) < $('#postJson').click(function( ) < // showing that something is loading $('#response').html("Loading response. "); /* * 'post_receiver.php' - where you will be passing the form data * $(this).serialize() - for reading form data easily * function(data) <. - data includes the response from post_receiver.php */$.post('post_receiver.php', < user_id: "143", username: "ninjazhai", website: "https://codeofaninja.com/" >, function(data) < // demonstrate the response $('#response').html(data); >).fail(function( ) < // if posting your form failed alert("Posting failed."); >); // to restrain from refreshing the whole page page returns false; >); >); script> body> html>
Why to Use jQuery for Ajax Requests?
In this snippet, we represented to you several ways of making ajax post requests with jQuery. You may ask why to use it. The reason to use it in your practice is apparent: it provides you with the simplest, short and readable code.
About jQuery Ajax Get() and Post() Methods
These methods are used for requesting data from the server using HTTP get or post request.
They are mainly applied for implementing request and response between the client and the server.
Get is used for requesting data from a particular resource. Post is used for submitting data to be processed to a particular resource.
Примеры отправки 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) т.к. перед данными могут появится управляющие символы, например:
Из-за них ответ считается не валидным и считается как ошибочный запрос. В таких случаях помогает очистка буфера вывода 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’,» и всё сразу заработало после этого. А я ведь ни один день ломал голову из-за этой ошибки!