0

How do i make an ajax get request like www.example.com/example.php?d=a in javascript? I've tried:

xmlhttp.open("GET","www.example.com/example.php?d=a",true);
xmlhttp.send();

Can someone provide me a working example? Thanks.

bob
  • 13
  • 1
  • 6

3 Answers3

2

Like that.

Although if you mean http://www. etc etc, then you do need to remember the http:// part of the URL.

Beware the same origin policy and see ways to work around it.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I don't know man, i just ran that script and i setup a .php file that will place the input placed in the d variable to a .txt file and i get no results. Got any other ideas? – bob Jul 24 '13 at 14:06
  • Look at the Net tab of your browser's developer tools. See exactly what HTTP requests are being made and what the responses are. – Quentin Jul 24 '13 at 14:12
  • You have to define `xmlhttp` first. `var xmlhttp = new XMLHttpRequest();` – Quentin Jul 24 '13 at 14:33
0

If you really want to use GET, here is the code:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","the_page_to_send_request_to.someFileFormat",true);
xmlhttp.send();
Fireworm
  • 189
  • 2
  • 2
  • 14
-1

Sure :)

This function will make a (POST) request with wahtever data you like (str), to wherever you like (phplocation). The xmlhttp.responseText is whatever the server sends back :)

<script type="text/javascript">
function submitForm(str, phpLocation)
{
  var xmlhttp;
  if (window.XMLHttpRequest)
    xmlhttp=new XMLHttpRequest();
  else
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

  xmlhttp.onreadystatechange=function()
  {
    if(xmlhttp.readyState<4)
    {
      //i'm not ready yet. Do stuff.....
    }
    if(xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      //Now I'm ready. Do stuff with this: xmlhttp.responseText;
    }
  }
  xmlhttp.open("POST", phpLocation, true);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  xmlhttp.send("str=" + encodeURIComponent(str));
}
</script>
Fireworm
  • 189
  • 2
  • 2
  • 14
  • Of course it doesn't work. You have to actually implement some actions on your page corresponding to want you want it to do - this should be done inside the two if's, instead of the comments. To start you off, try to just console.log(xmlhttp.responseText) in the last of them, and open your console (typically with F12). As for the GET, I thought I'd show you a POST example, as they are a bit more tricky, and I though you might want to learn something. – Fireworm Jul 24 '13 at 14:44