0

i am using xmlhttpRequest to get data from database but it shows an error cross origin request are only supported for http. i tried "header('Access-Control-Allow-Origin: *');" in php but still it shows error. here is my html code

    <!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","devangpatel.host56.com/sample.php",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>

</body>
</html>

nd here is php

<?php
header('Access-Control-Allow-Origin: *');
$con=mysqli_connect("host","user","password","db");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM demo");

while($row = mysqli_fetch_array($result)) {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br>";
}

mysqli_close($con);
?>
3
  • To use cors the browser must send an origin http header. Check with your browser debugger if it has been sent (or in your php if it has been received) Jul 5, 2014 at 6:09
  • carlo can you elabrate how to check is it send or not,because in mozilla debugger it is showing the program which is written , nothing else Jul 5, 2014 at 6:15
  • Opening the Firefox or Chrome debugger (Shift+Ctrl+i) you should have a network section with each request made from the browser containing informations on headers, params, cookies and so on. Alternatively you can use in your PHP page the getallheaders that will retrieve an array with all headers. Check if you are using a Browser that supports Cors here: caniuse.com/#search=cors Jul 5, 2014 at 6:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.