...

View Full Version : Object expected error



chesneil
07-21-2002, 06:33 PM
This started out as a cookie question. Now it seems to be just a coding problem - I get
'an object expected' error. (The script reads a cookie and gives 'message1' on the first visit, thereafter messages 2 or 3 depending on whether the previous visit was less or more than a week previously). But I don't think the problem's anything to do with cookies.

Here is the code in the BODY:
--------------------------------------
<script>
var rightnow=new Date();
var now=rightnow.getTime();
var last=lastvisit();

if (Count()==1){
document.write("Message1")
When()
}
else{
if ((now-last)<(7*24*60*60*1000)){
document.write("Message2");
}
else{
document.write("Message3");
}
}
</script>
----------------------------------------

The problem (I think) is the 'lastvisit()' function (that's where I get the 'object expected' error). That's in the HEAD code (in an external file), which includes the following:

----------------------------------------------
function lastvisit(){
var last_time=lastHereFormatting.getTime();
return last_time;
}
-----------------------------------------------

where 'lastHereFormatting' has been declared in the surrounding function. You can see where it's placed in the whole script below. I think there's a problem where it's placed in the HEAD code. But I've moved it just about everywhere and there's always some kind of error (mostly 'lastHereFormatting not defined'). I've put hours into this, but as a newbie I don't have any experience to fall back on. PLEASE someone take a look and tell me what's wrong. I'd appreciate it. It's just that last fence eluding me...

Here's the HEAD code. I've clearly marked the offending piece:
--------------------------------------------------

//Display Time of last visit script- Mattias Sjoberg
//Modified by JavaScript Kit (http://javascriptkit.com)
//Visit http://javascriptkit.com for this script

var expDays = 360;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

function When(info){
// When
var rightNow = new Date()
var WWHTime = 0;
WWHTime = GetCookie('WWhenH')

WWHTime = WWHTime * 1

var lastHereFormatting = new Date(WWHTime); // Date-i-fy that number

var intLastVisit = (lastHereFormatting.getYear() * 10000)+(lastHereFormatting.getMonth() * 100) + lastHereFormatting.getDate()
var lastHereInDateFormat = "" + lastHereFormatting; // Gotta use substring functions
var dayOfWeek = lastHereInDateFormat.substring(0,3)
var dateMonth = lastHereInDateFormat.substring(4,10)
var hours = "" + lastHereFormatting.getHours()
var year = lastHereFormatting.getYear()
if (year < 1000) year+=1900
var minutes = "" + lastHereFormatting.getMinutes()
if (minutes.substring(0,1) == minutes){
minutes = "0" + minutes;

//////////HERE///////////////////////////////
function lastvisit(){
var last_time=lastHereFormatting.getTime();
return last_time;
}
/////////////////////////////////////////////

}

var WWHText = dayOfWeek + ", " + dateMonth + " " + year + " at " + hours + ":" + minutes// display

SetCookie ("WWhenH", rightNow.getTime(), exp)

return WWHText;
}

function Count(info){
var psj=0;
// How many times
var WWHCount = GetCookie('WWHCount')
if (WWHCount == null) {
WWHCount = 0;
}
else{
WWHCount++;
}
SetCookie ('WWHCount', WWHCount, exp);

return WWHCount+1;
}

function set(){
// VisitorName = prompt("Who are you?", "Nada");
// SetCookie ('VisitorName', VisitorName, exp);
SetCookie ('WWHCount', 0, exp);
SetCookie ('WWhenH', 0, exp);
}

function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}

function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}

function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
// This cookie is history
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

chesneil
07-22-2002, 05:13 AM
Maybe I can make the problem a bit simpler:
I'm sure the 'lastHereFormatting' object in the HEAD records the previous visit, and that's what I'm trying to pass to the BODY code with the lastvisit() function.

Someone...please!

glenngv
07-22-2002, 09:47 AM
you have declared function within a function. Watch your curly braces, it should be properly closed. And the variable lastHereFormatting should be declared global, that is, outside any function.

mordred
07-22-2002, 10:11 AM
From what I see in your code I assume you're simply having a problem with variables scope. If you put a function into another, then it becomes a nested function and can't be called from the outside. It's sort of invisible this way.

Essentially you need the variable lastHereFormatting to be visible to your lastvisit() function, so that it can call a method of this date object. In the function When() the variable is instantiated like this:

var lastHereFormatting = new Date(WWHTime); // Date-i-fy that

