javascript - How to Store PHP Session Values from Multiple Click Events in jQuery? -
i trying use jquery pass values session variables when buttons clicked on. each button has unique values , need display values both buttons when both clicked.
the problem having 1 set of values (from recent button clicked) translated session variable - if click first button, first values passed session backend fine, clicking second button afterwards results in second values being passed.
my jquery looks this:
$button_one.click(function(e) { e.preventdefault(); var var_one = "value1"; var var_two = "value2"; $.post("sessions.php", { 'session_var_one': var_one, 'session_var_two': var_two }); }); $button_two.click(function(e) { e.preventdefault(); var var_three = "value3"; var var_four = "value4"; $.post("sessions.php", { 'session_var_three': var_three, 'session_var_four': var_four }); });
the sessions.php simple:
<?php session_start(); $_session['value_one'] = $_post['session_var_one']; $_session['value_two'] = $_post['session_var_two']; $_session['value_three'] = $_post['session_var_three']; $_session['value_four'] = $_post['session_var_four']; ?>
and have simple page set display session values:
<?php session_start(); ?> <!doctype html> <html> <body> <?php echo '<h5>' . $_session['session_var_one'] . '</h5>'; echo '<h5>' . $_session['session_var_two'] . '</h5>'; echo '<h5>' . $_session['session_var_three'] . '</h5>'; echo '<h5>' . $_session['session_var_four'] . '</h5>'; ?> </body> </html>
this page displays 2 values of button last clicked on - instead of displaying both sets of values if both buttons clicked on.
i guessing having 2 separate ajax requests, 1 within each click function, may problem here - when button 2 clicked after button one, "forgets" first request , values not recorded.
i have worked around problem sending each of button click values different session php page (i.e. button_one goes sessions_one.php , button_two goes sessions_two.php) prefer not have create new place store session values each button. plan on adding more buttons , seems bad practice have each button have separate home stored values.
how can rewrite ajax requests and/or sessions.php can store of values each button click? thank guidance, i'm new php , ajax in general!
if $_post
variable not provided, code put null
in corresponding $_session
variable. prevent that, check provided before doing so:
<?php session_start(); if( isset($_post['session_var_one']) ){ $_session['value_one'] = $_post['session_var_one']; } if( isset($_post['session_var_two']) ){ $_session['value_two'] = $_post['session_var_two']; } if( isset($_post['session_var_three']) ){ $_session['value_three'] = $_post['session_var_three']; } if( isset($_post['session_var_four']) ){ $_session['value_four'] = $_post['session_var_four']; } ?>
Comments
Post a Comment