/    Sign up×
Community /Pin to ProfileBookmark

Need to use variable on refresh..

Hi all,

I am struggling with a javascript problem..

I have two drop down boxes. the first is Month, second has Days. The number of days in the box (eg: 28,29,30,31) depends on which month is selected, so march would be 31,april would have 30 days etc…

Most of my work is in PHP, but this sort of thing cant be achieved without sending the form to the server, which i dont want to do, i need it to be dynamic..

I need to reload the page to reflect the changes, but when i do, the variable resets it self i think…

please see the following code….this section is in the <head> tag of my .php file..

<script language=”javascript”>
<!–
var days;
var reloaded = false;

function calc_days(month)
{

switch(month)
{
case 1: days = 31;
break;
case 2: days = 28;
break;
case 3: days = 31;
break;
case 4: days = 30;
break;
case 5: days = 31;
break;
case 6: days = 30;
break;
case 7: days = 31;
break;
case 8: days = 31;
break;
case 9: days = 30;
break;
case 10: days = 31;
break;
case 11: days = 30;
break;
case 12: days = 31;
break;

default: alert(“missed all cases”);
break;

}

reloaded = true;
window.location.reload(true);
}

function show_days(numDays)
{
for(var i = 1; i <= numDays; i++)
{
document.write(“<option>” + i + “</option>”);
}

}

//–>
</script>

How this is executed:

The month dropdown box has onchange=”calc_days(this.selectedValue)”….

and to display the days drop down box i have:

<select name=”days”>
<option SELECTED><–></option
<script language=”javascript”>
<!–
if(reloaded == true)
{ show_days(days); alert(“done with days variable:”); // debug statement
}
else
{
show_days(31); alert(“done without days:”); // debug statement
}
//–>
</script>
</select>

The show_days function relies on the reloaded variable to be true to excecute with the days variable….The problem is, when i have reloaded the page, both variables are gone because of the nature of javascript..

Does anyone have an alternative for select boxes where the 2nd one’s options depend on the value selected in the first one??

Any suggestions greatly appreciated..

Dave

to post a comment
JavaScript

7 Comments(s)

Copy linkTweet thisAlerts:
@BuezaWebDevSep 07.2006 — Try using a cookie.

Or, you could use an XMLHttpRequest object to send the currently selected values to a PHP object, which will set the session values, then when you load up the page, just load up those session values.
Copy linkTweet thisAlerts:
@funtmachineauthorSep 07.2006 — hi BuezaWebDev,

thanks for your reply...

I have been reading "ajax" tutorials in the last hour, and im not sure if i quite understand what i need to do in my situation...

I gather that i need all the required functions for the xmlhttprequest object, but do i also need an external file that specifies what the options of the second drop down menu will be?

you were saying it would set session variables for php, is there any other info you could help me out with (newbie) on how to do this in my situation??

Thanks heaps...

Dave
Copy linkTweet thisAlerts:
@BuezaWebDevSep 07.2006 — So, this is how the system would interact with the user:

1) Page loads

2) User selects month

3) User selects day

4) Trigger onChange javascript function (perhaps call it init())

5) init() initiates xmlhttprequest object and sends a GET query string with an asyncronous call to a file called "session.php"

6) session.php?month=1&day=2 --> takes those 2 values and inserts it into the session
[code=php]
session_start();
//check if month is valid month range
//--code goes here
//check if day is valid day range
//--code goes here

//set session variables based on the $_GET parameters
$_SESSION['month'] = $chosenMonth;
$_SESSION['day'] = $chosenDay;

//note, it is probably better practice to create an actual object to do this logic...
//but for this example, let's keep it procedural
[/code]


on your actual page with those drop down lists...ensure this is at the top:
[code=php]
session_start();
[/code]


Also, when you populate the month dropdown list, add logic that goes like this:
<i>
</i>if(month == '&lt;?php echo $_SESSION['month']; ?&gt;') {
document.write("&lt;option selected='selected'&gt;" + month + "&lt;/option&gt;");
} else {
document.write("&lt;option&gt;" + month + "&lt;/option&gt;");
}


This logic snippet will show determine which month was last selected when the page reloads. You will also need to triger another function that will repopulate the days drop down list.
Copy linkTweet thisAlerts:
@funtmachineauthorSep 07.2006 — ok, im sort of getting there...damn newbie

