Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Send HTML data to PHP and post back the result to HTML page with ajax

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;
?>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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...

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!