Reputation: 229
My response text has html tags which causes ERROR to fire instead of SUCCESS. What am I doing wrong?
Here's my html code:
<head>
<title>HTML Window</title>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function post() {
var email = document.getElementById("email");
var password = document.getElementById("password");
var data = {
email: email.value,
password: password.value
};
$.ajax({
type: "GET",
url: "http://localhost/ParentChild/index.php",
dataType: "json",
data: data,
success: function (response) {
console.log("SUCCESS");
console.log(response);
},
error: function (response, textStatus, errorThrown) {
console.log("ERROR");
console.log("Status: " + textStatus);
console.log(response.responseText);
}
});
}
</script>
</head>
<body>
<form method="GET" action="javascript:post();">
<div>
Parent Window
<br><label for="email">Email: <input type="text" id="email" name="email"></label>
<br><label for="password">Password: <input type="text" id="password" name="password"></label>
<br><input type="submit" value="Post">
</div>
</form>
</body>
Here's my php:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$response = array(
"a" => "test");
echo (json_encode($response);
?>
</body>
</html>
And here is the console message:
ERROR
(index):28 Status: parsererror
(index):29 errorThrown: SyntaxError: Unexpected token < in JSON at position 0
(index):30 <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{"a":"test"} </body>
If I remove dataType: "json", I SUCCESS fires but the html tags are still part of the response text.
What am I doing wrong?
Upvotes: 2
Views: 2090
Reputation: 94672
Your PHP script that return data to the ajax call should be treated pretty much like a subroutine and not a web page. If you have HTML in that script, it will also be sent back to the browser as part of the total response.
So amend the script to this i.e. remove all the HTML you had in it
<?php
$response = array("a" => "test");
echo (json_encode($response);
?>
Upvotes: 1