views:

396

answers:

8

Hello,

I have the following javascript code, which loads without error, however the update function does not actually seem functional, as get_Records.php is never loaded. I can not test if get_auction.php is loaded as it is loaded from within get_records.php

One of my main concerns is that I am doing the wrong thing by having update() take the paramters pk and query, as only one of them will ever be used. That seems like a bad hack, and poor logic, but I am not aware of a better way.

Here is the code

var xmlHttp
var layername
var url

function update(layer, part, pk, query) {
    alert ("update");
    if (part=="1") {
        alert ("part 1");
        url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
    } else if (part=="2") {
        alert ("part 2");
        url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
    }
    xmlHttp=GetXmlHttpObject()
    if(xmlHttp==null) {
        alert("Your browser is not supported?")
    }
    xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
            document.getElementById(layer).innerHTML=xmlHttp.responseText
        } else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
            document.getElementById(layer).innerHTML="loading"
        }
    };
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)
}

function GetXmlHttpObject() {
    var xmlHttp=null;
    try {
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
    }
    return xmlHttp;
}

function makewindows() {
    child1 = window.open ("about:blank");
    child1.document.write(<?php echo htmlspecialchars(json_encode($row2["ARTICLE_DESC"]), ENT_QUOTES); ?>));
    child1.document.close(); 
}

I placed alert statements into the update function, andnot one is displayed, indicated the update function is never called?

I do not want to, and cannot use a framework, nor do I have access to use firebug, so please do not suggest these things. I am aware of them and use them when I can.

I would also like to know if calling php from within makewindows() is preferred to having makewindows simply take a parameter.., is there any advantage or disadvantage to each approach?

I seem to get an error when trying to call the function, this is how I am doing it in PHP:

echo "<li><a href='#' onclick=update('Layer3','2','0','hello')'>Link 1</a></li>" .

which makes this html, which should be fine?"\n";

<li><a href='#' onclick='update('Layer3','2','0','hello')'>Link 1</a></li>

edit: I have taken tester101'S advice and changed it to this:

echo '<li><a href="#" onclick="update(\'Layer3\',\'2\',\'0\',\'hello\')">Link 1</a></li>' . "\n";

Which still gives an error. I will probably end up using toms answer, but would like to know why this is not working.

+1  A: 

Have you verified that the PHP code returns something sensible? (I assume, that you can view the source code of your html.)

Use good ol' alert-debugging: Insert alert statements (e.g. windows.alert("GetXmlHttpObject started.");) in your code to make sure that you reach them.

JSLint might help you. I tried it, though, and did not find anything really wrong.

Jan Aagaard
I edited the question showing the results of alert statements
Joshxtothe4
+1  A: 

If you can open your page in Firefox, I'd check the error console (c-s-J). It has helped me find many, many typos.

Also, your code seems to missing a lot of semicolons. Maybe some of them are optional but...

Michael Haren
+1  A: 

You could just take Url as a parameter to update(), then you wouldn't need to build the url within and you wouldn't need the 'optional' parameters

Edit (response to comment)

If you have an update() function that just takes url and element id (layer) and updates it based on the result of an AJAX call, you could do something like this to remove the need for optional parameters and using a function to do two different things.

function update(layer, url) {
    var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere

    if(xmlHttp==null) {
        alert("Your browser is not supported?");
    }

    xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
            document.getElementById(layer).innerHTML=xmlHttp.responseText;
        } else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
            document.getElementById(layer).innerHTML="loading";
        }

       //etc
    }

    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function updateByPk(layer, pk) {
   url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random();
   update(layer, url);
}


function updateByQuery(layer, query) {
   url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
   update(layer, url);
}

Then call either, depending on what you want to do:

updateByPk('id_of_div', 2);

or

updateByQuery('id_of_div2', 'query');

e.g. in HTML

<a href="#" onclick="updateByQuery('Layer3', 'hello');">Link 1</a>

or to generate that in PHP

