PDA

View Full Version : Javascript.



ben0
09-30-2008, 05:49 AM
Hi Folks,

I'm praying someone can help me with this JavaScript below. It's from an Auto suggest script. I'm trying to modify it to suit my needs and my knowledge of JS is very limited.

So i need to pass a variable to the autosuggestReply() from this line here http.onreadystatechange = autosuggestReply; but I don't thats allowed. :confused: As soon as I put it into brackets the script fails. I basically need to pass it the element ID of the div to the results to be dropped below the right form input.

Can anyone help me?

TIA

function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();

function autosuggest(inputname,inputid,queryid)
{
q = document.getElementById(inputid).value;
// Set the random number to add to URL request
nocache = Math.random();
http.open('get','search.php?inputname='+inputname+ '&queryid='+queryid+'&query='+q+'&nocache = '+nocache);
http.onreadystatechange = autosuggestReply;
http.send(null);
}

function autosuggestReply()
{
if(http.readyState == 4)
{
var response = http.responseText;
e = document.getElementById('results');
if(response!="")
{
e.innerHTML=response;
e.style.display="block";
} else {
e.style.display="none";
}
}
}

minijb
09-30-2008, 06:37 AM
So i need to pass a variable to the autosuggestReply() from this line here http.onreadystatechange = autosuggestReply; but I don't thats allowed. :confused: As soon as I put it into brackets the script fails. I basically need to pass it the element ID of the div to the results to be dropped below the right form input.


additions in bold


function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();

function autosuggest(inputname,inputid,queryid,divid)
{
q = document.getElementById(inputid).value;
// Set the random number to add to URL request
nocache = Math.random();
http.open('get','search.php?inputname='+inputname+ '&queryid='+queryid+'&query='+q+'&nocache = '+nocache);
http.onreadystatechange = autosuggestReply(divid);
http.send(null);
}

function autosuggestReply(divid)
{
if(http.readyState == 4)
{
var response = http.responseText;
e = document.getElementById(divid);
if(response!="")
{
e.innerHTML=response;
e.style.display="block";
} else {
e.style.display="none";
}
}
}

now you pass the target div for the autocomplete via the divid param when calling autosuggest.
untested, but should help you i hope

ben0
09-30-2008, 07:07 AM
Hey, thanks for replying - I really appreciate it!

So I tried adding in your suggestions and the script fails. I don't really have a clue on debugging JS but this is what I have tried:

function autosuggestReply(divid)
{
alert(divid); // This alert is displayed..
if(http.readyState == 4)
{
alert(divid); // If I place the alert here it doesn't get displayed.
var response = http.responseText;
e = document.getElementById(divid);
if(response!="")
{
e.innerHTML=response;
e.style.display="block";
} else {
e.style.display="none";
}
}
}


So I'm pretty much stuck now, I can't figure out why adding the variable to the function would cause it to fail :confused:

So this is what I have got. With the changes the http ready returns 1 and then the script doesn't return any results. Without the changes the http ready state goes from 1 - 4 then shows results then goes back to 1.

I have to leave work now but I am going to try and dig some info out when I get home, but any help would be a most helpful :)

TIA.
Ben0

ben0
09-30-2008, 08:25 AM
I think i've sorted it. Here is the finished article - it seems to work, I'm going to try it in a proper form tonight:

ajax_framework.js:

/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();

function autosuggest(inputname,inputid,queryid,divid)
{
q = document.getElementById(inputid).value;
// Set the random number to add to URL request
nocache = Math.random();
http.open('get','search.php?inputname='+inputname+ '&queryid='+queryid+'&query='+q+'&nocache = '+nocache);
http.onreadystatechange = function()
{
if(http.readyState == 4)
{
var response = http.responseText;
e = document.getElementById(divid);
if(response!="")
{
e.innerHTML=response;
e.style.display="block";
} else {
e.style.display="none";
}
}
}
http.send(null);
}


autosuggest.php:

<!-- AJAX AUTOSUGGEST SCRIPT -->
<script type="text/javascript" src="ajax_framework.js"></script>

<script type="text/javascript">
function getValue(div,inputname)
{
var x = document.getElementById(div);
document.myform[inputname].value = x.innerHTML;
}

function closeDiv(divid)
{
document.getElementById(divid).style.display = 'none';
}
</script>

