0

Ok, so I'm fairly new to dynamically updating a database without invoking a page refresh. I'm trying to create, on a far simpler scale, something like http://mytinytodo.net/

The end goal that I'm trying to hit here is for the program to:

  1. Be able to dynamically generate fields (Complete)
  2. Populate web page with existing entries in MYSQL database on load via PHP (Complete)
  3. Allow user to "Check All" or "Uncheck All" (Complete)
  4. Remember a user's personal list.. Cookies maybe? Help!
  5. Update the database with any changes the user makes to existing list items or commit newly created list items. AJAX? Jquery? Help!

I've spent a few hours into this little project so far and here is what I have:

index.php:

<!doctype html>
<html>
    <head>
    <metacharset="utf-8" />
    <title>Simple To-Do List</title>
    <?php
    // Create connection via my connect.php file
    require 'connect.php';

    // Create query
    $query = "select * from checklist";
    $result = mysql_query($query);

    // Create requisite array for checklist
    $checklistItems = array();

    //Check to ensure query won't implode and is valid
    if ($result === FALSE) {
        die(mysql_error());
    }

    // Calculates number of rows from query  
    $num = mysql_numrows($result);

    mysql_close($con);
    ?>
    <!-- javascript code to dynamically add new form fields as well as check\uncheck all boxes -->
    <script src="addInput.js" language="Javascript" type="text/javascript"></script>

</head>
<body>   

    <h1>My To-Dos</h1>


    <form name="checklist" id="checklist" action="" method="">
        <?php
        // Loop through query results     
        while ($row = mysql_fetch_array($result)) {
            $entry = $row['Entry'];
            $CID = $row['CID'];
            $checked = $row['Checked'];
            // echo $CID;
            echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" />";
            echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\"  value=\"$checked\"" . (($checked == '1') ? ' checked="checked"' : '') . "  />";
            echo "<br>";
        }
        ?> 
        <div id="dynamicInput"></div>
        <input type="submit" id="checklistSubmit" name="checklistSubmit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">               
        <input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
</body>
</html>

connect.php

<?php 

// Create connection
$con=mysql_connect("localhost","root","");
$selected = mysql_select_db("madmonk",$con); 

// Check connection
if (mysqli_connect_errno($con))
{
    echo "Failed to connect to MySQL: " . mysql_connect_error();
}

?>

In summary, how can I discreetly update the users list when an "onchange" happens to one of the form fields without having to throw the whole page at a post file and then redirect the url back? I don't want a refresh to happen.

How do I create a cookie that remembers who the user is and what his personal list of items are?

This is my first real attempt at something like this. Obviously I'm not near the "styling" phase yet, so there's no CSS or anything flashy.

EDIT: So I now have (essentially) unique session variables which I'm using to distinguish visitors from one another and when they create their new "checklist" in the database their 'uid' will be logged there. So the system will 'remember' them for as long as the session lasts... I think this is what some of you were intimating I do.

3 Answers 3

1

You might like to take up jQuery - it'll make your life easier as far as basic JS frameworks (and ajax stuffs).

Secondly, you could always use sessions. Just place session_start() at the top of your php files (all that are used).. then you can access $_SESSION['name'] and assign whatever you want to it.

PHP is stateless - the use of cookies isn't recommended and I frown upon it when avoidable. Sessions are server-side (but usually place a session ID cookie on the client.. but nothing else) and can typically be trusted.

As far as "Remember a user's personal list.. Cookies maybe?" - I thought you were using the database for this?

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

1 Comment

Right, but for multiple people it has to remember who you are and generate the list when you visit the page. Can sessions be utilized to 'cache' user data\selections and remember their list?
1

For the AJAX part you could use

$.ajax({                                      
            url: 'api.php',           //the script to call to get data          
            data: ''//you can insert url arguments here to pass to api.php
                                   //for example "id=5&parent=6"
            dataType: 'json',                //data format      
            success: function(data)          //on recieve of reply
            {
                //what you do after the script has been called
            } 
    });

2 Comments

Can you give me a working example that would be applicable to my project?
BTW, that example requires JQuery (if you arent using it you really should)
1

Assuming you take advantage of the jQuery ajax method provided by Carlos as well as using a session as Rob states, your api.php file can have something like this inside of it.

$json_data = $POST;

do_update($json_data);

function do_update($DATA) {
    if ($DATA['type'] == 'update') {        
        foreach ($json_data as $key=> $value) {
            $query .= " UPDATE table SET {$key} = '{$value}' WHERE user_id = '{$_SESSION['some_user_id']}' ";
        }
    } elseif ($DATA['type'] == 'delete') {      
        foreach ($json_data as $key=> $value) {
            $query .= " DELETE FROM table WHERE {$key} = '{$value}' AND user_id = '{$_SESSION['some_user_id']}' ";
        }
    }

    if (mysql_query($query)) {
        echo "Yay";
    } else {
        echo "Nay";
    }  
}

Comments

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.