1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

help with PHP calendar (reservation system)

Discussion in 'PHP' started by absentx, Aug 31, 2011.

  1. #1
    Okay so I have created a nice php calendar that suits my needs in terms of displaying what dates are available and what dates are taken for a reservation system.

    I want my users to be able to highlight all the dates they would like to reserve on the calendar and then hit "submit" to be taken to the next step of the process. Is there anyway I can do this with php or am I going to have to bring javascript into the mix?

    My calendar is basically made of a table and I want the user to be able to click a date, have that particular table cell change colors to indicate it is selected and then obviously we need to transfer the information to the next page in the process. Can I somehow work form elements into this? I really don't want radio or check boxes on the calendar. I am also really juvenille at Javascript so I am hoping there is some pure html/PHP way to get this done...but I can work through the javascript if that is what it is going to take. I am just brainstorming on how I should go about doing this, as I have been battling it in my head all night.

    I would also like to stay away from every date in the calendar being a link and every time you click a date it sends a new variable in the url...that just seems tedious especially if someone is selecting multiple days...

    Any help appreciated!
     
    absentx, Aug 31, 2011 IP
  2. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #2
    Since PHP runs on the server, and you want the users to do this in their browsers, you have to use a client-side ("in the browser) language - like Javascript. Your user can't run PHP - the web just doesn't work that way.

    You could use AJAX to tell the server which date the user clicked, and Javascript to highlight that cell if the date is available (the server checks it and tells the browser), but the web is "disconnected" - there's no connection between one page and another, except for your database.

    You can use jQuery to set an onClick event for the entire table, so that when the user clicks the table, the cell ID is sent to the server. The server "flips" that date, turning it on if it's off, off if it's on ($cellID = !$cellID). Keep track of the changes in a table (if you use sessions, which you should, key by session ID), and you can create the "next" page using the data in the table.
     
    Rukbat, Aug 31, 2011 IP
  3. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Well I love the AJAX idea...but I would need a lot of help or good examples to be able to do that. So I understand the logic:

    -Use javascript to code bgcolor change for selected table cells
    -Use AJAX to send information to server regarding which cell has been clicked (by cell id I would assume)
    -Record the information sent via AJAX in a MYSQL table
    -Each set of date requests sent via AJAX should be stored in the table with the session id as the key or row identifier
    -At the next step of the reservation, SELECT dates WHERE id = $session_id and then use them as necessary to continue the process.

    I love it...Just no clue where to start on the AJAX!
     
    absentx, Aug 31, 2011 IP
  4. shallowink

    shallowink Well-Known Member

    Messages:
    1,218
    Likes Received:
    64
    Best Answers:
    2
    Trophy Points:
    150
    #4
    shallowink, Aug 31, 2011 IP
  5. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #5
    There are AJAX tutorials all over the web. If you understand Javascript and PHP, look at jQuery's ajax() fuinction - it makes the AJAX part trivial. Just send the id of the date cell and receive back anything you like or on success check for an error and, if there is none, don't do anything. ("Success" means that the PHP page sent back a response. That response could be your code for "nothing went wrong", "couldn't connect to the database" or anything else you want to check.) The code, as I said, is fairly trivial:
     $.ajax({     url: "yourfile.php?cell="+cellID,         success: function(data){           if(data == 'error' {               //do what you want here           }     }   });  
    HTML:
    (I don't know why it insists on eating newlines.)
     
    Rukbat, Aug 31, 2011 IP
  6. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Well I must say...today was long but I had some major strides. For starters, I think ultimately I will thank the firebug add on to firefox for really helping me with Javascript. One thing that has helped me learn PHP is the great error messages it gives you when you are completely wrong...well firebug lets me see what is going on with the javascript so ultimately it is helping me learn it quicker...my biggest problem with javascript is that I just don't know it that well...everything I do is based off examples and trying to find patterns until I see something that works.

    So here is where I am at. Rukbat...your jquery ajax function looks so nice and simple...and I will most likely be using that by the end of the process, but for tonight I found a example that included xmlhttp and readystate and all that jazz and just decided to roll with that. I like to "learn it the hard way" before I take advantage of it "the easy way"

    So here is my code, javascript first

    
    <script language="javascript">
    
    function selectdate(neato)
    {
    	
    if (neato=="")
      {
      document.getElementById(target).innerHTML="";
      return;
      } 
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5  
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("success").innerHTML=xmlhttp.responseText;
        }
      }
      
    xmlhttp.open("POST","write_dates.php?cell="+neato,true);
    xmlhttp.send();
    }
    </script>
    
    
    
    Code (markup):
    And the php at write_dates.php

    
    <?php
    
    $dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
    or die ('sorry this just wont work.');
    
    $cell= mysqli_real_escape_string($dbc, trim($_REQUEST['cell']));
    $query =  "INSERT INTO dates (reservation) VALUES ('$cell')";
    $data = mysqli_query($dbc, $query);
    
    echo 'The insert of '.$cell.' was a success';
    
    mysqli_close($dbc);
    ?> 
    
    
    Code (markup):
    Watching the debugger in firebug finally show me that my the $cell variable was getting sent (and in fact reflecting the clicked date) in the ajax request was quite refreshing...then to even see that the date had been written to the database was even better.

    Now...this is all just the initial stages obviously..this is all in a testing environment just to see if I can make it happen. Now I have a lot of details to nail down.

    Rukbat, back to your suggestion of an "on/off" type switch for each date...I like that idea, but what is the best way to do this? If a user clicks a date, I want to write that to the table with an identifier...but then if they click it again, do I delete that row?

    perhaps I put another column in each row...if the user clicks the same date again, set the "marker" column to "off" and then simply don't include rows marked off in the transmission to the next step?

    I kind of like that idea.

    I need to go to bed.
     
    absentx, Sep 1, 2011 IP
  7. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #7
    I still have many files doing it that way, from before I started using jQuery. Since this is a job to me, not a hobby, I don't get the time to go back and fix what's working.
    Add FirePHP and you can throw debug statements at that window, so you can see the values of variables at that point.
    Exactly. Delete the row and "unhighlight" the cell. Unless the user has a VERY slow path to the server, all that back and forth will seem like a desktop app. (Which is how you should think of an app using AJAX.)
    You could do that, but of what use is an "off" row? Inserting a new row if he clicks that date again is faster than updating an existing row (in the database - insert is just faster than update).
     
    Rukbat, Sep 1, 2011 IP
  8. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Okay...today has been a good day too. I have updated the PHP so now I am updating the dates clicked in the table with the session_id as the unique identifier.

    I also have the delete query working when the user clicks the date back off again.

    My main trouble today is once again javascript (I know this is the php forum, but I think there is a useful conversation going on here)

    first, the php so far

    
    <?php
    session_start();
    $id = session_id();
    
    
    $dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
    or die ('sorry this just wont work.');
    //First lets check to see if the date is already in the database for this particular user, if it is, we need to delete it.
    $cell= mysqli_real_escape_string($dbc, trim($_REQUEST['cell']));
    $query= "SELECT reservation FROM dates WHERE customer ='$id'";
    $data = mysqli_query($dbc, $query);
    while ($row = mysqli_fetch_array($data)) {
    	if ($cell == $row['reservation']){
    		$query = "DELETE FROM dates WHERE reservation= '$cell'";
    		$data = mysqli_query($dbc, $query);
    		echo  $cell . 'has been succesfully removed from your reservation'; 
    		exit();
    
    	}
    }
    //We have made it through the above loop, since the date doesn't exist in the table for the current user, lets write it.
    $query =  "INSERT INTO dates (customer, reservation) VALUES ('$id','$cell')";
    $data = mysqli_query($dbc, $query);
    
    echo 'The insert of '.$cell.' for user '.$id.' was a success';
    
    mysqli_close($dbc);
    
    ?> 
    
    PHP:
    Okay so now the javascript, I can get the cell to change color once...but I can't get it to change back! Here is what I am using:

    
    
    $("td").click(function() {
    	if ($(this).class = "number"){
             $(this).addClass('number_taken');
    	}
    
    });
    
    Code (markup):
    But I need to get it to change back too, so I have tried this:

    
    $("td").click(function() {
    	if ($(this).class = "number"){
             $(this).addClass('number_taken');
    	}
    	if ($(this).class = "number_taken"){
             $(this).addClass('number');
    	}
    
    });
    
    
    Code (markup):
    I know that is a pretty crappy attempt to get it to work, but like I said, I need some work with javascript. I think the best thing to do would be to working something into the other javascript function I am already using for the ajax, because this function is already tied to the onclick event for the table cells, so if I could just work the color change into this somehow:

    
    function selectdate(neato)
    {	
    //---------	
    if (neato=="")
      {
      document.getElementById(target).innerHTML="";
    
      return;
      } 
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5  
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
    
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("success").innerHTML=xmlhttp.responseText;
        }
      }  
    xmlhttp.open("POST","write_dates.php?cell="+neato,true);
    xmlhttp.send();
    
    }
    
    Code (markup):
     
    Last edited: Sep 1, 2011
    absentx, Sep 1, 2011 IP
  9. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #9
    First:
    
    $("td").click(function() {
    	if ($(this).class = "number"){
             $(this).addClass('number_taken');
    	}
    	else if ($(this).class = "number_taken"){
             $(this).addClass('number');
    	}
    
    });
    
    
    Code (markup):
    Your code is changing it to number_taken, then back to number.

    Second, I'd do the color change in the success callback in ajax(). You could have an error on the server, so look at the data returned (let PHP return true or false, 1 or 0, any two values you want) and flip the color if there's no error. Otherwise change the innerHTML of an error message div to an error message. (PHP could also return what the error is). Or pop up an alert with the error message.

    (That's just at a glance - it's late and I'm heading off to bed.)
     
    Rukbat, Sep 1, 2011 IP
  10. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #10
    Okay so in that case we have php set a variable if there is no error...then I some how need to get that information back and process it.

    Alright so lets assume on the php script page I set $color_change ='0'; after the delete query and $color_change ='1'; after the insert query.

    Now, I really don't know how to get that back in the ajax:

    I know that with

    getElementById("success").innerHTML=xmlhttp.responseText;

    it will return my echo statment...how do I access the value of the $color_change variable?

    I appreciate all the help here, I am learning a lot and grinding through more and more of the Javascript each day but I still have a ways to go.
     
    Last edited: Sep 1, 2011
    absentx, Sep 1, 2011 IP
  11. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #11
    In PHP:

    echo $color_change;
    exit;

    In Javascript, the value PHP echoed will be in the success parm. IOW
    
    $.ajax({
      url: "yourfile.php",
      context: document.body,
      success: function(data){
        //data is now the value that PHP echoed
        getElementById("success").innerHTML= data;
      }
    });
    
    Code (markup):
    You can just use that to change the color of the date (pass the id of the date cell) or to pop a message up in a div (use jQuery oneTime or Javascript setTimeout to blank it after a few seconds) that the selection was accepted.

    I periodically take courses in new technologies and languages, but I find that grinding through it, actually doing it and making it work, teaches me a lot more. Even being forced to help others teaches me, which is one of the reasons I'm here.

    Sometimes people are amazed when they come to me with a problem, and I just sketch out a solution without thinking. What they don't know is that I spent 9 days helping someone solve exactly the same problem on some forum a while ago. Some people may call that wasting the company's time, but it costs a lot less than $4,000 for a course, motel bill and travel expenses.
     
    Rukbat, Sep 2, 2011 IP
  12. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #12
    About three years ago I was sick of hacking through dreamweaver trying to build websites...I was beginning to become familiar with what it took to get things done in terms of css and html, but I was still lost if I wanted to do anything really productive, and I had always been intrigued by a php powered site someone had built me...interfacing with a database was what I was looking to do and I was completely taken by the idea. So I went out and bought a book called "Head First PHP" and it literally changed things for me...since buying that book I have built a few really nice sites, even two that are making me a fair amount of money each month. It is an amazing book for getting the basics of PHP down and I recommend it to anyone looking to get started in the language.

    Are my sites coded perfect? Hell no...that comes with time and experience, but they do what I want them to do and I make improvements all the time as I learn.

    I agree with what you are saying though. The absolute best way to get things done is to do them. I have wasted a lot of time on missing commas and improperly written queries and it is all for the better.

    Okay so I like the example you have provided and that should help me get those boxes changed colors..I am taking the weekend off but I will be back at it on Tuesday, so I am sure I will have some more questions then! Thanks again.
     
    absentx, Sep 2, 2011 IP
  13. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #13
    NP. Take the weekend off? When I'm looking to take time off, and not just lying on the deck with my eyes closed, I'm writing code. Kind of hard to stop after 40 years. (They say work is like running - if you just stop, without a cool-down, you could drop dead.)

    I came to PHP after decades of programming, so the PHP chm file was enough for me. But whatever gets your site built, right?

    I think that once you start seeing what AJAX can do for you, it'll become one of your most used tools.
     
    Rukbat, Sep 2, 2011 IP
  14. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #14
    Well, what we have talked about here in this thread will probably be a seminal moment for me. I always wanted to know how AJAX and PHP could work together...what I never realized was that it was just a matter of having the AJAX request or send information to/from the PHP script...

    I mean really...watching me click dates on this calendar and seeing them immediately reflected in the database is amazing!

    The whole "weekend off" thing is just to satisfy my wife...but she just went to bed, and here it is 11:20 pm and I am "back to work"
     
    absentx, Sep 2, 2011 IP
  15. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #15
    You fool, you. Get into bed and cuddle up to her. :)

    Mine is usually on WoW on weekends, so I cut code. To each our own. And, both being computer professionals, we have to be in separate rooms. (She uses Chrome and her home page is Google! It's a mixed marriage, I tell you.)
     
    Rukbat, Sep 2, 2011 IP
  16. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #16
    Alright, Back to Work!

    Okay so just a quick issue to start the coding today. I keep getting a javascript error message in IE8. Here is my code:

    
    function selectdate(neato)
    {	
    if (neato=="")
      {
      document.getElementById(target).innerHTML="";
    
      return;
      } 
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5  
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
    
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("response").innerHTML=xmlhttp.responseText;
        }
      }  
    xmlhttp.open("POST","write_dates.php?cell="+neato,true);
    xmlhttp.send();
    
    }
    
    Code (markup):
    IE8 is giving me an error message at this line:

    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();

    BUT if I refresh the browser, everything works fine!

    No problems FF, Chrome or others.

    Okay, so now I am going to do some actual coding while we resolve that minor problem.
     
    absentx, Sep 6, 2011 IP
  17. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #17
    Okay disregard above thread...I switched all the ajax stuff to the Jquery $.ajax function and that cleared up any troubles there.

    My real problem for now is just with the color changing of the cells.

    My php script already returns the following:

    
    //add a new date to the table
    echo $cell ." ".'has been succesfully added to your reservation'; 
    
    //remove a date because the user clicked it again
    echo  $cell ." ".'has been succesfully removed from your reservation'; 
    
    Code (markup):
    so obviously this code in the ajax function populates the "response" id on my reservation screen

    
     success: function(data){
        //data is now the value that PHP echoed
        document.getElementById("response").innerHTML= data;
    
    Code (markup):
    Now, my question is, how do I use the ajax function to differentiate between the different data that PHP is sending back? Because if I all of the sudden introduce the $color_change variable in to the equation, how do I extract that properly, and usefully from my response?

    Secondly, I don't know how I target the individual cell for color change in the success part of the function...when I am sending the request, I am using "onclick" for each individual table cell...but when I get the information back I have tried several things to target the individual cell with a color change and nothing works.

    Here is where my code is now:

    
    //click on the table cell to pick or unpick a date
    
    	echo "<td id ='".$current_month."/".($i - $startday + 1)."/".$current_year."' onclick=\"try_ajax(this.id)\" align='center' valign='middle' height='20px' class='number'>". ($i - $startday + 1) . "</td>\n";
    
    
    PHP:
    which calls the following javascript:

    
    function try_ajax(neato) {
    	
    $.ajax({
      type: "POST",
      url: "write_dates.php?cell="+neato,
      context: document.body,
      success: function(data){
        //data is now the value that PHP echoed
        document.getElementById("response").innerHTML= data;
    [B]//so now I need to get back the $color_change variable and somehow run that through a little function to find out what color we should be and then apply that back to the table cell with the id "neato"[/B]
      }  
    });
    
    
    Code (markup):
     
    absentx, Sep 6, 2011 IP
  18. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #18
    Getting back to work on this for the week. Still battling the issues in the above post if anyone could provide a little help.
     
    absentx, Sep 12, 2011 IP
  19. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #19
    Have PHP send back (echo) the cell number and whether it was added or deleted. A simple

    echo $cell.'|'.$state;

    Will do it. In the browser you split on '|' and you have the cell number and whether to change its color to selected or not selected. Generate the text to display in the browser, not on the server.

    Send the server the cell id. It returns the cell id (and the state). That's the 'target'.

    
    function try_ajax(neato) {
        
    $.ajax({
      type: "POST",
      url: "write_dates.php?cell="+neato,
      context: document.body,
      success: function(data){
        //data is now the value that PHP echoed
        document.getElementById("response").innerHTML= data;
    [B]//so now I need to get back the $color_change variable and somehow run that through a little function to find out what color we should be and then apply that back to the table cell with the id "neato"[/B]
    return = data.split('|');
    var state = return[1]; //return[0] is the cell id
    if(state == 'selected') {
    //change the color of the id (return[0]) to the "selected" color
    } else {
    //change the color to the "not selected" color
    }
      }  
    });
    
    
    Code (markup):
    You can also play with sending the data back as JSON data, if you want to get a little experience playing with arrays.
     
    Rukbat, Sep 12, 2011 IP
  20. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #20
    Okay things are going good today...Rukbat, I have the cells changing nicely with the following code:

    
    
    function try_ajax(neato) {
    	
    $.ajax({
      type: "POST",
      url: "write_dates.php?cell="+neato,
      context: document.body,
      success: function(data){
        //data is now the value that PHP echoed
    phpsaid = data.split('|');
    var state = phpsaid[1];
    if (state == '1'){
         document.getElementById(phpsaid[0]).style.backgroundColor = "#0F0";
    	 document.getElementById("response").innerHTML= phpsaid[0]+' Has Been Successfully Added to Your Reservation';
    	 }
    else 
        {
    	 document.getElementById(phpsaid[0]).style.backgroundColor = "#CCC";
    	 document.getElementById("response").innerHTML= phpsaid[0]+' Has Been Successfully Removed From Your Reservation';
    
        }
      }
    });
    
    
    }
    
    
    Code (markup):
    Now, what I am trying to get done is to return all the cell colors to grey if someone hits the "clear all reservations" button

    Here is my current function that clears the dates from the database:

    
    
    function ajax_clear(wipe) {
    	
    	
     $.ajax({
      type: "POST",
      url: "write_dates.php?type="+wipe,
      context: document.body,
      success: function(data){
        //data is now the value that PHP echoed
      document.getElementById("response").innerHTML= data;
      }
    });
    
    }
    
    
    Code (markup):
    so now what should my strategy be for changing all the selected cells back to grey when someone hits the clear button? Can I just do some javascript to change the color of all the cells on the page or should I do similar to the function that changes the individual cell? So I would put all the dates in an array, then echo it back with a separator then split them like above and have javascript loop through each date sent back and change the color of that cell?

    My problem is that I can get the ajax function to affect a single cell, but anytime I add something to the ajax_clear function meant to influence all cells in the table, nothing happens.

    A few things I have tried would be something like "document.getelementsbyClassName('the class I am looking for').style.backgroundColor ="whatever color I want"

    I have tried getelementsbyTagName and others too just to see if I can get something to work, but again, I can't seem to influence everything. Maybe attacking each individual cell is the better way anyways, but I am not sure.

    Ideas?
     
    absentx, Sep 14, 2011 IP