简体   繁体   中英

Pass session variable as Key-Value pair to PHP file using AJAX post

I have a session variable, say $_SESSION['Current_User']. I want to pass it to a URL as a key-value pair using AJAX. I have some HTML inputs as follows: HTML is:

<INPUT type='text' name='input_1' id="INPUT_1"></INPUT>
<INPUT type='text' name='input_2' id="INPUT_2"></INPUT>
<INPUT type='text' name='input_3' id="INPUT_3"></INPUT>
<BUTTON id="BUTTON_1" name="BUTTON_1_SUBMIT" value="SUBMIT_1" onclick="ajax_post()">Post</BUTTON>

<DIV id="Sub_Div_4"></DIV>

Javascript is:

function ajax_post()   
    {   var AJAX = new ajaxFunction();
        AJAX.onreadystatechange = function()
        {   if((AJAX.readyState == 4) && (AJAX.status == 200))
                {   var PHP_REPLY = AJAX.responseText; 
                var RECI_EVE_D = JSON.parse(PHP_REPLY);     
                var STRING_jsonified = "|||data_1: " + RECI_EVE_D.data_1 + "||| data_2: " + RECI_EVE_D.data_2+ "||| data_3: "  + RECI_EVE_D.data_3;
                document.getElementById("Sub_Div_4").innerHTML = STRING_jsonified;
        }       }
    var INP_1 = document.getElementById("INPUT_1").value;
    var INP_2 = document.getElementById("INPUT_2").value;
    var INP_3 = document.getElementById("INPUT_3").value;
    
    var PARAM = "input_1=" + INP_1 + "&input_2=" + INP_2 + "&input_3=" + INP_3 ; 
    AJAX.open("POST", "PHP/PHP_SIMPLE_AJAX_POST.PHP", true);  
    AJAX.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    AJAX.send(PARAM);
    }

Lets say, the PHP file PHP_SIMPLE_AJAX_POST.PHP needs that session information, and the user inputs to do some processing and send back JSON. So my question is, how do I package the existing $_SESSION['Current_user'] and send it to the PHP file? Thanks, much appreciated!!

If you mean, how to use the value of any currently existing $_SESSION values, you could try this:

<INPUT type='text' name='input_1' value="<?php echo $_SESSION['Current_user']['input_1']; ?>" id="INPUT_1"></INPUT>
<INPUT type='text' name='input_2' value="<?php echo $_SESSION['Current_user']['input_2']; ?>" id="INPUT_2"></INPUT>
<INPUT type='text' name='input_3' value="<?php echo $_SESSION['Current_user']['input_3']; ?>" id="INPUT_3"></INPUT>

Update

Then you should manipulate the $_POST value in your PHP script as such:

$_SESSION['Current_user']['input_1'] = $_POST['input_1'];
$_SESSION['Current_user']['input_2'] = $_POST['input_2'];
$_SESSION['Current_user']['input_3'] = $_POST['input_3'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM