tags:

views:

157

answers:

3

Hi,

So I have this text input in a form, and I want to update a div as the user types text in the text input.

 <p><label for="movie_name">Film: </label> <input type="text" name="movie_name" class="required" onkeydown="changediv2(this.value)" /></p>

 <p><div id="ajax_update"></div></p>

My js method:

function changediv2(str) {
$('#ajax_update').html(geturl('http://url/search/movie?query='+str));
}

If I type in a browser http://url/search/movie?query=someString, I get some html displayed. But when I call it via this ajax call, nothing happens...

My geturl method:

function geturl(addr) {
 var r = $.ajax({
  type: 'GET',
  url: addr,
  async: false
 }).responseText;
 return r;
}

I cannot see what is wrong in there...

Please help me! :)

A: 

Your function should be like:

function geturl(addr) {    
 $.ajax({
  type: 'GET',
  url: addr,
  async: false,
  success:function(response) {
   return response;
  };
 });    
}
Sarfraz
A: 
  1. I'd use the "keyup" event, otherwise you are always 1 character behind.
  2. Is the page you are requesting via Javascript on the same server? Because that's impossible unless you are using something like "jsonp", which is probably not the case.
  3. I'd use a timeout / cleartimout situation so you don't send requests too often.
  4. Synchronous requests lock the whole browser until it's finished, not sure if that's what you want / if that will work well together with typing..
CharlesLeaf
about 3. and 4., I noticed this, what is the work around?
Piero
3. Have a variable that you can access from multiple places, which contains the value from setTimeout. Clear that timeout every time you have a new key-hit, and then do a setTimeout with a function that actually sends the request. So functions setTimeout and clearTimeout.4. This one is easy, just read the other answers. Remove the async line from the code, and use a "success" function that will be called when the request is completed.
CharlesLeaf
Thanks, I'll work on that and will post my results here!
Piero
+1  A: 

Chances are, your function returns before the ajax response is received by the client. I would suggest getting rid of the async option and performing the inject within $.ajax's success callback, e.g.:

function changediv2(addr, str) {
    $.ajax({
      type: 'GET',
      url: addr + str,
      success: function(response) { $('#ajax_update').html(response) }
    });
}
karim79