Why does the XHR succeed and show in chromeDevTools but is undefined and cant be parsed by JSON.parse()











up vote
1
down vote

favorite












here's the script:



  function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
})
}).then((data) => {
data = JSON.parse(data)
console.log("data for table is", data)
$("#requestTable").html(data);
})
}


What is returned from "getRequests.php" is markup in JSON.
Just for Reference, I'll post the backend code so you can look up what is put into the response. "$result" is what is returned at the end of the php.






<?php
/*
================================================================================
Wennn diese Datei aufgerufen wird und der Wert "ID" als Int übergeben wurde wird
eine Tabelle, die alle Anfragen anzeigt, zurückgegeben.
================================================================================
*/
if(isset($_POST["ID"])){
try{
$connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
'verwalter','N7pY1OTl2gaBbc51');
}catch(PDOException $e){
echo $e->getMessage();
}
session_start();

$userRole = $connection->query("
SELECT name
FROM rolle
WHERE id = (
SELECT rolle
FROM benutzer_rollen
WHERE benutzer='".$_POST["ID"]."'
)
")->fetchAll()[0][0];
if($userRole == "admin"){


$result .= "<thead><tr><td>Von</td><td>Bis</td><td>Benutzer</td><td>Raum/Platz
</td><td>Aktionen</td></tr></thead><tbody>";

$allReservation = $connection->query("
SELECT id, anfang, ende, benutzer, arbeitsplatz
FROM reservierung
WHERE status='angefragt'
")->fetchAll();
foreach($allReservation as $row){
$user = $connection->query("
SELECT name, vorname
FROM benutzer
WHERE id='".$row["benutzer"]."'
")->fetchAll()[0];
$position = $connection->query("
SELECT raum, nummer
FROM arbeitsplatz
WHERE ID = '".$row["arbeitsplatz"]."'
")->fetchAll()[0];
$raumbild = $connection->query("
SELECT bild
FROM raum
WHERE name ='".$position["raum"]."'
")->fetchAll()[0][0];


$result .= "<tr><td>".date("d.m.y",strtotime($row["anfang"]))."</td><td>"
.date("d.m.y",strtotime($row["ende"]))."</td><td>".$user["name"]." "
.$user["vorname"]."</td><td><a>".$position["raum"]."/"
.$position["nummer"]."<div><img class="hoverImage"src="".$raumbild.
"" /></div></a></td><td><div class="form-inline form-horizontal">
<select id="statusDrop".$row["id"]."" class="form-control">
<option>genehmigen</option><option>ablehnen</option></select>
<button class='btn btn-default' onclick="submitStatus(".$row["id"].
");">Ok</button></div></td></tr>";
}
$result .= "</tbody></table>";
echo json_encode($result);
}
}


?>





In the chromeDevTools, the response is displayed correctly as HTML elements ("" and the like). However, when I try to output the results via console.log I get "undefined". When I try to parse it with "JSON.parse()" it gives me a syntax error saying that there was an "unexepected expression at line 1 column 1" of the data.



I don't understand this, especially since I used the very same script code before in other parts of the site. There, this problem never appeared.










share|improve this question









New contributor




JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 3




    Why encoding in JSON something that is just a string and not an object/array?
    – Cid
    Nov 8 at 9:24






  • 1




    It's because you're not returning valid JSON. First console.log(data) in your then handler to see exactly what you are returning. It seems like you can just return the HTML and be done.
    – Rory McCrossan
    Nov 8 at 9:27












  • @RoryMcCrossan I already tried logging just the string without parsing, but then it says undefined. Also, when the markup is injected into the respective element (see last bit of code), no table appears.
    – JSONBUG123
    Nov 8 at 9:32










  • I also tried echoing without "json_encode", plus removing the JSON.parse() on the script. Didn't really change much, although in the devtools a few more results show up so "json_encode" wasn't the best idea here.
    – JSONBUG123
    Nov 8 at 9:35















up vote
1
down vote

favorite












here's the script:



  function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
})
}).then((data) => {
data = JSON.parse(data)
console.log("data for table is", data)
$("#requestTable").html(data);
})
}


What is returned from "getRequests.php" is markup in JSON.
Just for Reference, I'll post the backend code so you can look up what is put into the response. "$result" is what is returned at the end of the php.






