0

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! :)

3 Answers 3

3

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) }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your function should be like:

function geturl(addr) {    
 $.ajax({
  type: 'GET',
  url: addr,
  async: false,
  success:function(response) {
   return response;
  };
 });    
}

Comments

0
  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..

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.