Notice the "var" keyword at the beginning of the line? When this keyword is applied within a function, a local variable is defined. Such a variable is not visible to functions outside. But if you don't use "var", a global variable will be created, which can be used by other functions.

So drop the "var" and put your function lastvisit() outside of other functions. That should do the trick; although, your specific implementation is somewhat complex so my suggestion might need further amendments.

chesneil
07-22-2002, 11:13 AM
All brackets match up.

I deleted the var from

lastHereFormatting=newDate(WWHTime);

but kept it in the same place.

I also moved the entire lastvisit() function to the very bottom of the script, below any curly brackets.

Now I get the error message 'lastHereFormatting is undefined'.

mordred
07-22-2002, 12:12 PM
Do you also actually call the When() function before you call lastvisit()?
If not, your global variable lastHereFormatting does not get set and can't be worked upon.

chesneil
07-22-2002, 01:07 PM
MANY thanks guys - by your help it now works. I'd buy you a beer if it were possible. Ah... the euphoria :)

What I did, following your advice, was add the When() function to the second else statement in the BODY. I also copied:

WWHTime = GetCookie('WWhenH');
WWHTime = WWHTime * 1;
lastHereFormatting = new Date(WWHTime);

to above the function When(info) at the top of the HEAD.

Here's the complete code just in case anyone else needs it...unlikely:
-------------------------------------------------------------------------------------

HEAD
var expDays = 360;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

WWHTime = GetCookie('WWhenH');
WWHTime = WWHTime * 1;
lastHereFormatting = new Date(WWHTime);

function When(info){
// When
var rightNow = new Date()
var WWHTime = 0;
WWHTime = GetCookie('WWhenH')

WWHTime = WWHTime * 1

lastHereFormatting = new Date(WWHTime); // Date-i-fy that number

var intLastVisit = (lastHereFormatting.getYear() * 10000)+(lastHereFormatting.getMonth() * 100) + lastHereFormatting.getDate()
var lastHereInDateFormat = "" + lastHereFormatting; // Gotta use substring functions
var dayOfWeek = lastHereInDateFormat.substring(0,3)
var dateMonth = lastHereInDateFormat.substring(4,10)
var hours = "" + lastHereFormatting.getHours()
var year = lastHereFormatting.getYear()
if (year < 1000) year+=1900
var minutes = "" + lastHereFormatting.getMinutes()
if (minutes.substring(0,1) == minutes){
minutes = "0" + minutes;

}

var WWHText = dayOfWeek + ", " + dateMonth + " " + year + " at " + hours + ":" + minutes// display

SetCookie ("WWhenH", rightNow.getTime(), exp)

return WWHText;

}

function Count(info){
var psj=0;
// How many times
var WWHCount = GetCookie('WWHCount')
if (WWHCount == null) {
WWHCount = 0;
}
else{
WWHCount++;
}
SetCookie ('WWHCount', WWHCount, exp);


return WWHCount+1;
}

function set(){
// VisitorName = prompt("Who are you?", "Nada");
// SetCookie ('VisitorName', VisitorName, exp);
SetCookie ('WWHCount', 0, exp);
SetCookie ('WWhenH', 0, exp);
}

function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}

function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}

function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
// This cookie is history
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();

}

function lastvisit(){
var last_time=lastHereFormatting.getTime();
return last_time;
}

----------------------------------------------------------------------------

BODY
var rightnow=new Date();
var now=rightnow.getTime();
var last=lastvisit();


if (Count()==1){
document.write("Message1")
When()
}
else{
When()
if ((now-last)<(7*24*60*60*1000)){
document.write("Message2");
}
else{
document.write("Message3");
}
}
</script>

ConfusedOfLife
07-23-2002, 11:16 AM
Well, to be frank, I couldn't understand this code that much, it seems too long, I think you could have written that much easier, anyway, look at mine, it works too, but maybe it doesn't have some of your capabalities, just give it a try!