<?php
/*
================================================================================
Wennn diese Datei aufgerufen wird und der Wert "ID" als Int übergeben wurde wird
eine Tabelle, die alle Anfragen anzeigt, zurückgegeben.
================================================================================
*/
if(isset($_POST["ID"])){
try{
$connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
'verwalter','N7pY1OTl2gaBbc51');
}catch(PDOException $e){
echo $e->getMessage();
}
session_start();

$userRole = $connection->query("
SELECT name
FROM rolle
WHERE id = (
SELECT rolle
FROM benutzer_rollen
WHERE benutzer='".$_POST["ID"]."'
)
")->fetchAll()[0][0];
if($userRole == "admin"){


$result .= "<thead><tr><td>Von</td><td>Bis</td><td>Benutzer</td><td>Raum/Platz
</td><td>Aktionen</td></tr></thead><tbody>";

$allReservation = $connection->query("
SELECT id, anfang, ende, benutzer, arbeitsplatz
FROM reservierung
WHERE status='angefragt'
")->fetchAll();
foreach($allReservation as $row){
$user = $connection->query("
SELECT name, vorname
FROM benutzer
WHERE id='".$row["benutzer"]."'
")->fetchAll()[0];
$position = $connection->query("
SELECT raum, nummer
FROM arbeitsplatz
WHERE ID = '".$row["arbeitsplatz"]."'
")->fetchAll()[0];
$raumbild = $connection->query("
SELECT bild
FROM raum
WHERE name ='".$position["raum"]."'
")->fetchAll()[0][0];


$result .= "<tr><td>".date("d.m.y",strtotime($row["anfang"]))."</td><td>"
.date("d.m.y",strtotime($row["ende"]))."</td><td>".$user["name"]." "
.$user["vorname"]."</td><td><a>".$position["raum"]."/"
.$position["nummer"]."<div><img class="hoverImage"src="".$raumbild.
"" /></div></a></td><td><div class="form-inline form-horizontal">
<select id="statusDrop".$row["id"]."" class="form-control">
<option>genehmigen</option><option>ablehnen</option></select>
<button class='btn btn-default' onclick="submitStatus(".$row["id"].
");">Ok</button></div></td></tr>";
}
$result .= "</tbody></table>";
echo json_encode($result);
}
}


?>





In the chromeDevTools, the response is displayed correctly as HTML elements ("" and the like). However, when I try to output the results via console.log I get "undefined". When I try to parse it with "JSON.parse()" it gives me a syntax error saying that there was an "unexepected expression at line 1 column 1" of the data.



I don't understand this, especially since I used the very same script code before in other parts of the site. There, this problem never appeared.










share|improve this question









New contributor




JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 3




    Why encoding in JSON something that is just a string and not an object/array?
    – Cid
    Nov 8 at 9:24






  • 1




    It's because you're not returning valid JSON. First console.log(data) in your then handler to see exactly what you are returning. It seems like you can just return the HTML and be done.
    – Rory McCrossan
    Nov 8 at 9:27












  • @RoryMcCrossan I already tried logging just the string without parsing, but then it says undefined. Also, when the markup is injected into the respective element (see last bit of code), no table appears.
    – JSONBUG123
    Nov 8 at 9:32










  • I also tried echoing without "json_encode", plus removing the JSON.parse() on the script. Didn't really change much, although in the devtools a few more results show up so "json_encode" wasn't the best idea here.
    – JSONBUG123
    Nov 8 at 9:35













up vote
1
down vote

favorite









up vote
1
down vote

favorite











here's the script:



  function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
})
}).then((data) => {
data = JSON.parse(data)
console.log("data for table is", data)
$("#requestTable").html(data);
})
}


What is returned from "getRequests.php" is markup in JSON.
Just for Reference, I'll post the backend code so you can look up what is put into the response. "$result" is what is returned at the end of the php.






<?php
/*
================================================================================
Wennn diese Datei aufgerufen wird und der Wert "ID" als Int übergeben wurde wird
eine Tabelle, die alle Anfragen anzeigt, zurückgegeben.
================================================================================
*/
if(isset($_POST["ID"])){
try{
$connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
'verwalter','N7pY1OTl2gaBbc51');
}catch(PDOException $e){
echo $e->getMessage();
}
session_start();

