set PHP's session without form submit

微笑、不失礼 提交于 2019-12-11 20:26:59

问题


I have a textarea with two buttons. One button will preview the text that I entered, and the other one submits the text to server. Here is my code:

<?php
session_start();
$_SESSION['ShortDescription']='';
if(isset($_POST['Submit']))
{...}
?>

<form name="news" action="add_news.php" method="post">
<textarea  rows="5" name="ShortDescription" id="ShortDescription"></textarea>&nbsp
<input type="button" name="Preview" value="Preview Description">
<input type="submit" name="Submit" value="Submit">
</form>

I am a beginner in PHP and JavaScript. I know the problem can be solve by using AJAX. However I am very new to AJAX. Can anyone help me please?


回答1:


From what I understand, you're initiating a session and afterwards, you want to create a $_SESSION variable based on what someone types in the text area. Assuming you don't want the page to change when the user clicks preview (but you want to be able to use the $_SESSION variable in future situations) you'll need to use something like AJAX (as you mentioned). The easiest way I've found to accomplish something like this is to use jQuery and AJAX together.

Basically, you'll create a JavaScript function (using jQuery) to select whenever the preview button was clicked. It will look something like this. First we add the id within the input tag...

<input type="button" id="previewID" name="Preview" value="Preview Description">

Next we create the function in the javascript file...

 $('#previewID').click(function() {
   request = $.ajax({
    url: "/form.php",
    type: "post",
    data: serializedData
    });
});

form.php could simply be a form that checks to see if $_POST['ShortDescription'] exists, if it does, sanitize it and store it in $_SESSION['ShortDescription']. The "serializedData" is just the contents of the text area that is being passed. (which really is just passing the variable contents over the URL. For example, if ShortDescription = "HelloThere", the serialized data would be "ShortDescription=HelloThere", which appends to the URL like...

"www.website.com/form.php?ShortDescription=HelloThere"

Keep in mind that you would not typically manually set this though, that was just to show the concept. Use something like:

    var serializedData = $form.serialize();

View this question for an example AJAX request.

Disclaimer: There may be a better way to accomplish this, but I figured I would offer one possibility since no one had answered yet!



来源:https://stackoverflow.com/questions/17591582/set-phps-session-without-form-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!