Home > Back-end >  Why xmlhttprequest response is in html code
Why xmlhttprequest response is in html code

Time:02-20

For some reason when I am sending an http request using xmlhttp the answer that I'm getting is in a html form

function HttpRequest(method, url, username, password) {
    const xhr = new XMLHttpRequest();
    let received_data;
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responsejson);
            if (xhr.responseText == "access granted")
                console.log("ok");
            else
                console.log("error");
        }
    }
    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send('username='   username   '&password='   password);
    xhr.onload = function() {
        console.log("connected to "   url);
    }
 }

function send_data() {
    let method = 'POST';
    let url = 'https://localhost:83/android_app/server.php'; //url of the php 
server(must be https:// (secure) in order to make the connection using cordova app)
    let username = document.getElementById('username').value;
    let password = document.getElementById('password').value;
    HttpRequest(method, url, username, password)
   }

also the php server that I am sending this request it just that:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<?php

header('Access-Control-Allow-Origin: *');

$name = $_POST['username'];
$password = $_POST['password'];
if($name=="admin" && $password=="1234"){
    echo "access granted";
}
else{
    echo "access denit";
}


?>

</body>
</html>

this is the response that I am getting

enter image description here

CodePudding user response:

You can think of a function called via AJAX as if it were a subroutine. It should only return what the caller wants. Currently with all that HTML in there that is being sent back to the AJAX call as well as the access granted and therefore making what you want difficult to find.

So if you change the server.php code to

<?php

header('Access-Control-Allow-Origin: *');

$name = $_POST['username'];
$password = $_POST['password'];
if($name=="admin" && $password=="1234"){
    echo "access granted";
}else{
    echo "access denit";
}

The all you will get returned to the AJAX call is either access granted or access denit, which is what you are testing for in the javascript

  • Related