R
R
Ruslan Website2020-05-08 10:56:57
PHP
Ruslan Website, 2020-05-08 10:56:57

How to write to and from a database without reloading the page?

There is a php page with a form.

index.php
<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>


There is a handler for this form.

collaborators.php
<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>


And a script that should process the whole thing without reloading the page.

script.js
$( 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 = "Ошибка. Данные не отправлены.";
        }
    });
}


In this form, when you click on the "send" button, nothing happens, the script does not work, but if you add php/sotrudniki.php to the form in the action, processing occurs, i.e. the handler itself is working, adds an entry to the table and retrieves it.

But, the handler and the script will work if the action in the form is left empty and the code is uncommented at the very beginning of the handler, and the previous one is commented out. The script code was taken from an article on one site, but this does not change the essence, it works with one code in the handler and does not work with another code in the handler, although both codes work separately from the script.

I've only been studying php mysql for a few days, and in general this is my first question anywhere, so don't judge too harshly. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan Website, 2020-05-09
@Sadyrbaev

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:

Form page - index.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="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>

Script ajax request and return json - script.js
$( 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 = "Ошибка. Данные не отправлены.";
        }
    });
}

Processor - sotrudniki.php
<?php
include ('connect.php');
include ('insert.php');
include ('select.php');

?>

Connecting to the database - connect.php
<?php
$servername = "localhost";
$database = "Arman";
$username = "root";
$password = "";


$conn = mysqli_connect($servername, $username, $password, $database);
?>

Adding an entry to the database - insert.php
<?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);

?>

Retrieving records from the database - select.php
<?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
Ivan Ivanov, 2020-05-08
@maksim_fix

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);

4. Receiving data on the client side. The previously sent response from the server comes to the client as a JSON object.
success: function(response) { 
     //Данные отправлены успешно
            alert(response.name);
            //выведет Васю
        },

You also need to specify dataType: "json", // data format, not html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question