Reputation: 13
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.
Upvotes: 0
Views: 371
Reputation: 189
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();
Upvotes: 0
Reputation: 189
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>
Upvotes: -1
Reputation: 944455
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.
Upvotes: 2