Why try to retrieve $ _SESSION variables in a PDO, JavaScript, XMLHttpRequest query, the result is not the same as with PHP?

This is the first time I ask a question, my concern is this.

In order not to prolong the problem, I will show more relevant fragments
in
index.php

First of all, you have to put the beginning of the file index.php labels to be able to use the sessions, without which we could not use them.

    
<div class = "alert alert- fade-show "unusable by the alert" role = "alert">
// destroys the session when closing the alert not to be refreshed when the page is refreshed, the session is kept and therefore the message identical
// form to add a note that sends the data via POST to check in the file save_task.php
// the data is loaded dynamically with the help of JS, with XMLHttpRequest ();
title Description Creation date Edit Remove

1.C & is the part

L & # 39; archive main.js contains the code to use is the following

function showTodo () {
xmlhttp = new XMLHttpRequest ();
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
document.getElementById (& # 39; show & # 39;). innerHTML = this.responseText;
}
}
xmlhttp.open ("GET", "libs / showData.php", true);
xmlhttp.send ();} showAll ();

With xmlhttp = new XMLHttpRequest () I create a new object
In document.getElementById (& # 39; show & # 39;). innerHTML = this.responseText; I select the element with the ID #show to display the answer when performing the function showAll ().

In xmlhttp.open ("GET", "libs / showData.php", true); the connection will be passed 3 parameters the method of shipment in this case GET, the URL of the file to be processed, finally the parameter asynchronous specifies whether the request will be handled asynchronously or not.

The processed file is show_Data.php

prepare ($ sql); // preparation of the consutla
$ stmt-> execute (); // execute the query
while ($ result = $ stmt-> fetch (PDO :: FETCH_OBJ)) {?> // travel with a moment and with searching the lines are obtained
<! - id;?> ->
                        title;?>
                        description;?>
                        created_at;?>
                        
       
       
       
       <type of button = "button" data-toggle = "modal" data-target = "# edituser" class = "btn btn-secondary" data-id = "id;?> ">
                                
                            
                        
                            
                            
                            
                            <a class = "btn btn-danger" href = "libs / delete_task.php? id =id;?> ">
                                
                            
                        
                    
       

Buttons that perform the editing and deleting actions

<type of button = "button" data-toggle = "modal" data-target = "# edituser" class = "btn btn-secondary" data-id = "id;?> ">
                  
                            

This is the Edit button that opens a modal sale using Bootstrap in which a data-id = "id;?> " which will be retrieved with JavaScript that will be used as a parameter in the loadForm () function

The loadForm () function

document.addEventListener ("click", function (event) {
// validation that searches in the class .btn btn-sencodary
if (event.target.className == "btn btn-secondary") {

when you find matches, you can retrieve the data id

                var id = event.target.dataset.id;
// console.log (id);
loadForm (id, function () {
document.querySelector ("# ed"). innerHTML = this.responseText;
});
}});

Before showing the function, I have to add a addEventListener to document as the buttons were loaded dynamically, if we did not perform this step, our function would simply not realize that they exist and execute nothing.

var id = event.target.dataset.id;

the data-id is recovered with dataset which provides a read / write interface to get all the custom data attributes (data- *) of each of the elements and with target which is a reference to an object that launched the event in this case, the button.

loadForm (id, function () {
document.querySelector ("# ed"). innerHTML = this.responseText;
});    

By clicking the button, the loadFormular () function to which the identifier is passed as a parameter, is a callback function that will display the response obtained when the function is executed and will display the data in the modal .

function loadForm (id, callback) {
var xmlhttp = new XMLHttpRequest ();
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
callback.apply (xmlhttp);
} // end if
}
xmlhttp.open ("GET", "libs / edit_task.php? id =" + id, true);
xmlhttp.send ();

}

To the function loadForm () it is passed in id parameter, retrieved and a callback function that will display the results in the modal

xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
callback.apply (xmlhttp);
} // end if
}

// bind the parameters will be the GET method, and the path of the file to be processed will be an asynchronous request.
xmlhttp.open ("GET", "libs / edit_task.php? id =" + id, true);
xmlhttp.send ();

In this piece of code in callback.apply (xmlhttp)
the method apply invokes a function by referring to this object, here is how a teacher explains that it works.

The file that processes the data is edit_task.php