$userRole = $connection->query("
SELECT name
FROM rolle
WHERE id = (
SELECT rolle
FROM benutzer_rollen
WHERE benutzer='".$_POST["ID"]."'
)
")->fetchAll()[0][0];
if($userRole == "admin"){


$result .= "<thead><tr><td>Von</td><td>Bis</td><td>Benutzer</td><td>Raum/Platz
</td><td>Aktionen</td></tr></thead><tbody>";

$allReservation = $connection->query("
SELECT id, anfang, ende, benutzer, arbeitsplatz
FROM reservierung
WHERE status='angefragt'
")->fetchAll();
foreach($allReservation as $row){
$user = $connection->query("
SELECT name, vorname
FROM benutzer
WHERE id='".$row["benutzer"]."'
")->fetchAll()[0];
$position = $connection->query("
SELECT raum, nummer
FROM arbeitsplatz
WHERE ID = '".$row["arbeitsplatz"]."'
")->fetchAll()[0];
$raumbild = $connection->query("
SELECT bild
FROM raum
WHERE name ='".$position["raum"]."'
")->fetchAll()[0][0];


$result .= "<tr><td>".date("d.m.y",strtotime($row["anfang"]))."</td><td>"
.date("d.m.y",strtotime($row["ende"]))."</td><td>".$user["name"]." "
.$user["vorname"]."</td><td><a>".$position["raum"]."/"
.$position["nummer"]."<div><img class="hoverImage"src="".$raumbild.
"" /></div></a></td><td><div class="form-inline form-horizontal">
<select id="statusDrop".$row["id"]."" class="form-control">
<option>genehmigen</option><option>ablehnen</option></select>
<button class='btn btn-default' onclick="submitStatus(".$row["id"].
");">Ok</button></div></td></tr>";
}
$result .= "</tbody></table>";
echo json_encode($result);
}
}


?>





In the chromeDevTools, the response is displayed correctly as HTML elements ("" and the like). However, when I try to output the results via console.log I get "undefined". When I try to parse it with "JSON.parse()" it gives me a syntax error saying that there was an "unexepected expression at line 1 column 1" of the data.



I don't understand this, especially since I used the very same script code before in other parts of the site. There, this problem never appeared.










share|improve this question









New contributor




JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











here's the script:



  function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
})
}).then((data) => {
data = JSON.parse(data)
console.log("data for table is", data)
$("#requestTable").html(data);
})
}


What is returned from "getRequests.php" is markup in JSON.
Just for Reference, I'll post the backend code so you can look up what is put into the response. "$result" is what is returned at the end of the php.






<?php
/*
================================================================================
Wennn diese Datei aufgerufen wird und der Wert "ID" als Int übergeben wurde wird
eine Tabelle, die alle Anfragen anzeigt, zurückgegeben.
================================================================================
*/
if(isset($_POST["ID"])){
try{
$connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
'verwalter','N7pY1OTl2gaBbc51');
}catch(PDOException $e){
echo $e->getMessage();
}
session_start();

