I am trying to send an input text value "Username" to a php script which is giving a result. That result I want it back on the html page.
<input type="text" id="user" name="user" placeholder="Username">
<button type="button" id="fetchBtn">Click Me!</button>
<p id="txt"></p>
Javascript inside my website
<script>
let fetchBtn = document.getElementById('fetchBtn');
fetchBtn.addEventListener('click', buttonClickHandler);
function buttonClickHandler() {
// Instantiate an xhr object
var xhr = new XMLHttpRequest();
// What to do when response is ready
xhr.onreadystatechange = () => {
if(xhr.readyState === 4) {
if(xhr.status === 200) {
document.getElementById("txt").innerHTML =
xhr.responseText;
} else {
console.log('Error Code: ' + xhr.status);
console.log('Error Message: ' + xhr.statusText);
}
}
}
xhr.open('GET', 'data.php');
// Send the request
xhr.send();
}
</script>
Now I am trying to get the PHP variable $title back to HTML page after it's processed by the php script. I can't figure out how to display it properly
<?php
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$para = $_GET['user'];
$html = file_get_contents_curl("http://website.com/$para");
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
?>
Your not sending any data back, the XHR is GET in which case you'll have to query vars on the end of the url data.php?user='+user.value, better to use POST
and in your PHP user $user = $_GET['user'];
But not 100% what your asking but your code examples...