Answer the question
In order to leave comments, you need to log in
How to write to and from a database without reloading the page?
There is a php page with a form.
<code lang="php">
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Сотрудники</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="js/script.js" ></script>
</head>
<body>
<section class="main">
<h2>Редактирование</h2>
<form id="ajax_form" action="" method="post">
<table class="table2">
<tr>
<td><input type="text"/ name="name" placeholder="ФИО"></td>
<td><input type="text"/ name="phonenumber" placeholder="Должность"></td>
<td><input type="text"/ name="bdate" placeholder="Дата рождения"></td>
<td><input type="text"/ name="mnumber" placeholder="Мобильный номер"></td>
<td><input type="text"/ name="email" placeholder="E-mail"></td>
</tr>
</table>
<input type="button" id="btn" name="save" value="Отправить"/>
<input type="submit" name="update" value="Обновить"/>
</form>
<h2>Сотрудники</h2>
<div id="result_form"></div>
</section>
</body>
</html>
</code>
<code lang="php">
<?php
/*if (isset($_POST["name"]) && isset($_POST["phonenumber"]) ) {
// Формируем массив для JSON ответа
$result = array(
'name' => $_POST["name"],
'phonenumber' => $_POST["phonenumber"]
);
// Переводим массив в JSON
echo json_encode($result);
}*/
$fio = $_POST['name'];
$position = $_POST['phonenumber'];
$bdate = $_POST['bdate'];
$mnumber = $_POST['mnumber'];
$email = $_POST['email'];
$servername = "localhost";
$database = "Arman";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password, $database);
if(isset($_POST['save'])) {
$tor = "
INSERT INTO
`Сотрудники`
SET
`ФИО` = '$fio',
`Должность` = '$position',
`Дата рождения` = '$bdate',
`Мобильный номер` = '$mnumber',
`E-mail` = '$email'
";
} elseif(isset($_POST['update'])) {
$tor = "
UPDATE
`Сотрудники`
SET
`ФИО` = '$fio',
`Должность` = '$position',
`Дата рождения` = '$bdate',
`Мобильный номер` = '$mnumber',
`E-mail` = '$email'
WHERE
`ID` = '2'
";
}
if (mysqli_query($conn, $tor)) {
echo "Запись добавлена <br><br>";
} else {
echo "Ошибка: " . $tor . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
$conn = mysqli_connect($servername, $username, $password, $database);
$sotr = "
SELECT
`ФИО`,
`Должность`,
`Дата рождения`,
`Мобильный номер`,
`E-mail`
FROM
`Сотрудники`
WHERE
`ID` = '2'
";
$resultt = mysqli_query($conn, $sotr);
$row = mysqli_fetch_array($resultt);
$fio = $row['ФИО'];
$dol = $row['Должность'];
$result = array(
'name' => $fio,
'phonenumber' => $dol
);
echo json_encode($result);
/*mysqli_free_result($resultt);
mysqli_close($conn);*/
?>
</code>
$( document ).ready(function() {
$("#btn").click(
function(){
sendAjaxForm('result_form', 'ajax_form', 'php/sotrudniki.php');
return false;
}
);
});
function sendAjaxForm(result_form, ajax_form, url) {
jQuery.ajax({
url: url, //url страницы (action_ajax_form.php)
type: "POST", //метод отправки
dataType: "html", //формат данных
data: jQuery("#"+ajax_form).serialize(), // Сеарилизуем объект
success: function(response) { //Данные отправлены успешно
result = jQuery.parseJSON(response);
document.getElementById(result_form).innerHTML = "Имя: "+result.name+"<br>Телефон: "+result.phonenumber;
},
error: function(response) { // Данные не отправлены
document.getElementById(result_form).innerHTML = "Ошибка. Данные не отправлены.";
}
});
}
Answer the question
In order to leave comments, you need to log in
Problem solved. I don’t remember exactly what helped, but at least I had 2 $fio variables with different values in the handler, I also removed all the if conditions from the handler, the script doesn’t work with them for some reason, I also rewrote the array of the $result variable.
Here are the working codes:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Сотрудники</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="js/script.js" ></script>
</head>
<body>
<section class="main">
<h2>Редактирование</h2>
<form id="ajax_form" action="" method="post">
<table class="table2">
<tr>
<td><input type="text"/ name="name" placeholder="ФИО"></td>
<td><input type="text"/ name="position" placeholder="Должность"></td>
<td><input type="text"/ name="bdate" placeholder="Дата рождения"></td>
<td><input type="text"/ name="mnumber" placeholder="Мобильный номер"></td>
<td><input type="text"/ name="email" placeholder="E-mail"></td>
</tr>
</table>
<input type="submit" class="btn" name="add" value="Добавить"/>
<input type="submit" class="btn" name="update" value="Обновить"/>
</form>
<h2>Сотрудники</h2>
<div id="result_form"></div>
</section>
</body>
</html>
$( document ).ready(function() {
$(".btn").click(
function(){
sendAjaxForm('result_form', 'ajax_form', 'php/sotrudniki.php');
return false;
}
);
});
function sendAjaxForm(result_form, ajax_form, url) {
jQuery.ajax({
url: url, //url страницы (php/sotrudniki.php)
type: "POST", //метод отправки
dataType: "html", //формат данных
data: jQuery("#"+ajax_form).serialize(), // Сериализуем объект
success: function(response) { //Данные отправлены успешно
result = jQuery.parseJSON(response);
document.getElementById(result_form).innerHTML = "Имя: " +result.name+" Должность: "+result.position+" Дата рождения: "+result.bdate+" Мобильный номер: "+result.mnomber+" E-mail: "+result.email;
console.log(response);
},
error: function(response) { // Данные не отправлены
document.getElementById(result_form).innerHTML = "Ошибка. Данные не отправлены.";
}
});
}
<?php
include ('connect.php');
include ('insert.php');
include ('select.php');
?>
<?php
$servername = "localhost";
$database = "Arman";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password, $database);
?>
<?php
$name = $_POST['name'];
$position = $_POST['position'];
$bdate = $_POST['bdate'];
$mnumber = $_POST['mnumber'];
$email = $_POST['email'];
$add = "
INSERT INTO
`Сотрудники`
SET
`ФИО` = '$name',
`Должность` = '$position',
`Дата рождения` = '$bdate',
`Мобильный номер` = '$mnumber',
`E-mail` = '$email'
";
mysqli_query($conn, $add);
?>
<?php
$sotr = "
SELECT
`ФИО`,
`Должность`,
`Дата рождения`,
`Мобильный номер`,
`E-mail`
FROM
`Сотрудники`
/*WHERE
`ID` = '2'*/
";
$res = mysqli_query($conn, $sotr);
$row = mysqli_fetch_row($res);
$result = array
('name' => $row[0],
'position' => $row[1],
'bdate' => $row[2],
'mnomber' => $row[3],
'email' => $row[4],
);
echo json_encode($result);
mysqli_free_result($res);
mysqli_close($conn);
?>
I'll tell you how it should happen in theory.
1. Sending a request. We fasten to some event (clicking on a button, for example) sending a request to the server (via AJAX). Normal ajax request, you send the required data to the server.
2. Data processing on the server. Here you process your request in every possible way. You filter the data, put the data into the database, take whatever you want from there.
3. Data return. Next, you must return the data for further processing on the client side (js). It is desirable to return in JSON. Example:
$arr = ['name' => 'Вася'];
return json_encode($arr);
success: function(response) {
//Данные отправлены успешно
alert(response.name);
//выведет Васю
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question