prepare ($ sql); // prepare the request
$ query-> bindParam (": id", $ _GET[‘id’]); // parameter link
$ query-> execute (); // execute the query
while ($ row = $ query-> fetch (PDO :: FETCH_OBJ)) {?> // browse the arrar with while and get lines with fetch
// form loaded into the modal window when you click on the edit button, which contains the parameters modified by the query and linked to the input
title;?> ">

description;?>
// button that manages a data identifier to be retrieved and processed with JS
id;?> "> Release Notes

This file processes the request of the function cargaFormulario (), which receives a parameter $ _GET and continue running the query to display the data in the Modal window.


In the div ID # ed

the file form is loaded edit_task.php

Now, what I can not achieve is once the note data has been changed:

  • Once the data has been modified in Modal, the file is processed correctly by modifying the data in the database.
  • But what I want is to do the same effect as with PHP
  • Which form sends the data to the file saved_task.php and I save the messages in the $ _SESSION variables that will be displayed once I redirect to index.php to display these messages in the alert of bootstrap.
  • But with JavaScript using XMLHttpRequest (), I do not get the same behavior, save the messages with $ _SESSIONS.

I do it in the following way, but only the simple messages are displayed.

var alert = document.getElementById ("alert"); document.addEventListener ("click", function (e) {if (e.target.id == "save_data") {var id = e.target.dataset.id;
saveUpdates (id)}}); function saveUpdates (id) {
var ts = document.querySelector ("# ts"). value;
var tes = document.querySelector ("# tes"). value;

var title = "title =" + ts;
var description = "& description =" + te;
xmlhttp = new XMLHttpRequest ();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
showAll ();
alerta.innerText = this.responseText;
}
}
xmlhttp.open ("GET", "libs / saved_changes.php? &" + title + description + & # 39; & id = + id, true);
xmlhttp.send ();

}

This function is similar to loadingFormulario (), you must run addEventListener in the document to identify the button that will launch the event related to the function. saveUpdates () since otherwise the button with the ID # save_data has been loaded dynamically, the function will not detect that this button exists and will not execute anything.

The difference is that you have passed two parameters, plus the value of the input # ts and the input #defined in the file. edit_task.php and the appl method is not used.

if (this.readyState == 4 && this.status == 200) {
showAll (); // passing the check, we call the showTodo () function to visually see the changes, otherwise the user will not notice anything.
alerta.innerText = this.responseText; // to return variables, reference to the div # alert is used

}

What can we add to index.php

<- aqui se muestran los mensajes retornados por la funcion saveUpdates()- -->

The file that processes the data is saved_changes.php

prepare ($ sql);
$ query-> bindParam (": title", $ _GET['title'])
$ query-> bindParam (": descri", $ _GET['description'])
$ query-> bindParam (": id", $ _GET['id'])
$ query-> execute ();
$ type = $ _SESSION['type'] = & # 39 ;;
$ message = $ _SESSION['message'] = & # 39; Changes successfully & # 39 ;;
} catch (PDOException $ e) {
$ type = $ _SESSION['type'] = & # 39; danger & # 39 ;;
$ message = $ _SESSION['message'] = & # 39; The changes were not saved & # 39 ;;
}
echo $ type;
echo $ message;}

This is the file that the UPDATE performs in the database. As mentioned, it works, save the changes but does not show the messages as I would like,
I'm working for the first time with JS and XMLHttpRequest (), because when saving messages when executing the function that processes this file, only normal messages that do not look like those I get in the warning of bootstrap which displays them in color according to the response type of the file.

Archive database.php

    PDO :: ERRMODE_EXCEPTION,
PDO :: ATTR_EMULATE_PREPARES => false,
];
$ pdo = new PDO ($ dns, self :: $ user, self :: $ password, $ options);
return $ pdo;
} catch (PDOException $ e) {
print_r (& # 39; Error while establishing the connection with the database provider & # 39 ;. $ e-> getMessage ());
}
}

}

I know that with JS, we work differently, I think it's not possible to retrieve the $ _SSESION variables with JS and XMLHttpRequest (), I have an idea but I do not know how to implement it.

-If I set two variables of array type in the first store the alert number and in the second the message.

$ var type = array (
& # 39; 0 & # 39; => & # 39;
& # 39; 1 & # 39; => & # 39 ;, warning
& # 39; 2 & # 39; => "Danger",
) /// etc ....
$ var message = array (
& # 39; 0 & # 39; => & # 39; Success message & # 39 ;,
& # 39; 1 & # 39; => & # 39; message in case of warning & # 39 ;,
& # 39; 2 & # 39; => & # 39; message in case of error & # 39;
)

And already check in the query ligo these variables according to the response of the data validation
and I connect them and return them to be processed in the index.php,
in the alert

<div class = "alert-"> would show aler-success what is the color of the successful message alert
"

but it's a vague idea and I do not know how to implement it.

I hope and you can solve my doubt.