Created
December 16, 2019 22:54
-
-
Save dilumdesilva/93c6cca08a3d7451315c29f82acebca0 to your computer and use it in GitHub Desktop.
How to send a simple ajax call from front end to a php backend (php file) to add a value to the $_SESSION
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if(!isset($_SESSION)) { session_start(); } | |
$username = $_POST['user_name']; | |
$_SESSION['usernames'] = $username; | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sendAJAX(name){ | |
$.ajax({ | |
url: './add_to_session.php', | |
type: 'post', | |
dataType: 'json', | |
data: { "user_name": "name" }, | |
success: function (response) { | |
console.log('Username '+name+'has been added to the session' ) | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo ' | |
$name = 'DilumDeSilva'; | |
<button class="sample-class" id="sample-btn" onclick("sendAJAX($name)")>Click Me</button> | |
'; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment