javascript - AJAX request returns entire HTML page instead of just the data I wanted it to echo
Get the solution ↓↓↓I have:
Index.php
<?php
if(isset($_POST["id"])){
echo($_POST["id"]);
}
?>
JavaScript:
let xhttp = new XMLHttpRequest();
xhttp.open("POST", "index.php", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhttp.onreadystatechange = function (){
if(xhttp.readyState == 4 && xhttp.status == 200)
{
let result = xhttp.responseText;
console.log(result)
}
}
xhttp.send("id=195");
But the console prints the whole HTML code for the php page. I thought it should print just the ID.
Answer
Solution:
It sounds like you have other code in index.php, then?
If you only want it to print the ID, add anexit();
command just after it echoes the ID, so that the rest of the script is not processed in that situation. (That's assuming that the PHP code comes before the HTML in the file, of course.)
P.s. Most developers tend to separate the PHP which responds to Ajax requests from the PHP which deals with loading HTML pages. This
a) prevents the type of problem you're experiencing,
b) keeps the functionality clean and clear and separate, making unit testing a lot easier, and
c) takes a step to it being more like a fully-fledged API which just deals with data - and can potentially be called from other applications, services or front-ends too, if that's useful.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.