You are viewing our Forum Archives. To view or take place in current topics click here.
[JS / PHP] AJAX response not showing
Posted:

[JS / PHP] AJAX response not showingPosted:

-Deano
  • Rated Awesome
Status: Offline
Joined: Aug 19, 201013Year Member
Posts: 5,238
Reputation Power: 532
Status: Offline
Joined: Aug 19, 201013Year Member
Posts: 5,238
Reputation Power: 532
I'm having a bit of an issue sending data between my server and client via AJAX for a uni project.

The page requests to load all reviews from my server which should be retrieved and then returned in JSON format.

I have tested the script by itself and it does return the JSON as seen in [ Register or Signin to view external links. ] . That is the echo from the server script.

When I log the value of e.target.responseText to console, it says that it is empty.
Obviously, when I try to parse the JSON, nothing happens because the value of 'response' is empty.

JavaScript

function reviewSearch() {
        $("#searchResults").html("");
        var xhr2 = new XMLHttpRequest();

        xhr2.addEventListener("load", (e) => {
          var response = JSON.parse(e.target.responseText);
         
          for (var i = 0; i < response.length; i++) {
            var text = `
            <div class="row mb-4">
              <div class="card">
                <img class="card-img-top" src="{$response[i].image_location}" alt="Card image cap">
                <div class="card-body">
                  <h3 class="card-title">{$response[i].title}</h3>
                  <div class="row">
                    <h5 class="col-md-8 text-left">{$response[i].component_name}</h5>
                    <h5 class="col-md-4 text-right">{$response[i].component_type}</h5>
                  </div>
                  <p class="card-text">{$response[i].message}</p>
                </div>
                <div class="card-footer">
                  <div class="row">
                    <p class="col-md-8 m-0 font-weight-bold">{$response[i].username}</p>
                    <small class="col-md-4 text-muted text-right">{$response[i].submission_date}</small>
                  </div>
                </div>
              </div>
            </div>
            `;
            $("#searchResults").append(text);
          }
         
        });
       
        var type = $("#reviewSearch").val();
        xhr2.open("GET", `./scripts/getReviews?type={$type}`);
        xhr2.send();
       
        console.log("Request sent");
      }



PHP

<?php

// Connect to the database
include( "./common.php" );
$conn = connect();

$type = $_GET["type"];
$sql = "SELECT id, username, submission_date, title, message, component_name, component_type, image_location FROM reviews";

try {

  if ( isset( $type ) ) {
    $sql .= " WHERE component_type LIKE ?"; // If the user wants a certain component type then add to the end of the SQL statement
    $stmt = $conn->prepare( $sql ); // Create prepared statement
    $type = "%" . $type . "%";
    $stmt->bindParam( 1, $type ); // Bind the parameter
  } else {
    $stmt = $conn->prepare( $sql ); // Create prepared statement
  }

  $stmt->execute(); // Store the result
  $results = $stmt->fetchAll( PDO::FETCH_ASSOC );
 
  echo json_encode( $results ); // Return the results in JSON format

  $conn = null; // Close connection to the DB
 
} catch ( PDOException $e ) {
  echo $e->getMessage();
}

?>



If anyone can see what mistake I've made, I would greatly appreciate it.
#2. Posted:
CriticaI
  • Summer 2023
Status: Offline
Joined: Nov 05, 201310Year Member
Posts: 2,737
Reputation Power: 448
Status: Offline
Joined: Nov 05, 201310Year Member
Posts: 2,737
Reputation Power: 448
I would recommend you use axios. I just recently completed a project for university as well.


//JS
axios.get('/endpoint.php').then(res => {
  console.log(res.data);
});

/*
returns {
  username: 'john',
  id: 123
}
*/



//PHP
function json ($data) {
  header('Content-Type: application/json');
  echo json_encode($data);
  exit();
}

$data = [
  "username" => "john",
  "id" = 123
];

json($data);


If you have to use ajax I believe you can do this.

//JS
$.get("/endpoint.php", function(data, status){
       console.log(data);
});


Also I use this chrome extension for debugging json responses. [ Register or Signin to view external links. ]
#3. Posted:
Cyimking
  • TTG Senior
Status: Offline
Joined: May 02, 201211Year Member
Posts: 1,129
Reputation Power: 34
Status: Offline
Joined: May 02, 201211Year Member
Posts: 1,129
Reputation Power: 34
Yea the easiest option is to switch to a JS framework like Vue Js or React JS.
#4. Posted:
-Deano
  • Spooky Poster
Status: Offline
Joined: Aug 19, 201013Year Member
Posts: 5,238
Reputation Power: 532
Status: Offline
Joined: Aug 19, 201013Year Member
Posts: 5,238
Reputation Power: 532
Appreciate the suggestions to use a framework but I stand by the firm belief that if you don't understand how to do it yourself, you shouldn't be using a framework.

You definitely should understand how to do something on your own before letting other frameworks do it for you otherwise you won't learn anything, in my opinion at least.

I have managed to solve the issue now. There was an issue with my string literals.
Jump to:
You are viewing our Forum Archives. To view or take place in current topics click here.