0

EDIT: if I am able to access session data using sessionStorage in JS, regardless of how it was created, via php or AJAX, then why am I not able to remove sessionData using JS? sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network)

Also, if someone could suggest a way of doing this using AJAX I would appreciate it!

I am building a user generated form builder and saving values in $_SESSIONS on a php page. I am using a random alphanumeric generator to create two identifying tag attributes that will then be used to delete created input if the user so desires. The deletion is being done with vanilla JS and needs to happen before the page is loaded.

Okay, in order to save the multiple submissions of forms data each time a form is parsed and data is constructed into an input tag I am using SESSIONS. I am setting the $_SESSIONS using associative arrays inside the $_SESSION['form'] array and then building the output.

My issue is the delete functionality I have in Javascript works fine for the DOM, however I want to use the JS delete button to also reset the $_SESSION['form']['content']['randomly-generated-alphanumeric-number'] which is unique for the input the user has created.

Eventually I will be running this all through proper html entities to remove tags and add them appropriately, right now I am simply testing functionality with the application of the code.

Please keep in mind the random character is generated dynamically and inserted into the HTML and SESSIONS via php.

Here is the vardump($_SESSION['form']['content'])

array {
  ["m2HRvKPdDL"]=>
  string(313) "
    <div id="m2HRvKPdDL" class="input-type">
        <label>First Name: </label>
        &lt;input type="text" id="fname" class="input-type" name="first_name"&gt;<input type="button" alt="m2HRvKPdDL" id="deleteInput" class="deletInput" value="Delete this field"> <span id="deleteMSG"></span>
    </div>
    "
}

Here is the PHP function that creates this $_SESSION and generates the input tag: I am defining an array within the function that will eventually hold the data for display as the value and the randomly generated character -> $ran for the key.

function constInputTag($ran){
    $inputTitle = $_POST['inputTitle'];
    $attrTypeSubmit = $_POST['attrTypeSubmit'];          
    $output = [];
    $output[1] = $ran;    
    $output[0] = '
    <div id="'.$output[1].'" class="input-type">
        <label>'.$inputTitle.'</label>
        &lt;input type="'.$_POST['inputType'].'"';
    if(isset($attrTypeSubmit)){        
        foreach($_POST as $name => $value){
            //set post keys not included in the input tag in $omit to exclude them from input tag
            $omit = array('inputTitle', 'inputType', 'attrTypeSubmit');
            if(!in_array($name, $omit)) {
                $output[0] .= ' '.$name.'="'.$value.'"';
            }else{
                unset($name);                
            }           
        }
    }
    $output[0] .= '&gt;<input type="button" alt="'.$output[1].'" id="deleteInput" class="deleteInput" value="Delete this field"> <span id="deleteMSG"></span>
    </div>
    ';   
    return $output;
}

The output: This code is within conditionals that checks if forms have been submitted then concatenates an output variable and SESSION array depending on what submission post is set.

$ran = create_random_char(10);
$output .= constInputTag($ran)[0];
if(isset($_SESSION['form']['content'])){    
    $_SESSION['form']['content'][constInputTag($ran)[1]] = constInputTag($ran)[0]; 
}
//--> $_SESSION['form']['content']['key from function'] = 'value from function';

The Javascript: Front end code that checks if delete button is clicked, creates yes/no buttons, adds attributes to those buttons and displays them, locates and sets the random character that will be used as identifier for parent div, button and session, deletes the parent div that holds dynamically created element

NEED: Deletion of SESSION key/value that holds the corresponding user input.

var getInputId = document.getElementById("deleteInput"); // get the delete button and define it
if(document.getElementById("deleteInput")){ // if the element is in the DOM
    getInputId.addEventListener('click', function() { // set an event listener for click for the delete input button
        const delMsg = document.getElementById("deleteMSG"); // get the delete message span by id
        delMsg.innerHTML = '<span class="warning">Delete this input?</span>'; // set message and css to make sure user wishes to delete this input
        const yes = document.createElement('input'); // create the yes button input element
        const no = document.createElement('input'); // create the no button input element                          
        yes.type = 'button'; // add attributes to the yes button
        yes.id = 'deleteTrue';
        yes.value = 'Yes';
        no.type = 'button'; // add attributes to the no button
        no.id = 'deleteFalse';
        no.value = 'No';
        delMsg.appendChild(yes); // append the buttons to the span tag asking if user wants to delete
        delMsg.appendChild(no);

        // click event that searches for the randomly generated character in order to delete the input from the DOM
        yes.addEventListener('click', function() {  
            // Sets the ID for the parent div to the inputs ALT tags 
            // value which is set in php to the randomly generated character
            let searchId = getInputId.alt; 
            deleteId = document.getElementById(searchId); // search for the ID set to the random character 
            deleteId.remove(); // remove the tag, which is the div with ID set to random character
            sessionStorage.removeItem(searchId); // here is my attempt to remove session value
            console.log(searchId); // log console to compare values from inspector in browser

        });
        no.addEventListener('click', function() { // resets delMsg span and children
            delMsg.innerHTML= '';
        });
    });
}

This seems to be the code not working: sessionStorage.removeItem(searchId);

Again, searchid holds the randomly generated value that is set in the parent div that is used to delete the input field on users input, it is also set as the key value in the $_SESSION['form']['content'] array;

This code works fine in the DOM and deletes the input from the page. Now I just need to figure out how to unset the associative arrays value for that corresponding input within the $_SESSION array. I am not opposed to using AJAX, however JS and AJAX in particular is not a strong point for me and I would need some break down of how it works from any answers submitted.

Thank you in advance! All help is greatly appreciated!!!

dale landry
  • 7,831
  • 2
  • 16
  • 28
  • Your JavaScript code runs on the browser. The `$_SESSION` variable is solely on your server. Nothing your JS does can directly affect it. You will most definitely need to create an Ajax call to cause code to run on the server. – Greg Schmidt Apr 16 '20 at 04:10
  • Does this answer your question? [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Greg Schmidt Apr 16 '20 at 04:11
  • Hello Greg Sxhmidt, I understand the difference between server-side and client side coding. I guess I am more interested in if I am able to access session data using `sessionStorage` in JS, regardless of how it was created, via php or AJAX, then why am I not able to remove sessionData using JS? `sessionStorage` (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network). – dale landry Apr 16 '20 at 04:21
  • @Greg Schmidt Are you saying sessionStorage and the $_SESSION are two entirely different arrays of data? If that is the case, I will close this question and rethink my logic. – dale landry Apr 16 '20 at 04:35
  • Yes, despite the similar names, the two are entirely unrelated. – Greg Schmidt Apr 16 '20 at 13:52

1 Answers1

0

I a using an AJAX call to solve this issue.

dale landry
  • 7,831
  • 2
  • 16
  • 28