0

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.preventDefault();
    });

});

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";
?>
3
  • NB: Your mySQL query is vulnerable to SQL injection. You need to use mysql_real_escape_string() Commented Jul 5, 2010 at 15:35
  • yea, i have that already covered in my class. I just proivded a snippet remember ;) Commented Jul 5, 2010 at 21:11
  • Mmmm.... if you say so? What I see is that $_GET values are passed through straight into ´mysql_query()` without any filtering. But, it's your code :) Commented Jul 6, 2010 at 9:11

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Not necessarily: If PHP is falling back to adding the session ID through a GET parameter because cookies are turned off, it could be that the jQuery URL does not get automatically rewritten. In that case, adding the session ID manually is the only option.
Well I guess that's an example of an edge case where you might want to pass a session id to your js file, but it doesn't really seem like that's what s2xi was asking about. And it would be a serious drag to have to support cookieless sessions in an ajaxy web app!
the script takes an action from the index.php and relays it with javascript over to my ajax.php which has my todo.class.php included. So Add/ Edit/ Delete actions are carried over via $_GET so it looks like ?action=new&text=My test text&position=2 what I would like is for the JS to capture the session id and carry it over in the $GET to my ajax.php that relays the info to my class.php... does that make sense?
@s2xi @Joey is arguing that this should usually not be necessary, which is true except for the one case I mentioned. Session info is usually transported through cookies.
well actually my problem is that since my database uses InnoDB I can no longer edit/update my records because I would need to put in a where clause to only affect those who match up to the foreign key... right?
0

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>

3 Comments

well the files are separated, if i had them all together then i wouldn't be wondering about this because i could use php to echo out what i need with in the js.
@s2xi yes, but if you do the above before including the script the php_session_id javascript variable will be available.
hah, i did that php_session_id = <?;?> and i was able to use that js variable in my script...not i just don't know why it won't save to my database, i get an error ;(
0

@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:

  1. 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?

  2. You are using GET requests to perform actions and modify data. This is a really bad idea.

4 Comments

He is not looking for the session ID , he is looking for a session variable (a custom user_id) most likely from a login .. But the fact remains (as you mentioned) that the session is maintained so the PHP pages called from AJAX know the user_id..
Ah, fair enough, I miseed the $_SESSION['user_id'] in the SQL statement. Although that doesn't really make me any less confused. If you're already using $_SESSION['user_id'] then what's the problem?
hmmm, well i'm using InnoDB with foreign keys in place. My problem is that I'm trying to find a way to 1) pass the user_id from the php page over via ajax to the class.php or 2) .... no idea ;( i'm trying to think why i can't simply add WHERE clauses in my class.php with my session variable and bypass the js altogether...?
I think you are overthinking this. If you are setting $_SESSION['user_id'] somewhere else you can still use it in ajax.php!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.