Получить данные от php ajax

PHP — AJAX и MySQL

В этом уроке мы наглядно проиллюстрируем, насколько просто получить доступ к информации из базы данных с помощью AJAX, мы собираемся создавать запросы MySQL на лету и отображать результаты в виде таблицы HTML.

Пример работы с Ajax, PHP и MySQL

В следующем примере показано, как веб-страница может получать информацию из базы данных с помощью AJAX. Вы можете из выпадающего списка выбрать одного из клиентов и увидите, что, без перезагрузки страницы, необходимая информация будет отображаться ввиде таблицы HTML:

Example

Таблица примера работы с Ajax и MySQL

Пример

  // Попытка выполнить запрос на создание таблицы $sql = "CREATE TABLE ajax_demo ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, age int(11) NOT NULL, hometown VARCHAR(30) NOT NULL, job VARCHAR(30) NOT NULL ) "; if(mysqli_query($link, $sql)) < echo "Таблица успешно создана."; >else < echo "ERROR: Не удалось выполнить $sql. " . mysqli_error($link); >// Закрыть соединение mysqli_close($link); ?>

Пример

 // Попытка выполнения запроса вставки $sql = "INSERT INTO ajax_demo (firstname, lastname, age, hometown, job) VALUES ('Ivan', 'Ivanov', 30, 'Moskow', 'designer'), ('Stepan', 'Stepanov', 32, 'Kiev', 'manager'), ('Maxim', 'Maxsimov', 33, 'London', 'boss'), ('Irina', 'Sidorova', 35, 'Varshava', 'programmer')"; if(mysqli_query($link, $sql)) < echo "Записи успешно вставлены."; >else < echo "ERROR: Не удалось выполнить $sql. " . mysqli_error($link); >// Закрыть соединение mysqli_close($link); ?>

таблица примера работы с Ajax и MySQL

В результате мы получим следующую таблицу, которую будем исползовать в этом уроке:

Объяснение примера работы с Ajax и MySQL

В приведенном в начале урока примере, когда пользователь выбирает человека в раскрывающемся списке, выполняется функция showUser() . Функция showUser() запускается событием onchange :

Пример

       

  • Создадим объект var xmlhttp = new XMLHttpRequest();
  • Создадим функцию xmlhttp.onreadystatechange, которая будет выполняться, когда будет готов ответ сервера if (this.readyState == 4 && this.status == 200)
  • Отправим запрос в php-файл getuser.php на сервере
  • Обратите внимание, что к URL-адресу добавлен параметр (q) (с содержимым раскрывающегося списка)

Файл-обработчик для работы с Ajax и MySQL

Страница на сервере, вызываемая выше приведенным JavaScript, представляет собой PHP-файл «getuser.php».

Исходный код в файле «getuser.php» выполняет запрос к базе данных MySQL и возвращает результат в таблице HTML:

Пример

    table < width: 100%; border-collapse: collapse; >table, td, th < border: 1px solid black; padding: 5px; >th  mysqli_select_db($con,"demo"); $sql="SELECT * FROM ajax_demo WHERE = mysqli_query($con,$sql); echo " "; while($row = mysqli_fetch_array($result)) < echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
Firstname Lastname Age Hometown Job
" . $row['firstname'] . "" . $row['lastname'] . "" . $row['age'] . "" . $row['hometown'] . "" . $row['job'] . "
"; mysqli_close($con); ?>

Объяснение кода: Когда запрос отправляется из JavaScript в файл PHP, происходит следующее:

  1. PHP открывает соединение с сервером MySQL
  2. Выполняется поиск выбранного человека из списка
  3. Создается таблица HTML, заполняется данными и отправляется обратно в элемент-заполнитель «txtHint».

Источник

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

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

Читайте также:  Catch exception java heap space

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

Читайте также:  Binary files in java examples

Источник

How To Return JSON Response in PHP & MySQL using Ajax and jQuery

In this tutorial, I will share with you how to return JSON response in PHP & MySQL using Ajax & jQuery this is useful to display multiple types of data from server response and process it to our client-side using ajax and jquery. Don’t worry this method is easy we are going to use an array from the server and encode it with JSON format.

