Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - How to update SESSION variable with jQuery + AJAX, is it even possible?

I would like to update session variable.

Let me introduce this in simple example. We get a div with input fields printed out by PHP script, with some values etc...

Example PHP code:

echo '
<div id="few-input-fields">
<input id="Name" size="20" value="' . $_SESSION['name'] . '" />
<br />
<input id="Lastname" size="20" value="' . $_SESSION['lastname'] . '" />
</div>
<span id="save">save</span>
</div>
';

Let's say user edit this input field (id=Name) and type name "Mark" inside it and then press save text.

On click it should save/update session variable, without reloading page AND refresh input fields.

Is that possible? Perhaps with ajax / jquery? And most importantly how ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, just do a simple AJAX request. With jQuery it would be:

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

   return false;
});

And your PHP:

<?php
   session_start();
   $_SESSION["name"] = $_POST["name"];
   // Add the rest of the post-variables to session-variables in the same manner
?>

Note

You need to add name-attributes to your input-fields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...