I am new to ‘PHP and JavaScript’. The other day, I was coding for asynchronous request and response. Working sometime with fetch()
, I thought of using the XMLHttpRequest()
. It was a bit of work, but then I entered the following code:
<script>
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/test/test.php', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status != 200){
console.log(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
document.getElementById("lull").innerHTML = xhr.response
}
};
xhr.send("url=wikipedia.org");
</script>
I tried whole night debugging why this is returning null
in its response. Then I stumbled upon this and casually changed the xhr.responseType = 'json';
to xhr.overrideMimeType("application/json");
and it worked! So, I am trying to understand how the two differs in their working? The mdn_website says responseType()
can be used to change the response type, and many other sources have used it!
The php
file that open is refrencing is just listening for url
key in the $_POST
array and is responding with the html web page using file_get_contents()
and encoding it using json_encode()
.
The php file required is:
<?php
if (isset($_POST['url'])){
header('Content-Type: application/json');
$data = [
"html" => file_get_contents('https://www.' . $_POST['url'])
];
echo json_encode($data);
}
And to add, it works completely fine when using fetch()
and even with XMLHttpRequest
when using Content-Type: text/html
.