<html>
<head>
<title>Untitled</title>
<script>
function init()
{
expireDate = new Date();
expireDate.setYear( expireDate.getYear() + 1);
if ( document.cookie == "" )
{
alert("Welcome, it's your first visit");
ourDate = new Date();
document.cookie = ourDate.getYear() + "-" + ourDate.getMonth() + "-" + ourDate.getDay() + "=" + "Null"
+ "; " + "expires=" + expireDate.toGMTString();
document.cookie = "visitsNumber=1; " + "expires=" + expireDate.toGMTString();
}
else
{
readData = "";
readData = document.cookie.split("; ");

// Getting the old date in the cookie.
ourYear = readData[0].split("=")[0].split("-")[0];
ourMonth = readData[0].split("=")[0].split("-")[1];
ourDay = readData[0].split("=")[0].split("-")[2];

// Getting the current date.
currentDate = new Date();
if ( currentDate.getDay() <= ourDay + 7 &&
currentDate.getMonth() == ourMonth )
alert("It's not even a week that you paid a visit!");
if ( currentDate.getMonth() == ourMonth + 1 )
alert("About two month ago you just registered!");

// Getting the number of visits.
visitsNumber = 0;
visitsNumber = readData[1].split("=")[1];
document.write("You visited this site " + String(visitsNumber) + " times!");

// Incerementing the visitsNumber inside of the cookie.
++visitsNumber;
document.cookie = "visitsNumber=" + visitsNumber + "; " + "expires=" +
expireDate.toGMTString();

// You can add your other conditions or messages in here!
}
}
</script>
</head>

<body onload="init();">



</body>
</html>


// Wow! I finally blurted that out!!

chesneil
07-23-2002, 04:39 PM
ConfusedOfLife. Thanks for posting your solution. Actually I sent the job off (as it worked). Even though I'm a beginner at this thing called javascript, I was surprised how different it looked compared to the codes in the textbook, considering there wasn't anything unusual in the original. As you can see above, I cut and pasted the script and with help from some of the forum guys and a pinch of my own savvy I got it to work.

However, as a determined-to-learn beginner I printed your code out and went through it line by line. Your code is certainly 'textbook-friendly' (i.e. I mostly understand it) but if you'll help me out I've got some questions which I'm sure are simple to answer if you're familiar with js. I've marked the lines below to make it easy to see what I'm on about.

Q1. Is this just a simple way to see the cookie exists (i.e. an empty cookie is the same as a non-existant one)?

Q2. Is the Null statement here just an empty element to keep the a=b format (I presume so because the name of the cookie in my preferences is '2002-6-3')?

Q3. Why is this line necessary? On the next line it gets a new value anyway. I've seen such illogical (to me) assignments all over the place.

Q4. This line is called if a cookie exists. But there are two cookies, so which one is split into an array? Or does this apply to any cookie of this document?

Q4a I don't understand how this knows which cookie to split. The array is from the first cookie, but how does it know to opertate on that one?

Q5. same as Q3 I think.

Q6. This is like Q4 again. This gets its value from the second cookie. How does it know which cookie?

Q7. readData has split and created an array around the ';'. So surely in the second cookie, readData[1] is 'expires=....' and readData[0] is 'visitsNumber=x'. I know I'm wrong because the code works, but...

