Ajax POST request with JQuery and PHP — Tutsmake

How to Insert Form Data Using jQuery Ajax in PHP MySQL

insert data in MySQL db in PHP using jquery ajax without page refresh. In this tutorial, you will learn how to create and submit a simple form in PHP and store from data into MySQL database using jQuery ajax.

And this tutorial also guides on how to send data to MySQL database using AJAX + jQuery + PHP without reloading the whole page and show a client-side validation error message if it has an error in the form.

How to Insert Data to MySQL Database from PHP using jQuery Ajax

  • Step 1 – Create Database And Table
  • Step 2 – Create a Database Connection File
  • Step 3 – Create An Ajax POST Form in PHP
  • Step 4 – Create An Ajax Data Store File

First of all, go to your PHPMyAdmin and create a table name customers with the following fields: name, email, message.

Step 1 – Create Database And Table

First of all, navigate to your phpmyadmin panel and create database and table using the following sql queries:

CREATE DATABASE my_db; CREATE TABLE `customers` ( `id` int(10) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `message` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_date` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Step 2 – Create a Database Connection File

In this step, you will create a file name db.php and update the below code into your file.

Читайте также:  Using list class in java

The below code is used to create a MySQL database connection in PHP. When you insert form data into MySQL database, there you will include this file:

Step 3 – Create An Ajax Post Form in PHP

In this step, you need to create an ajax form and update the below code into your ajax-form.php file.

     body < font-family: calibri; >.box < margin-bottom: 10px; >.box label < display: inline-block; width: 80px; text-align: right; margin-right: 10px; >.box input, .box textarea < border-radius: 3px; border: 1px solid #ddd; padding: 5px 10px; >.btn-submit 

Ajax POST request with JQuery and PHP - Tutsmake.com

Step 4 – Create Ajax Form PHP File

Now you need to create a new file name store.php and update the below code into your store.php file.

The below code is used to store form data into a MySQL database table name customers. If form successfully submitted to the database, it will return success message otherwise it returns an error.

Conclusion

In this tutorial, you have learned how to create a simple form and store data into a MySQL database without reloading or refreshing the whole web page with client-side validation using jQuery ajax in PHP.

Источник

Примеры отправки 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 .

Читайте также:  Try with resources java closeable

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_ , например:

Читайте также:  Html no address bar

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

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

Источник

How to Submit Form using Ajax in PHP?

In this post, we will learn How to Make a Form Submit in ajax PHP. i explained simply step by step How To Use Form Submit using Ajax in PHP & MySQL. Here you will learn how to Form submit to database Using ajax. This tutorial will give you simple example of ajax form submit php mysql Code Example.

I will give you simple Example of How to make a ajax form submit in PHP.

So let’s see bellow example:

Form Submit using Ajax in PHP MySQL Example

Name

Email address