M
M
Mosapi2020-06-07 15:25:48
MySQL
Mosapi, 2020-06-07 15:25:48

Session does not fire when writing data to mysql, when sending with fetch?

By clicking on the button, I send several variables using fetch in this way:

var button2 = document.querySelector("#tybl");
button2.addEventListener("click", function() {
      //console.log("Кнопка нажата сохранить.");
      var finc ='save';
      var soloma = document.querySelector("#tl").innerHTML;
      var kit = lad_id;
      var par = [finc, soloma, kit];
      var formData = new FormData();
      for(var i=0;i<3;i++){
        formData.append("par_"+i, par[i]);
      }
      fetch('../system/gen.php', {
            method: 'POST',
    		body: formData
      }).then(function(response){
        console.log("Watch in mysql db");
        //document.getElementById("boro").innerHTML = response.text();
      }).catch(function(error){
         console.log("Error");
      });
    });


to the php handler . As a result, there is no entry to the database, because the session is not initialized.
I searched the net for recommendations, but did not find a sensible solution.
- session_start();registered at the very top
- In the session id cookies, it changes, as it should be.
- Registered var_dump($_SESSION)
result:
array(0) {
}

in errors, php swears at an undefined index 'user_id' from $_SESSION['user_id']- which is actually logical, since the session is not defined.

php handler structure:
session_start();
var_dump($_SESSION);
require_once ('../func/tobase.php');//подключение к базе

if(isset($_POST)) 
{
$dt_j = $_POST['par_0']; //save
$da_is = $_POST['par_1']; //data
$da_ls = $_POST['par_2']; //id

if($dt_j == 'save'){
$nn_new = mysqli_query($link, "SELECT 1 FROM l_projects WHERE id='{$da_ls}'and author='{$_SESSION['user_id']}'");
$orage = mysqli_num_rows($nn_new);
if($orage != 0){
mysqli_query($link, "UPDATE `l_projects` SET `bl1` = '{$da_is}' WHERE `id`='{$da_ls}' and `author` = '{$_SESSION['user_id']}'");// 
}
}
}

I clean author = '{$_SESSION['user_id']}'and record in basis goes. Which is quite logical, since the error does not interfere with this in any way.
What is most strange, similar actions sent to the same handler, but from jquery with the usual ajax, work fine and record. Is it a matter of fetch or what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mosapi, 2020-06-07
@Mosapi

In general, a solution has been found.
As I understand it, along with fetch, it is also necessary to transfer the session (so to speak). That is, it is necessary to add credentials to the request parameters. By writing like this.

... 
fetch('../system/gen.php', {
            method: 'POST',
            Credentials: 'same-origin' , 
    	    body: formData
      })
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question