I bet you wished you'd never replied. But I would be grateful for some basics here! Thanks a lot.
(I've been looking at this too long. No idea if it makes sense :(
-----------------------------------------------------------
<html>
<head>
<title>Untitled</title>
<script>
function init()
{
expireDate = new Date();
expireDate.setYear( expireDate.getYear() + 1);
if ( document.cookie == "" ) //////////////////////////Q1
{
alert("Welcome, it's your first visit");
ourDate = new Date();
document.cookie = ourDate.getYear() + "-" + ourDate.getMonth() + "-" + ourDate.getDay() + "=" + "Null" ///////////////////////////////Q2
+ "; " + "expires=" + expireDate.toGMTString();
document.cookie = "visitsNumber=1; " + "expires=" + expireDate.toGMTString();
}
else
{
readData = ""; ////////////////////////////////////Q3
readData = document.cookie.split("; "); ///////////////////////////////Q4

// Getting the old date in the cookie.
ourYear = readData[0].split("=")[0].split("-")[0]; ////////////////////Q4a
ourMonth = readData[0].split("=")[0].split("-")[1];
ourDay = readData[0].split("=")[0].split("-")[2];

// Getting the current date.
currentDate = new Date();
if ( currentDate.getDay() <= ourDay + 7 &&
currentDate.getMonth() == ourMonth )
alert("It's not even a week that you paid a visit!");
if ( currentDate.getMonth() == ourMonth + 1 )
alert("About two month ago you just registered!");

// Getting the number of visits.
visitsNumber = 0; ///////////////////////////////////Q5
visitsNumber = readData[1].split("=")[1]; ///////////////////////Q6 & Q7
document.write("You visited this site " + String(visitsNumber) + " times!");

// Incerementing the visitsNumber inside of the cookie.
++visitsNumber;
document.cookie = "visitsNumber=" + visitsNumber + "; " + "expires=" +
expireDate.toGMTString();

// You can add your other conditions or messages in here!
}
}
</script>
</head>

<body onload="init();">



</body>
</html>

ConfusedOfLife
07-25-2002, 11:48 AM
Hi dear chesneil, well, at first = I'm still a begginer too, it means that we don't have much differences. But when I satrated learning about cookies ( about 3 weeks ago!), I was really curious to see how they work, and I started working on that.
At first I'm gonna say some basics, then we go to your questions, and, you lost your bet! I didn't wish I'd never replied!

ok, each document has a seperate cookie file, it means that if you wana see if the cookie file is filled with something or not, you can simply write:

if ( document.cookie == "" )
{
// Do something when it's empty.
}
else
{
// Do something else when it's NOT empty!
}

ok? well, about writing and reading from the cookie file. I dunno if you ever programmed with C, Pascal or well, other languages, but reading and writing into a file is very easy, I mean you just have one directive to write into your desired file ( or some bunch of commands that are similiar) and another command to read from the file, but the way that you make up your file, I mean the structure that you use inside of your file is very important. And this is the structure that makes your file, let's say written in C language, different with mine, coz if you used a seperator like "|" for your fields, then you use this seperator between each field, and if I want to decode your file, I have to find this seperator first! Or I can not do that! coz we know that whatever is between the seperators are our fields! ok? so, java script is really simpler, the seperator is that little "; " or ";", based on what you choose. I mean you write something to your cookie file in this way:

name1=value1; expiration=A fancy date
name2=value2; expiration=A fancy date
name3=value3; expiration=A fancy date

Look at the "; " after the values (i.g. value1, value2 & value3), it's our seperator.
Now if you want to get the contents of your cookie file, you have to write something like this:

ourContents = document.cookie;

But just remember that, the document.cookie does NOT give you the expiration date! nor the path! ok? it means, in our case, you'll have the following in your ourContents:

ourContents = "name1=value1; name2=value2; name3=value3"

you see? so, our variable, I mean ourContents, now is just a simple string variable, if you want to split it to your contents, you can use:

splittedContents = ourContents.split("; ");

If you're familiar with the split function, you know that it'll return an array, so, our array now has the following items:

splittedContents[0] = "name1=value1";
splittedContents[1] = "name1=value2";
splittedContents[2] = "name1=value3";

and now for example if you wana have the name and the value of splittedContents[0], you can use the following:

complex = splittedContents[0].split("=");
ourName = complex[0];
ourValue = complex[1];

but it's no need to define that "complex" variable in here, we can simply use:

ourName = splittedContents[0].split("=")[0];
ourValue = splittedContents[0].split("=")[1];

you see those little indexes that I used in front of "splittedContents[0].split('=')" ??? They do the trick! And you can use multiple indexes and multiple splits in just one line, java script can understand it. If you wana know more about the split function ( you have to know mroe!), just go for it!

ok, what most of ppl do ( not most of them!) is that when they wana search for something inside the cookie file, they use the "indexOf()" function, the thing that I don't like, I use the split function, to split the contents, and then with a simple "for" loop, I search all the array to find my name of value, you got it?

now something else, putting that "; " is necessary, putting the expiration date, if you want your cookie to live after the user closes the browser window is necessary, but putting the name and the value in the way that you like is totally optional, also that "=" is necessary! So, just imagine that we wanted to mix our name and our value and put them together in the left side of the "=", and just write something that we like, like "hello" as our value in the right part of the "=", so, what should we do? well, just define a fancy splitter for yourself, let's say your name is "hisAge", and your value is "18", so, we write it in this way into the cookie file:

hisName^18=hello; expiration= ........

now if we want to retrive our name and value, we first check that if cookie is not empty ( your Q1 answer!), then we can write:

contents = document.cookie.split("; ");
field = contents[0].split("=")[0] // it omits the "hello"!!
ourName = field.split("^")[0];
ourValue = field.split("^")[1];

well, I think you can understand what I write now, what I did, was to use a fancy splitter myself ( it's a kinda trick that you can mix lots of names and values into just one field!) and I put that fancy "Null" in there, you can put anything that you like, "Null" just works as "Hello" in our example! You got it? I mixed the yearDate, monthDate and the dayDate ( I can't remember what are the exact variables names, but it's easy to look it up, huh?!), so, you could have written that easier, I mean defining 4 fields, three of them for the yearDate, monthDate, and dayDate and the last one for your counter. it could have been like:

ourYear=theYear; expires=......
ourMonth=theMonth; expres=......
ourDay=theDay; expires=.......
counter=theCounter; expires=.......

but then if you use "document.cookie.split("; ")", you'll have 4 items, instead of well, 2 items! it's not different! I mean coz I was working on a kinda URLBook based on cookies, I just put my own fancy seperators ( coz I needed them in that program really! ) but for now, it almost doesn't have any difference, it's just your taste that makes the final program! You understand now?

sorry if I wasn't specific to your questions, I mean writing their name (Q1 ...... Qn!!!) and answering them, but I'm gonna do that for this one:
Q3 : there are several way to define a new variable in js, one if to use for example "var readData= new String" or ......
but what I use is to write for example
readData = "";
to define a string, or
b = 0;
to define an integer! You might say why I don't write them in the place that I like and it itself makes it, then I say that sometimes your program crashes if you do that! sometimes it happend to me, js isn't that strong, belive me! at least for some begginers like me & you.

Now you should already know the answerof Q6 & Q7.
You said in

visitsNumber = readData[1].split("=")[1];

how it finds out which cookie? well, I wrote "readData[1].....", that index does the trick! "readData[0]" contains our mixed field, I mean the name that holds everything, and the value that does nothing! and readData[1] holds just the counter, you got it?

ConfusedOfLife
07-25-2002, 11:52 AM
I wrote some other things in the previous reply, but it seems it's a limit in here! it doesn't show everything! anyway, I just wrote that for an example on cookies, you can go to:

http://www.irandiba.net/confusedoflife/URLBook

It's something that I really worked on, but coz I didn't notice that cookie has a limit and it can not be more that 4Kbs, now the program isn't worth a ....!! but well, I just wrote it and I think it's good to see!

If you have any other questions, just feel free to ask, I'll answer if I can, good luck.

chesneil
07-25-2002, 03:47 PM
Excellent! Thanks very much. That's cleared up the misunderstandings I had. I didn't realize document.cookie doesn't give the expire date or path, etc.. Just a few more simple questions if you don't mind:

1) +String(visitsNumber) is the same as +visitsNumber? I know the former is a string and the latter a variable, but does it matter which type you use?

2) ++visitsNumber is the same as visitsNumber+=1? (No, no other programming except some simple Basic way back in the dark ages on my ZX81...when Debbie Harry was a sex symbol :) )

