CORS: How cross domain call works in browsers?
Usage and working of CORS in browsers.
Assume that the ip.php file is hosted in
http://examplesite.com/ip.php. As you can see, ip.php takes a variable as an argument. So while creating an http request, we are sending the URL (of which we need to get ip) to the ip.php using a GET request. If you pass google.com as a URL, the request goes like this: http://examplesite.com/ip.php?domain=google.com. Now, lets get back to the main script. The statement var http = new XMLHttpRequest() will initiate a new request and store it in a variable named http.
onreadystatechange() stores a function (or the name of a function) to be called automatically, each time the readyState property changes. When the readyState is equal to 4 and status is 200, the cross domain call request gets back its response and it can be stored into a variable.
readyState equals to 4 means that the request is successfully completed (the ip.php function is correctly executed) and the response is ready.
While writing the
ip.php, I included 2 statements
header('Access-Control-Allow-Origin: *'); which is very necessary for this script to work. Here
Access-Control_Allow-Origin: * means that any domain can make a
cross domain call (althrough this should don’t be the case with real world applications) to this file. If you want to restrict it to limited number of sites, you can replace your domain name in the place of * . If this header is missing, you cannot make a cross domain call because by default, it will block all requests generating from external domain according to the same origin security policy.