$userRole = $connection->query("
SELECT name
FROM rolle
WHERE id = (
SELECT rolle
FROM benutzer_rollen
WHERE benutzer='".$_POST["ID"]."'
)
")->fetchAll()[0][0];
if($userRole == "admin"){


$result .= "<thead><tr><td>Von</td><td>Bis</td><td>Benutzer</td><td>Raum/Platz
</td><td>Aktionen</td></tr></thead><tbody>";

$allReservation = $connection->query("
SELECT id, anfang, ende, benutzer, arbeitsplatz
FROM reservierung
WHERE status='angefragt'
")->fetchAll();
foreach($allReservation as $row){
$user = $connection->query("
SELECT name, vorname
FROM benutzer
WHERE id='".$row["benutzer"]."'
")->fetchAll()[0];
$position = $connection->query("
SELECT raum, nummer
FROM arbeitsplatz
WHERE ID = '".$row["arbeitsplatz"]."'
")->fetchAll()[0];
$raumbild = $connection->query("
SELECT bild
FROM raum
WHERE name ='".$position["raum"]."'
")->fetchAll()[0][0];


$result .= "<tr><td>".date("d.m.y",strtotime($row["anfang"]))."</td><td>"
.date("d.m.y",strtotime($row["ende"]))."</td><td>".$user["name"]." "
.$user["vorname"]."</td><td><a>".$position["raum"]."/"
.$position["nummer"]."<div><img class="hoverImage"src="".$raumbild.
"" /></div></a></td><td><div class="form-inline form-horizontal">
<select id="statusDrop".$row["id"]."" class="form-control">
<option>genehmigen</option><option>ablehnen</option></select>
<button class='btn btn-default' onclick="submitStatus(".$row["id"].
");">Ok</button></div></td></tr>";
}
$result .= "</tbody></table>";
echo json_encode($result);
}
}


?>





In the chromeDevTools, the response is displayed correctly as HTML elements ("" and the like). However, when I try to output the results via console.log I get "undefined". When I try to parse it with "JSON.parse()" it gives me a syntax error saying that there was an "unexepected expression at line 1 column 1" of the data.



I don't understand this, especially since I used the very same script code before in other parts of the site. There, this problem never appeared.






<?php
/*
================================================================================
Wennn diese Datei aufgerufen wird und der Wert "ID" als Int übergeben wurde wird
eine Tabelle, die alle Anfragen anzeigt, zurückgegeben.
================================================================================
*/
if(isset($_POST["ID"])){
try{
$connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
'verwalter','N7pY1OTl2gaBbc51');
}catch(PDOException $e){
echo $e->getMessage();
}
session_start();

$userRole = $connection->query("
SELECT name
FROM rolle
WHERE id = (
SELECT rolle
FROM benutzer_rollen
WHERE benutzer='".$_POST["ID"]."'
)
")->fetchAll()[0][0];
if($userRole == "admin"){


$result .= "<thead><tr><td>Von</td><td>Bis</td><td>Benutzer</td><td>Raum/Platz
</td><td>Aktionen</td></tr></thead><tbody>";

$allReservation = $connection->query("
SELECT id, anfang, ende, benutzer, arbeitsplatz
FROM reservierung
WHERE status='angefragt'
")->fetchAll();
foreach($allReservation as $row){
$user = $connection->query("
SELECT name, vorname
FROM benutzer
WHERE id='".$row["benutzer"]."'
")->fetchAll()[0];
$position = $connection->query("
SELECT raum, nummer
FROM arbeitsplatz
WHERE ID = '".$row["arbeitsplatz"]."'
")->fetchAll()[0];
$raumbild = $connection->query("
SELECT bild
FROM raum
WHERE name ='".$position["raum"]."'
")->fetchAll()[0][0];


$result .= "<tr><td>".date("d.m.y",strtotime($row["anfang"]))."</td><td>"
.date("d.m.y",strtotime($row["ende"]))."</td><td>".$user["name"]." "
.$user["vorname"]."</td><td><a>".$position["raum"]."/"
.$position["nummer"]."<div><img class="hoverImage"src="".$raumbild.
"" /></div></a></td><td><div class="form-inline form-horizontal">
<select id="statusDrop".$row["id"]."" class="form-control">
<option>genehmigen</option><option>ablehnen</option></select>
<button class='btn btn-default' onclick="submitStatus(".$row["id"].
");">Ok</button></div></td></tr>";
}
$result .= "</tbody></table>";
echo json_encode($result);
}
}


?>





<?php
/*
================================================================================
Wennn diese Datei aufgerufen wird und der Wert "ID" als Int übergeben wurde wird
eine Tabelle, die alle Anfragen anzeigt, zurückgegeben.
================================================================================
*/
if(isset($_POST["ID"])){
try{
$connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
'verwalter','N7pY1OTl2gaBbc51');
}catch(PDOException $e){
echo $e->getMessage();
}
session_start();

$userRole = $connection->query("
SELECT name
FROM rolle
WHERE id = (
SELECT rolle
FROM benutzer_rollen
WHERE benutzer='".$_POST["ID"]."'
)
")->fetchAll()[0][0];
if($userRole == "admin"){


$result .= "<thead><tr><td>Von</td><td>Bis</td><td>Benutzer</td><td>Raum/Platz
</td><td>Aktionen</td></tr></thead><tbody>";

$allReservation = $connection->query("
SELECT id, anfang, ende, benutzer, arbeitsplatz
FROM reservierung
WHERE status='angefragt'
")->fetchAll();
foreach($allReservation as $row){
$user = $connection->query("
SELECT name, vorname
FROM benutzer
WHERE id='".$row["benutzer"]."'
")->fetchAll()[0];
$position = $connection->query("
SELECT raum, nummer
FROM arbeitsplatz
WHERE ID = '".$row["arbeitsplatz"]."'
")->fetchAll()[0];
$raumbild = $connection->query("
SELECT bild
FROM raum
WHERE name ='".$position["raum"]."'
")->fetchAll()[0][0];


$result .= "<tr><td>".date("d.m.y",strtotime($row["anfang"]))."</td><td>"
.date("d.m.y",strtotime($row["ende"]))."</td><td>".$user["name"]." "
.$user["vorname"]."</td><td><a>".$position["raum"]."/"
.$position["nummer"]."<div><img class="hoverImage"src="".$raumbild.
"" /></div></a></td><td><div class="form-inline form-horizontal">
<select id="statusDrop".$row["id"]."" class="form-control">
<option>genehmigen</option><option>ablehnen</option></select>
<button class='btn btn-default' onclick="submitStatus(".$row["id"].
");">Ok</button></div></td></tr>";
}
$result .= "</tbody></table>";
echo json_encode($result);
}
}


?>






javascript php jquery json ajax






share|improve this question









New contributor




JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Nov 8 at 10:07









ADyson

21.5k112441




21.5k112441






New contributor




JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Nov 8 at 9:20









JSONBUG123

63




63




New contributor




JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






JSONBUG123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 3




    Why encoding in JSON something that is just a string and not an object/array?
    – Cid
    Nov 8 at 9:24






  • 1




    It's because you're not returning valid JSON. First console.log(data) in your then handler to see exactly what you are returning. It seems like you can just return the HTML and be done.
    – Rory McCrossan
    Nov 8 at 9:27












  • @RoryMcCrossan I already tried logging just the string without parsing, but then it says undefined. Also, when the markup is injected into the respective element (see last bit of code), no table appears.
    – JSONBUG123
    Nov 8 at 9:32










  • I also tried echoing without "json_encode", plus removing the JSON.parse() on the script. Didn't really change much, although in the devtools a few more results show up so "json_encode" wasn't the best idea here.
    – JSONBUG123
    Nov 8 at 9:35














  • 3




    Why encoding in JSON something that is just a string and not an object/array?
    – Cid
    Nov 8 at 9:24






  • 1




    It's because you're not returning valid JSON. First console.log(data) in your then handler to see exactly what you are returning. It seems like you can just return the HTML and be done.
    – Rory McCrossan
    Nov 8 at 9:27












  • @RoryMcCrossan I already tried logging just the string without parsing, but then it says undefined. Also, when the markup is injected into the respective element (see last bit of code), no table appears.
    – JSONBUG123
    Nov 8 at 9:32










  • I also tried echoing without "json_encode", plus removing the JSON.parse() on the script. Didn't really change much, although in the devtools a few more results show up so "json_encode" wasn't the best idea here.
    – JSONBUG123
    Nov 8 at 9:35








3




3




Why encoding in JSON something that is just a string and not an object/array?
– Cid
Nov 8 at 9:24




Why encoding in JSON something that is just a string and not an object/array?
– Cid
Nov 8 at 9:24




1




1




It's because you're not returning valid JSON. First console.log(data) in your then handler to see exactly what you are returning. It seems like you can just return the HTML and be done.
– Rory McCrossan
Nov 8 at 9:27






It's because you're not returning valid JSON. First console.log(data) in your then handler to see exactly what you are returning. It seems like you can just return the HTML and be done.
– Rory McCrossan
Nov 8 at 9:27














@RoryMcCrossan I already tried logging just the string without parsing, but then it says undefined. Also, when the markup is injected into the respective element (see last bit of code), no table appears.
– JSONBUG123
Nov 8 at 9:32




@RoryMcCrossan I already tried logging just the string without parsing, but then it says undefined. Also, when the markup is injected into the respective element (see last bit of code), no table appears.
– JSONBUG123
Nov 8 at 9:32












I also tried echoing without "json_encode", plus removing the JSON.parse() on the script. Didn't really change much, although in the devtools a few more results show up so "json_encode" wasn't the best idea here.
– JSONBUG123
Nov 8 at 9:35




I also tried echoing without "json_encode", plus removing the JSON.parse() on the script. Didn't really change much, although in the devtools a few more results show up so "json_encode" wasn't the best idea here.
– JSONBUG123
Nov 8 at 9:35












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










I think you get undefined for data in the .then((data) => {
data = JSON.parse(data)
block because this "then" is attached to the call to getLoggedUser, not getRequests. So it receives a different response (and also probably executes before getRequests has completed).



So you need to do two things



1) Attach your callback to the correct AJAX call



2) stop trying to use JSON to try and wrap around HTML. What you're passing to json_encode() isn't JSON, and there's no need for it to be - just return the HTML as a string and append it directly to your HTML.



JS:



function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
}).then((data) => {
console.log("data for table is", data)
$("#requestTable").html(data);
})
})
}


PHP:



Simply replace



echo json_encode($result);


with



echo $result;





share|improve this answer





















  • Thanks, that was it! :=)
    – JSONBUG123
    Nov 8 at 10:10











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






JSONBUG123 is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53204699%2fwhy-does-the-xhr-succeed-and-show-in-chromedevtools-but-is-undefined-and-cant-be%23new-answer', 'question_page');
}
);

Post as a guest
































1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote



accepted










I think you get undefined for data in the .then((data) => {
data = JSON.parse(data)
block because this "then" is attached to the call to getLoggedUser, not getRequests. So it receives a different response (and also probably executes before getRequests has completed).



So you need to do two things



1) Attach your callback to the correct AJAX call



2) stop trying to use JSON to try and wrap around HTML. What you're passing to json_encode() isn't JSON, and there's no need for it to be - just return the HTML as a string and append it directly to your HTML.



JS:



function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
}).then((data) => {
console.log("data for table is", data)
$("#requestTable").html(data);
})
})
}