this is how my system runs...

  • 1. User selects month.

  • 2. Month has onchange="init(this.selectedIndex)".

  • 3. init() is called and instantiates a new XMLHttpRequest object called "http".

  • 4. Then comes the tutorial stuff i found and put in, and it is SUPPOSED to send a $_GET query (i think) to session.php.

  • 5. session.php then sets $_SESSION['month'] to $_GET['month'], and returns to scheduler.php (the file with the select boxes..)

  • 6. Thats all i'm trying to do at the moment, have the month set in a session variable so that i can use it to determine the number of days in that month in another function, and populate the days drop down box accordingly..


  • See Code Here:

    **Month select box:**

    <select name=monthStart onchange="init(this.selectedIndex)" style="font-size:10pt;;height:20px;">


    **init() Function, and required other function from tutorial:**

    function init(param)

    {

    //http = new ActiveXObject("Microsoft.XMLHTTP");
    http = new XMLHttpRequest(); //for all standards compliant browsers (everything except ****ty IE 5+)

    http.open("GET", "session.php?month=" + escape(param), true);
    http.onreadystatechange = useHttpResponse;
    http.send(null);
    }

    function useHttpResponse()
    {
    if (http.readyState == 4)
    {
    var textout = http.responseText;
    document.write.textout;
    }
    else
    {
    alert("didnt work!!");
    }
    }



    **** Finally, session.php code ****

    [code=php]<? //"session.php"
    session_start();
    $_SESSION['month'] = $_GET['month'];
    header("location: scheduler.php"); //Go back to the page with select boxes..do i even need to do this??

    ?> [/code]


    So you can sort of see the flow better now i have explained it like this i think... Do i need that other function useHttpResponse()? i think im not writing a correct $_GET query, or its not reaching session.php or something??

    Cheers,

    Dave
    Copy linkTweet thisAlerts:
    @BuezaWebDevSep 07.2006 — You don't need the header because that script will only receive data via query string (GET) and set the session variable with the query string's value.

    Quite possibly, you don't even need the useHttpResponse function, or the onreadstatechange.

    <i>
    </i>http.open("GET", "session.php?month=" + escape(param), true);
    http.send(null);


    The way I look at it, you only need to send data to the script, script sets the session variable, and then your form retrieves data from the session variable.
    Copy linkTweet thisAlerts:
    @funtmachineauthorSep 07.2006 — Ok, heres a weird one.....

    I got it working....BUT.....it only works some of the time... sometimes it is correct, sometimes it isnt... i think the ajax code is correct now, but it might be my php stuff, check this new code out...

    After setting $_SESSION['mth'], i proceed to fill the days select menu with a php function called select_day(). the parameter i pass in is the $_SESSION['mth'] variable, which then is put into a switch statement to determine the number of days...


    ***************************

    [code=php]

    function select_day($month)
    {
    ?><script language="javascript">alert("month is: " + <? echo("$month");?>);</script><?

    switch($month)
    {
    case 1: $numDays = 31;
    break;
    case 2: $numDays = 28;
    break;
    case 3: $numDays = 31;
    break;
    case 4: $numDays = 30;
    break;
    case 5: $numDays = 31;
    break;
    case 6: $numDays = 30;
    break;
    case 7: $numDays = 31;
    break;
    case 8: $numDays = 31;
    break;
    case 9: $numDays = 30;
    break;
    case 10: $numDays = 31;
    break;
    case 11: $numDays = 30;
    break;
    case 12: $numDays = 31;
    break;

    default: $numDays = 4;
    break;

    }

    for($i = 1; $i <= $numDays; $i++)
    {
    ?><option><? echo("$i"); ?></option><?
    }
    }

    [/code]


    What do you think???

    See, when it works, the days are numbered correctly according to the month selected, but sometimes it hangs on a month even when you select a new one..could it be that the value isnt being cleared or overwritten sometimes?

    It seems, that its working every second time....

    Dave
    Copy linkTweet thisAlerts:
    @BuezaWebDevSep 10.2006 — Perhaps the $month value doesn't exist or is null--try putting the switch statement above this line:

    [code=php]
    ?><script language="javascript">alert("month is: " + <? echo("$month");?>);</script><?
    [/code]
    ×

    Success!

    Help @funtmachine spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.13,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...