Ajax PHP call returns nothing

I am trying to make my first ajax example working on my MAMP. my ajax.html looks like this:

<html> <head> <script src='ajax.js'></script> </head> <body onload = 'ajax()'> <div id='test'></div> </body> </html> 

my ajax.js looks like this:

 function ajax ()
 {
 >> var xmlhttp; 
if (window.XMLHttpRequest) {// code for IE7 +, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest (); } else {// code for IE6, IE5
xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP"); } xmlhttp.open ("GET", "http: // localhost: 8888 / ajax.php", true); xmlhttp.send (); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById ("test"). innerHTML = xmlhttp.responseText; } } }

my ajax.php looks like this:

echo 'hello world';

I found the response header from firebug:

Answer Headers
Keep-Alive Connection
Content-Length 11
Content-Type text / html
Date Mon, 05 Nov 2012 18:57:46 GMT
Keep-Alive timeout = 5, max = 99
Server Apache / 2.2.22 (Unix) mod_ssl / 2.2.22 OpenSSL / 0.9.8r DAV / 2 PHP / 5.4.4
X-Pad avoids browser error
X-Powered-By PHP / 5.4.4

but nothing in the response text and nothing has changed in my html.

Can anybody help me?

Thanks!

+4
source share
1 answer

Your problem is that you are trying to execute a cross-domain request. The browser prevents this because of the same origin policy .

The standard solution is to set the CORS headers in your PHP to allow these requests.

For instance:

 <?php header("Access-Control-Allow-Origin: *"); ?> 
+12
source

Source: https://habr.com/ru/post/1444183/


All Articles