PHP:



Simply replace



echo json_encode($result);


with



echo $result;





share|improve this answer





















  • Thanks, that was it! :=)
    – JSONBUG123
    Nov 8 at 10:10















up vote
0
down vote



accepted










I think you get undefined for data in the .then((data) => {
data = JSON.parse(data)
block because this "then" is attached to the call to getLoggedUser, not getRequests. So it receives a different response (and also probably executes before getRequests has completed).



So you need to do two things



1) Attach your callback to the correct AJAX call



2) stop trying to use JSON to try and wrap around HTML. What you're passing to json_encode() isn't JSON, and there's no need for it to be - just return the HTML as a string and append it directly to your HTML.



JS:



function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
}).then((data) => {
console.log("data for table is", data)
$("#requestTable").html(data);
})
})
}


PHP:



Simply replace



echo json_encode($result);


with



echo $result;





share|improve this answer





















  • Thanks, that was it! :=)
    – JSONBUG123
    Nov 8 at 10:10













up vote
0
down vote



accepted







up vote
0
down vote



accepted






I think you get undefined for data in the .then((data) => {
data = JSON.parse(data)
block because this "then" is attached to the call to getLoggedUser, not getRequests. So it receives a different response (and also probably executes before getRequests has completed).



So you need to do two things



1) Attach your callback to the correct AJAX call



2) stop trying to use JSON to try and wrap around HTML. What you're passing to json_encode() isn't JSON, and there's no need for it to be - just return the HTML as a string and append it directly to your HTML.