3) when you increment the visitsNumber (in your code), you simply write 'document.cookie="visitsNumber="+visitsNumber+...'. Does this just overwrite the existing statement in the SAME PLACE as the old one in your cookie? I wonder because you don't use indexOf(), so you have to know exactly where the information is in the cookie when you come back to it (i.e. when you split it you have to know what is where in the resulting array).

Cheers,
Chesneil

ConfusedOfLife
07-27-2002, 12:58 PM
You're welcome dear, well, I go straight to your questions:

1- Yeah, it is, I could have written "visitNumber", but coz the program wasn't working ( I don't say because of writing visitNumber) I added the things that I thought can make it work, and one of them answered, I dunno if it was this particular one or not! But just I assumed that like other programming languages, using "String(Number)", gives u a string, even though JS itself says that it does the data conversion automatically!

2- Yeah, ++visitNumber is equal to visitNumber+=1!! I put the latter coz I wanted to see if visitNumber is a string, coz if it be a string and visitNumber == 2 and then you write visitNumber+=1; then it'll be "21", not 3 !! Just another form, ok?

3- what you said is right, for over-writing something in the cookie file, you just have to know the name that you used, if you have

name="salam" + "; expires=....."

then you write:

name="hi" + "; expires=......"

then your name is gonna be "hi" after this and "salam" doesn't exist anymore ( you could have tested all these things yourself! besides, you can go to your windows\cookies directory, and open each cookie that you like, JS doesn't encode the cookies that much! Also, take a look at "escape()" function, it can help you alot in encoding, I used that in my URLBook a lot!)

Cheers,
ConfusedOfLife

chesneil
07-27-2002, 03:04 PM
Thanks a lot. Happily, I understand a lot more about cookies now.
Much appreciated :thumbsup:
Chesneil



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum