PDA

View Full Version : Simple - Passing a variable into a function


samuurai
04-03-2008, 10:50 PM
Hi,

I'm just making my first steps with Javascript, i've got a bit of PHP experience and it's helping me learn java to a small degree, but i'm having trouble doing something really simple.. Passing a variable into a script.

Here's my code

<html>
<body>

<script type="text/javascript" src="rsh/json2007.js"></script>
<script type="text/javascript" src="rsh/rsh.js"></script>

<script type="text/javascript">
window.dhtmlHistory.create();

var yourListener = function(newLocation, historyData) {
//do something;
}

window.onload = function() {
dhtmlHistory.initialize();
dhtmlHistory.addListener(yourListener);
};
</script>



<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById('myDiv').innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("GET","time.php",true);
xmlHttp.send(null);
}
</script>
<button type="submit" onClick="ajaxFunction();">Click Me!</button>
<div name="myDiv" id='myDiv'>
Hello!!!
</div>

</body>
</html>

I want to pass the function ajaxFunction a variable of a url which would then populate where it says "time.php"

How can I do that?

mjlorbet
04-03-2008, 11:46 PM
this is not java, it's javascript, they are very very different & not related at all, please use the proper name in the future.

you create functions that accept variables like this


function myFunction(some_name){
alert(some_name);
}


see that there is a name between ( and ), this will be the name you use to access the variable passed in. you pass the value like this


myFunction("hello");


if you add this code to a page, you will get a box popping up telling you hello. if you don't have the value you need as a string literal (like in the above example) don't worry, the javascript parser will determine what you mean. just make sure that strings are in quotes & you'll do fine


var myMessage = "hello";
function myFunction(message){
alert(message);
}
myFunction(myMessage);


so you would modify your function to be like this


function ajaxFunction(url){
...
xmlHttp.open("GET", url, true);
...
}


and call it like this ajaxFunction("myUrl.php")

samuurai
04-04-2008, 12:33 AM
Wow, thanks for putting so much time and effort into responding. It worked perfectly!

Also, yes I don't know why I referred to it as Java.. It's late and i've been working for the last 14 hours. I've edited the post!

Thanks again!

Beren