JS:



function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
}).then((data) => {
console.log("data for table is", data)
$("#requestTable").html(data);
})
})
}


PHP:



Simply replace



echo json_encode($result);


with



echo $result;





share|improve this answer












I think you get undefined for data in the .then((data) => {
data = JSON.parse(data)
block because this "then" is attached to the call to getLoggedUser, not getRequests. So it receives a different response (and also probably executes before getRequests has completed).



So you need to do two things



1) Attach your callback to the correct AJAX call



2) stop trying to use JSON to try and wrap around HTML. What you're passing to json_encode() isn't JSON, and there's no need for it to be - just return the HTML as a string and append it directly to your HTML.



JS:



function getReq(){
$.post('../include/getLoggedUser.php', {
//nothing to transmit
}).then((loggedUser) => {
$.post("../include/getRequests.php", {
ID:loggedUser
}).then((data) => {
console.log("data for table is", data)
$("#requestTable").html(data);
})
})
}


PHP:



Simply replace



echo json_encode($result);


with



echo $result;






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 8 at 10:05









ADyson

21.5k112441




21.5k112441












  • Thanks, that was it! :=)
    – JSONBUG123
    Nov 8 at 10:10


















  • Thanks, that was it! :=)
    – JSONBUG123
    Nov 8 at 10:10
















Thanks, that was it! :=)
– JSONBUG123
Nov 8 at 10:10




Thanks, that was it! :=)
– JSONBUG123
Nov 8 at 10:10










JSONBUG123 is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















JSONBUG123 is a new contributor. Be nice, and check out our Code of Conduct.













JSONBUG123 is a new contributor. Be nice, and check out our Code of Conduct.












JSONBUG123 is a new contributor. Be nice, and check out our Code of Conduct.















 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53204699%2fwhy-does-the-xhr-succeed-and-show-in-chromedevtools-but-is-undefined-and-cant-be%23new-answer', 'question_page');
}
);

Post as a guest




















































































Popular posts from this blog

鏡平學校

ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

Why https connections are so slow when debugging (stepping over) in Java?