Mohamed Athif Mohamed Athif - 1 month ago 34
Ajax Question

Cannot set session ajax using jquery and php

i want to add a value to a session array when ever i click a button on my form. i tried to achieve this using jquery onclick, ajax and jquery. but it doesnt seem to set a variable or return anything.

in my main.php i have

<form id="sessy">
<input type="text" name="name" id="name">
<button id="submit" name="submit" class="btn btn-success">Submit</button>
</form>

<script>
$("#sessy").submit(function(){
$.ajax({
type: "POST",
url: "session.php",
data: $(this).serialize(),
success: function(){
// Do what you want to do when the session has been updated
}
});

return false;
});
</script>

<?php
session_start();
echo $_SESSION['name'];

?>


and in my session.php

<?php
session_start();

$_SESSION['name'][] = $_POST['name'];
?>


and i am calling jQuery.js at the bottom of the page.

it gives me below, where line 23 is the part where i am trying to echo the session variable.

Notice: Undefined index: name in ....main.php on line 23


and i try print_r($_SESSION); instead of echo i get just "Array ( )"

Answer

You don't really need a form is you submit with ajax.
And submit is a reserved keyword that you shouldn't use as an id, class or a name.
It has a tendency to bug...

Try this as your main.php:

<?php
session_start();
?>
<html>
<head>
<!-- jQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="sessy">
    <input type="text" name="name" id="name">
    <button class="btn btn-success">Submit</button>
</div>
<br>
<div id="result"></div>
<script>
    $("#sessy .btn").click(function(){
        $.ajax({
            type: "POST",
            url: "session.php",
            data: $("#sessy #name"),
            success: function(data){
                // Do what you want to do when the session has been updated
                $("#result").html("<h2>Name «"+data+"» is in session.</h2>");
            }
        });
    });
</script>
</body>
</html>

And your session.php:

<?php
session_start();

$_SESSION['name'] = $_POST['name'];
echo $_SESSION['name'];
?>
Comments