Grab session variable from php page via jquery?
I edited my original text to demostrate my entire set of code for those that weren't understanding my question. All this works perfect when I had my database use MyISAM but when I changed over to InnoDB I now have to account for my foreign key or the mysql_queries won't successfully execute. I have the user_id in a session variable that gets created at the time a user logs in. I would figure I need to relay that number (int) from this session variable and append it to the $_GET so that it can be transferred to the todo.class.php for processing right?
the final get() would perhaps need to look like this ?action=new&user_id=1 (or what ever number the user is)&text=text type by user...
if there is a better way to do this, i'm all ears and ready to learn! ;-)
todo.js
$(document).ready(function(){
$(".todoList").sortable({
axis : 'y',
containment : 'window',
update : function(){
var arr = $(".todoList").sortable('toArray');
arr = $.map(arr,function(val,key){
return val.replace('todo-','');
});
$.get('././process/todo/todo.ajax.php',{action:'rearrange',positions:arr});
},
/* Opera fix: */
stop: function(e,ui) {
ui.item.css({'top':'0','left':'0'});
}
});
var currentTODO;
$("#dialog-confirm").dialog({
resizable: false,
height:130,
modal: true,
autoOpen:false,
buttons: {
'Delete item': function() {
$.get("././process/todo/todo.ajax.php",{"action":"delete","id":currentTODO.data('id')},function(msg){
currentTODO.fadeOut('fast');
})
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
$('.todo').live('dblclick',function(){
$(this).find('a.edit').click();
});
$('.todo a').live('click',function(e){
currentTODO = $(this).closest('.todo');
currentTODO.data('id',currentTODO.attr('id').replace('todo-',''));
e.preventDefault();
});
$('.todo a.delete').live('click',function(){
$("#dialog-confirm").dialog('open');
});
$('.todo a.edit').live('click',function(){
var container = currentTODO.find('.text');
if(!currentTODO.data('origText'))
{
currentTODO.data('origText',container.text());
}
else
{
return false;
}
$('<input type="text">').val(container.text()).appendTo(container.empty());
container.append(
'<div class="editTodo">'+
'<a class="saveChanges" href="#">Save</a> or <a class="discardChanges" href="#">Cancel</a>'+
'</div>'
);
});
$('.todo a.discardChanges').live('click',function(){
currentTODO.find('.text')
.text(currentTODO.data('origText'))
.end()
.removeData('origText');
});
$('.todo a.saveChanges').live('click',function(){
var text = currentTODO.find("input[type=text]").val();
$.get("././process/todo/todo.ajax.php",{'action':'edit','id':currentTODO.data('id'),'text':text});
currentTODO.removeData('origText')
.find(".text")
.text(text);
});
var timestamp=0;
$('#addButton-todo').click(function(e){
if((new Date()).getTime() - timestamp<5000) return false;
$.get("././process/todo/todo.ajax.php",{'action':'new','text':'New Todo Item. Doubleclick to Edit.','rand':Math.random()},function(msg){
$(msg).hide().appendTo('.todoList').fadeIn();
});
timestamp = (new Date()).getTime();
e.preventDe开发者_运维知识库fault();
});
});
todo.class.php
<?php
class ToDo{
private $data;
public function __construct($par){
if(is_array($par))
$this->data = $par;
}
public function __toString(){
return '
<li id="todo-' . $this->data['id'] . '" class="todo">
<div class="text">' . $this->data['text'] . '</div>
<div class="actions">
<a href="#" class="edit">Edit</a>
<a href="#" class="delete">Delete</a>
</div>
</li>';
}
public static function edit($id, $text){
$text = self::esc($text);
if(!$text) throw new Exception("Wrong update text!");
mysql_query("UPDATE `todo` SET `text` = '".$text."' WHERE `id`=".$id );
if(mysql_affected_rows($GLOBALS['link'])!=1)
throw new Exception("Couldn't update item!");
}
public static function delete($id){
mysql_query("DELETE FROM `todo` WHERE `id` = ".$id);
if(mysql_affected_rows($GLOBALS['link'])!=1)
throw new Exception("Couldn't delete item!");
}
public static function rearrange($key_value){
$updateVals = array();
foreach($key_value as $k=>$v)
{
$strVals[] = 'WHEN '.(int)$v.' THEN '.((int)$k+1).PHP_EOL;
}
if(!$strVals) throw new Exception("No data!");
mysql_query("UPDATE `todo` SET `position` = CASE `id`".join($strVals)." ELSE `position` END");
if(mysql_error($GLOBALS['link']))
throw new Exception("Error updating positions!");
}
public static function createNew($uid,$text){
$text = self::esc($text);
if(!$text) throw new Exception("Wrong input data!");
$posResult = mysql_query("SELECT MAX(`position`)+1 FROM `todo`");// WHERE `user_id` = 1");
if(mysql_num_rows($posResult))
list($position) = mysql_fetch_array($posResult);
if(!$position) $position = 1;
mysql_query("INSERT INTO `todo` SET /*`user_id` = {$uid},*/ `text` = '".$text."', `position` = ".$position);
if(mysql_affected_rows($GLOBALS['link'])!=1)
throw new Exception("Error inserting TODO!");
echo (new ToDo(array(
'id' => mysql_insert_id($GLOBALS['link']),
'text' => $text
)));
exit;
}
public static function esc($str){
if(ini_get('magic_quotes_gpc'))
$str = stripslashes($str);
return mysql_real_escape_string(strip_tags($str));
}
}
?>
todo.ajax.php
<?php
require "../../dbc.php";
require "../../resources/classes/todo.class.php";
$id = (int)$_GET['id'];
try{
switch($_GET['action'])
{
case 'delete':
ToDo::delete($id);
break;
case 'rearrange':
ToDo::rearrange($_GET['positions']);
break;
case 'edit':
ToDo::edit($id,$_GET['text']);
break;
case 'new':
ToDo::createNew($_GET['text']);
break;
}
}
catch(Exception $e){
echo $e->getMessage();
die("0");
}
echo "1";
?>
Why do you need the session id on the client side? jQuery is sending a GET request to a PHP script on your server. To your PHP script it looks like any other request. The $_SESSION array will be in place and all the session-related functions will work just fine.
Trusting the client to provide a session id is a really bad idea.
I don't follow your script entirely, but to my knowledge the only way to get the current session ID reliably into JavaScript space is
(... head section of the HTML document ...)
<script type="text/javascript">
php_session_id = "<?php echo session_id(); ?>"
alert("The PHP session ID is "+php_session_id);
</script>
@s2xi I realize you are looking for an answer to a simple question, "How do I get the PHP session id into my javascript?" and Unicron's answer is a foolproof way of doing that.
I think we are just trying to figure out why you need to put the PHP session id in your GET request. Your PHP script will always know the user's session id, you just need to call session_id()
. There's no need to put it in your GET request. (Let's ignore the cookies-disabled edge case for now, I think it's clear we have bigger fish to fry)
Other things I'm worried about:
Tying data in your database to the session id doesn't make a whole lot of sense. As soon as that user's session expires, you will never be able to tie that data back to them. Am I missing something here?
You are using GET requests to perform actions and modify data. This is a really bad idea.
精彩评论