<div id="search-wrap">
<form name="myform">
<input name="search" id="searchq" type="text" onkeyup="javascript:autosuggest('search','searchq','student ','search_results')"/>
<div id="search_results"></div>

<input name="search1" id="searchq1" type="text" onkeyup="javascript:autosuggest('search1','searchq1','stude nt','search_results1')"/>
<div id="search_results1"></div>
</form>
</div>

search.php:

<?php
include '../functions/constants.php';
?>

<?php
$connection = @mysql_connect(DBSERVER,DBUSER,DBPASS);
@mysql_set_charset('utf8',$connection);
@mysql_select_db(DBNAME, $connection);
$search = strip_tags($_GET['query']);
$queryid = strip_tags($_GET['queryid']);
$inputname = strip_tags($_GET['inputname']);
$searchword = explode(" ", $search);
for( $i = 0; $i < sizeof($searchword); $i++ )
{
$searchword[$i] = "student_firstname LIKE '%" .$searchword[$i]. "%'";
}
$queryselect = implode(" AND ", $searchword);
$query = "SELECT * FROM `student` WHERE ($queryselect)";
$getRecord = mysql_query($query);
$i = '1';
if(strlen($search)>0)
{
?>
<div onclick="closeDiv('<?php echo $search; ?>')" id="<?php echo $search; ?>">
<?php
while ($row = mysql_fetch_array($getRecord))
{
?>
<div onclick="getValue('div<?php echo $i; ?>','<?php echo $inputname; ?>')" id="div<?php echo $i; ?>"><?php echo $row['student_firstname']." ".$row['student_surname']; ?></div>
<?php
$i++;
}
?>
</div>
<?php
}
?>


If anyone has any suggestions, let me know, but so far seem ok!

PS. Ignore the query variable, im eventually going have predefined querys to select data from different tables.

Thanks!

minijb
10-01-2008, 01:55 AM
http.onreadystatechange = function()
{
...
}


Oops, didnt read it properly last night. Guess thats why you shouldnt post untested programming tips at 2am while you are sick and have spent all day looking at code...

http.onreadystatechange = something
the above is assigning a function as the callback to be executed when readystatechange event occurs. This callback only gets called later, and the location where this function is called doesnt know about the function arguments and calls it without args. In other languages you normally "bind" the argument to the function to produce a new function that no longer needs the bound argument. In javascript I dont think there is such a mechanism built-in, however you can achieve the same effect via this technique (http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=14c020c7-20a6-47d7-b445-9c3ecda153b2). Then the below would work

http.onreadystatechange = BindArguments(autosuggestReply, divid);

BindArguments is returning a null-ary function (the callback) that calls the unary function with the divid parameter. The final effect is the same as your current anonymous function method, its just a style choice.

ahmad
10-04-2008, 12:38 AM
There are several ways to overcome such a problem, one way is like it was suggested to have the parameters get passed from a function that returns that function, since items are passed by value and not reference in javascript.

Another way is using anonymous methods like you did, yet another is using global members. But you have bigger problems.

I can tell you without running your code, this will not work in IE7 correctly (possibly 6 and 5 as well). Microsoft caches similar requests when it comes to ActiveXObjects to help you, but it ends up not working because it would always behave the same regardless of any input you specify afterwards. You may want to consider testing this further just so you are convinced there is a bug.

One way to overcome it is by passing a random variable with every request to ensure it doesn't try to cache it. Another is this which I got from Microsoft's own API for ASP.NET AJAX callbacks:


if (!window.XMLHttpRequest) {

window.XMLHttpRequest = function window$XMLHttpRequest() {

var progIDs = [ 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP' ];

for (var i = 0, l = progIDs.length; i < l; i++) {

try {

return new ActiveXObject(progIDs[i]);

}

catch (ex) {

}

}

return null;

}

}


Then rather than doing your createObject call, you would simply do:

var http = new XMLHttpRequest();

And this works. Although I am not sure if this overcomes the caching issue, but it doesn`t seem to occur when done in this manner and I never had a problem with it.

ben0
10-04-2008, 12:06 PM
Awesome, thanks for all your help guys :-)

Im quite new to coding, I've only being doing PHP for about 9 months, but JS and others really confuse me and I haven't got the time to study whilst writing the application I've got in hand, so nuch appreciated it folks!

I will give it a go this week.

:)