0

This has been bothering me for ages and I tried everything and I cannot get it to work.

Here is my function currently

   function example1() {
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET", url,true);
   xmlhttp.onreadystatechange=function() {
     if (xmlhttp.readyState==4) {
      data=(xmlhttp.responseText);
      }
     }
  xmlhttp.send(null);
 }

I would like to be able to get "data" out of that function that I can then in another function return some regex on AND I would like to be able to make "url" dependent on user input

I hope someone can help me, this is driving me extremely crazy.

Thanks for you time

Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62
jigh
  • 1
  • 1
  • 1

2 Answers2

0

Short answer: you need to change the third parameter, the async flag from

xmlhttp.open("GET", url, true) 

to

xmlhttp.open("GET", url, false)

A common mistake is to think this is a scoping problem since if you set debugging messages within the xmlhttp.onload = function() {...}, it works within the callback while nothing happens outside the callback.

It turns out this is actually a timing problem because if async is set to true (the default), the debugging messages outside of the onload callback run before the callback gets executed.

radical7
  • 8,957
  • 3
  • 24
  • 33
joeblog
  • 1,101
  • 11
  • 17
-1

XmlHttpRequest doesn't work across domain, so if a user, say, submits http://google.com, it won't work. However, if you want to get data from your own site, and have them input a url from your own site, then the HTML of url would be included in

xmlhttp.responseHtml;
codersarepeople
  • 1,971
  • 3
  • 20
  • 25
  • sorry that is not myy problem. "I would like to be able to get "data" out of that function that I can then in another function return some regrex on AND I would like to be able to make "url" dependent on user input" – jigh Aug 14 '10 at 23:58
  • Oh sorry about that. To get user input, lets say you have a var url, then change it to this: var data = example1(url); So instead of saying data=(xmlhttp.responseText); say return xmlhttp.responseText; – codersarepeople Aug 15 '10 at 02:32
  • I'm still having trouble. I have found another reason why I can't continue so I'm giving up on the whole idea (for now) Thanks anyway – jigh Aug 15 '10 at 04:05