Any ajax coders about?

Link

Tank
Joined
Apr 28, 2004
Messages
2,446
Reaction score
3
Hey guys. I know this isn't exactly the best forum to ask this, but I figure theres got to be 1 or 2 people here that know their way around a script :)

I'm starting to learn ajax, and have hit a little bit of a stumbling block. What I am trying to do is enter some text in an input box, and have that update into a <div>
. It does work, however, it only updates when the user clicks out of the box. Ideally I would want to to update as soon as text is entered, or maybe after a few seconds delay. I had thought the "onchange" value would call the update as soon as it is changed, but it dosen't seem to work that way.

Heres the code I'm using: Year.php
Code:
<div id="yearshowupdate">
Temp
</div>

The javascript that is called in the head of the page
Code:
var xmlhttp

function update_year(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  }
var url="year_update.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  *************ElementById("yearshowupdate").innerHTML=xmlhttp.responseText;
  }
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

And finally, the year_update.php that the javascript calls
Code:
<?php
echo $_GET['q'];
?>

As I say, it does work, when the user clicks out the box, whatever was typed in the box replaces "temp", but I can't figure out why it waits untill the user clicks out. Any suggestions?
 
I'm not really good with javascript but is there a reason you are doing the processing server side? If your php script won't be any more complicated than that it would be much more efficient to do this client side.

DreamThrall is very good when it comes to this from what I remember, you might want to send him a note or wait to see if he sees this thread.
 
Hi, thanks for the reply.

Its a fair point, I should have said, once I have the ajax side working, the script will be saving the input to a database :)
 
But that might still put a lot of overhead on your server if each time somebody types something the database has to be updated. I don't know the details of your application but you might want to have a button which will save the data only when the user is ready to save it.

What exactly does your input field look like? Are you using the onChange event? Maybe the onkeydown event would work instead:

http://www.w3schools.com/jsref/jsref_onkeydown.asp

Since my javascript skills aren't very advanced sorry if I'm just guessing here.
 
Link:

The reason your text is changing only when the user clicks out of the box is because you are firing your event when the state changes.

The best solution is to add a button to your page that when pressed, executes the code (change the text, read/write to database). If you are just looking to change something on the page, I suggest just sticking to javascript and using an onclick event handler.

The onchange event handler doesn't really work like you'd think. It does not fire as you type text into a box, but only once you're done typing and then change the focus to something else.
 
onChange is suppose to work the way you described where by it'll fire only when the user has finished changing the data in the input field. I think you might want to try onKeyDown or onKeyUp instead. You may even have to use both of them together.
 
Thanks for all the replys guys. Following what you have all said, I have realised that what I actually want to do is fire a javascript on each "onKeyDown" that looks to see if the page has been update in the last, say, 5 seconds, and if not, call the page update script. The idea being that once a user has finished typing, the script will update the box.

To make it clearer, the idea is that there will be several texts fields in the form, and as each is updated, the new entry will be saved into a php session vaiable, then when the form is "submitted", that session data will be saved to the database.

The reason I want to do this that way is because the form is going to be aimed at very "newbie" type users, so I want to ensure that the various bits of the form are valid and verified before the user even clicks submit. I'm aiming at ultimate simplicity for the end user here.

Thinking about it now, I'm not sure the best way to achieve this. Will have to see what I can come up with when I get back to my coding PC.

Cheers for all the advice guys.
 
Be careful... you don't want to have an ajax call firing off every time the user hits a key.

I would do a setTimeout on the onKeyUp event that will trigger the update after 500-1000ms or so, and use a clearTimeout on the onKeyDown event to cancel the timeout.

Also, http://stackoverflow.com is a great place to ask programming questions.
 
Perfect, thats exactly what I need :)

Thanks for the link as well, I'm sure it'll come in handy.
 
Be careful... you don't want to have an ajax call firing off every time the user hits a key.

I would do a setTimeout on the onKeyUp event that will trigger the update after 500-1000ms or so, and use a clearTimeout on the onKeyDown event to cancel the timeout.

Also, http://stackoverflow.com is a great place to ask programming questions.

Was about to recommend Stackoverflow. <3 <3 it, bestest site on the web.

OT:

If you're listening to an onChange event: that event is not fired until the element loses focus. Hence your problem, I suppose.

While it's commendable that you're trying to learn the basics of Ajax requests, in reality, absolutely no one does it like this. There's a lot of libraries for this without this hassle, that work across all browsers without headaches, of which the most popular being jQuery.

Your code with jQuery would be something like this:

Code:
$('#textfield').change(function(){
  $('#yearshowupdate').load('page.php', { q: this.value });
});

And frankly, I don't think it's really needed to know the basics in this case. I honestly wouldn't be able to reproduce your code, I've never done it like that. Manually doing an Ajax request? Wouldn't know the precise details on how to do it.

The most important thing is to know that an Ajax request is an asynchronous request to a server, the rest are just implementation details, like in your code.

You're using a scripting language to approach problems from a high level, not to fiddle around with low level stuff like this. I think it's much more important to spend your time on learning the Javascript language, which is full with cool and (at first) mind-bending stuff. Dynamic typing, functions as first class objects, functional style programming, all very valuable to know and to be honest: best taught by using libraries.

And learning to use libraries like jQuery is also valuable in the sense that they come with their own style of programming (as shown above) which is probably nothing like you've done before, and I think that's more valuable than the low level stuff. Don't reinvent the wheel, but build a racecar with the wheels that are provided ;)

Not to say you should stop with what you're doing, continue if you think it's helpful by all means! I'm not telling you to be lazy and just use what others have written, I'm saying to shift your attention to a higher level.
 
Indeed. Using a javascript framework like jQuery (there are others, like prototype, dojo, mootools, etc... but I've only used jQuery) makes writing javascript actually fun, and generally abstracts over the cross-browser intricacies you'd inevitably have to figure out.

HOWEVER.

As a developer, I like to, as much as possible, understand what the code I'm writing is actually doing. If what you're doing now is just for fun or learning, I'd encourage you to solider on without the framework for a bit so you understand what it actually does.
 
I was going to suggest dreamthrall, but here he is!
 
Back
Top