php – AJAX request not returning items from the server in correct <divs>-ThrowExceptions

Exception or error:

I have an overlay which appears on screen when a user clicks on an image. When the image is clicked on, a post ajax request is executed and it should return the result of moduleID, moduleName and pageID into the <div id="result"> and it should also return content into the <div id="content"> However I get nothing at all?

modules.php:

<div class="grid-2 dashboardIcons module">
    <h3 class="fontAmaticH1">Critical Writing</h3>
        <a class="cursor module" onclick="toggleWindow(); getModuleData(4)"><img value="4" src="images/CriticalWriting.png">
        </a>
</div>

<div id="result"> <!-- Should be returning data from db here -->
</div>
<div id="content"> <!-- and here -->
</div>

moduleTestingAJAX.php:

<?php

require 'scripts/db.php';

$moduleID = $_POST['moduleID'];
$pageID = 1;

if(isset($_POST['moduleID']))
{


    //$stmt = $conn->prepare ("SELECT * FROM `module` WHERE moduleID = ?");
    $stmt = $conn->prepare ("SELECT `module`.`moduleID`, `module`.`moduleName`,`moduleContent`.`pageID`, `moduleContent`.`content` FROM `moduleContent` INNER JOIN `module` ON `module`.`moduleID` = `moduleContent`.`moduleID` WHERE `moduleContent`.`pageID` = ? AND `moduleContent`.`moduleID` = ? ");    
    $stmt->bind_param("ii", $pageID, $moduleID);
    $stmt->execute();
    $result = $stmt->get_result();
    $output = [];

    while($row = $result -> fetch_assoc()) {
        $output["result"] = $row['moduleID'].' '.$row['moduleName'].' '.$row['pageID'];

        $output["content"] = $row['content'];

    }

    echo json_encode($output);
}
 ?>
</div> 

script.js:

// When user clicks open a module, pass the moduleID through in an ajax request to get data from the db
function getModuleData(moduleID){
  console.log(moduleID);
  $.ajax({  
      url: "moduleTestingAJAX.php",  
      method: "post",   
      data: {moduleID:moduleID},
      success: function(data){  
            console.log(data);
            $('#result').html(data.result);    
            $('#content').html(data.content);    
      }  
  });
  console.log("test");
}

What is held in the table moduleContent
DB Data

After running console.log(data); in the ajax call I get this returned:
output

How to solve:

You’re not parsing the JSON you receive. When your PHP script echoes json_encode($output), you’re getting a JSON encoded string, which you then attempt to use as an object.

There are two options, either tell your AJAX request you’re expecting JSON by adding the dataType attribute:

$.ajax({  
      url: "moduleTestingAJAX.php",  
      method: "post",   
      data: {moduleID:moduleID},
      dataType: 'json', // <-- this line added
      success: function(data){
            $('#result').html(data.result);    
            $('#content').html(data.content);    
      }  
});

Or, you could manually parse the JSON inside your success function:

success: function(data){
    parsedData = JSON.parse(data);
    $('#result').html(parsedData.result);    
    $('#content').html(parsedData.content);    
}

I’d suggest the first option.

Leave a Reply

Your email address will not be published. Required fields are marked *