Basic Example

Let’s do the basics first we will create a new file called basic.php as you can see below code I created an associative array with first_name & last_name name keys. Then I use json_encode to encode the array into JSON format.

Then this is the result when executing it in the browser.

How To Response JSON in PHP & MySQL using jQuery & Ajax

AJAX Integration

For ajax integration we need to create a simple button in our index.html then a simple ajax function to communicate the above code basic.php.

Let’s code our button with HTML.

Then next is our javascript ajax code. We will create our function named basic() inside scripts.js. Here is the code below:

Then if we will click the button «Basic JSON Response» the result will be like this on the console.

How To Response JSON in PHP & MySQL using jQuery & Ajax

Next, we will parse the response JSON so that we can easily call it as JSON. See the code below.

As you can see we add a new line of code «response = JSON.parse(response);». Kindly see the console result after this code.

How To Response JSON in PHP

As you can see from the result above it is clickable now because we already parse it as JSON from a string.

Display by JSON Property

Now we will display the JSON by property like if you want to display the first_name value only. Here is the code update below:

As you can see below we add a new line of code «console.log(«First Name:» + response.first_name);» now in this code, we only access the first_name value.

Display JSON Property in HTML

Now we will display the specific property on your web page. We will update our HTML code below.

Then also our javascript code inside scripts.js. See below code updates.

As you can see above I add new line of code «$(«#json_first_name»).html(«First Name: » + response.first_name);». I call the ID selector «#json_first_name» and use html() function to display the first_name value from your server.

How To Response JSON in PHP

Now since you have the basic knowledge already of how to Response the JSON we will implement the dynamic data using PHP & MySQL with Ajax.

Читайте также:  Проверка деления нацело python

Display Dynamic Data Using Response JSON with PHP & MySQL

I will share with you the easy method to display the dynamic data from your server-side. In this example, we will display the employee in Edit Employee Modal using ajax and jquery.

Display Dynamic Data Using Response JSON with PHP & MySQL

Here is the HTML code inside index.html

Our HTML code for modal inside index.html

  

Edit Employee

Then our PHP code inside get.php as you can see below that I encode the $row variable array from the result query.

query($sql); // Fetch Associative array $row = $results->fetch_assoc(); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now we will add our javascript code get() function inside scripts.js.

function get() < $(document).delegate("[data-target='#edit-employee-modal']", "click", function() < var employeeId = $(this).attr('data-id'); // Ajax config $.ajax(< type: "GET", //we are using GET method to get data from server side url: 'get.php', // get the route value data: , //set data beforeSend: function () , success: function (response) >); >); >

Loop the JSON Response

Since you already know how to display your JSON response to your web page. Now I will give you an example of how to loop the JSON. Below are the screenshot example on listing the employees via ajax with JSON response.

Before we dive in I will show you first a basic code on how to do it. As you can see in the code below I use «$.each(response, function(key,value)

Kindly check the console result below of the above code.

Loop the JSON Response

So that’s the basic way on how to loop the JSON. So we will apply it in the advance by displaying the list of employees using the bootstrap list group as you can see the result below:

Lop the JSON Response

Now let do the code. First set up our HTML code inside index.html.

Then next our PHP Code inside all.php.

query($sql); // Fetch Associative array $row = $results->fetch_all(MYSQLI_ASSOC); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now let’s code the javascript for looping the employee’s result via ajax. You will find this code inside scripts.js with all() functions.

function all() < // Ajax config $.ajax(< type: "GET", //we are using GET method to get all record from the server url: 'all.php', // get the route value success: function (response) '; // Loop the parsed JSON $.each(response, function(key,value) < // Our employee list template html += ''; html += "

" + value.first_name +' '+ value.last_name + " (" + value.email + ")" + "

"; html += "

" + value.address + "

"; html += ""; html += ""; html += ''; >); html += '
'; > else < html += '
'; html += 'No records found!'; html += '
'; > // Insert the HTML Template and display all employee records $("#employees-list").html(html); > >); >

Now you have the foundation already about JSON Response from your server-side. I hope this article may help you. To see the action capability of this code just click the «Download» button below.

Thank you for reading. Happy Coding!

Источник

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