<?php echo '<a href="#" onclick="updateByQuery(\'Layer3\', ' . json_encode($query) . ');">Link 1</a>';
Tom Haigh
is that the preferred way to do things? Is having two optional paramters bad form?
Joshxtothe4
Not necessarily, but it makes sense to split functionality into functions that perform smaller tasks - this will make your code more re-usable. You could have two functions which both call update but perform different logic to construct the url
Tom Haigh
I could have it just take the url, but pk and query must still be passed, and only one will ever be used. if I used another url to generate the url, I would still have the same problem with passing variables would I not?
Joshxtothe4
if only one is ever used why not have two functions, one that takes pk and one that takes query. They can then both individually generate the url and call update() from there
Tom Haigh
Makes sense.., so I would only have the layer and part parameters for update(), or if the url was being generated I would not even need the part parameter...?
Joshxtothe4
+1  A: 

If you can use Firefox and reproduce the error, I would strongly suggest using Firebug as it's really easy to use and step through scripts, set breakpoints, etc. Plus instead of having to use "alert" statements you can use things like console.info("unexpected value x=%o", some_object); and it will log a value to the console (including line #) that you can inspect later w/o interrupting your script.

edit: in fact, if you're using PHP on the server, you can use FirePHP to help debug on the client.

Jason S
+1  A: 

With regards to your concerns, as far as I am aware JavaScript does not complain if you dont give it all the arguments.

e.g

function myFunction(var1, var2, var3, var4){

calling this function like:

myFunction('test1','test2');

does not produce an error.

It is similar to putting a default next to an argument, the default being in javascript as null or undefined.

You can test for this by checking:

if(null != var3){

Might help you clean up that function a little; Also you can harvest a small ajax class from the web which will tidy up your javascript somewhat. There are plenty of wrapping functions out there that encapsulate the xmlHttpRequest object, allowing cross browser usage with identical results.

Let me know if you need any help. I have some confidence that if you find some prebuilt ajax methods (jQuery has some great functionality!), the task you are trying to achieve will be much easier.

Jay
I simply cannot use frameworks for this. Besides, I am interested in learning the underlying concepts. I guess there is no way to call var1, var2 and var4 but not var3?
Joshxtothe4
Can't you just pass false or null as the variable you dont want, and test for it in the code?
Jay
+1  A: 

Mismatched parentheses in

child1.document.write(<?php echo htmlspecialchars(json_encode($row2["ARTICLE_DESC"]), ENT_QUOTES); ?>));
Jimmy
you've got one opening bracket: .write( ... and two closing brackets: ));
nickf
fixed, but nothing changed.
Joshxtothe4
+1  A: 

onclick=update('Layer3','2','0','hello')'>Link 1

I don't know if it is a typo but this line should be


onclick="update('Layer3','2','0','hello')">Link 1



This code will cause errors and never call update, because the single quote after onClick= terminates at ('. Use double quotes.


onclick='update('Layer3','2','0','hello')'>Link 1
Tester101
Are double quotes required? From inside the php statement it is easier to use single quotes. I have changed the quote to include update, but it stil is not called.
Joshxtothe4
If you were calling update with no parameters you could use single quotes, but since you are using parameters enclosed in single quotes the function must be contained in double quotes.
Tester101
Ahh, Check my edit, I have changed it but still get an error.
Joshxtothe4
why are there \ in the string?
Tester101
are you receiving any error messages?
Tester101
A: 

Maybe too many newlines?

In most languages, you have either newline as command separator, or ";". In JavaScript, you have both: the newline sometimes works as ";"

Try this instead, see if that helps:

function update(layer, part, pk, query) {
   alert ("update");
   if (part=="1") {
      alert ("part 1");
      url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
   } else if (part=="2") {
      alert ("part 2");
      url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
   }
   // and so on...
}

The only thing different is the formatting: the opening curly is on the same line as the construct that uses it ('if','else','function',...).

Piskvor