There is no data being shown after making an ajax request in a php document

Exploring Data Display with PHP and Ajax

In an attempt to showcase data on a PHP page using ajax, I've set up a system where a request is sent via ajax to a separate PHP file. This secondary PHP file then connects to a MySQL database and retrieves the necessary data. The goal is for users to click a button and have the retrieved data displayed on the same page without the need for a full page refresh.

Detailed Content of Files Used:

displaydata.php

  • This page is visible to the client and presents the fetched data.

getData.php

  • This script facilitates the connection to the MySQL database and retrieval of data.

app.js

  • This file is responsible for making the ajax request.

The Challenge Faced:

Upon testing the existing code, the issue arises when clicking the button intended to trigger the ajax request results in a page reload without displaying any data.

Using Inspect Element, I observed that the requests are successfully sent with a status 200 (OK). Additionally, I placed console.log("app.js found") at the beginning of the app.js file to verify it's being read, which does display in the console; however, other console.log() statements within the function fail to appear.

Code Snippets:

app.js

function init() {
  document.getElementById("Submit").addEventListener('click', ajax);
}

function ajax() {
  console.log("Function started");
  request = new XMLHttpRequest();
  request.open('GET', 'getData.php', true);
  request.onload = function() {
    console.log(request);
    if (request.status >= 200 && request.status < 400){
      // Success!
      document.getElementById("displayData").innerHTML = request.responseText;
    } else {
      // Error handling
    }
  };

  request.onerror = function() {
    // Connection error
  };
  request.send();
  console.log("Request sent");
}
document.addEventListener('load', init);

displaydata.php

<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="app.js"></script>
  </head>
 <body>
   <p class='title'>Presenting udp packet data</p><hr />
   <center><div class='data-window'>
   <form id="getSearchNumber">
     <label for="imei">IMEI of desired devices</label> 
     <select name="imei" id="imei">
       <option value="Alldata">All Data</option>
       <option value="012981000298213">012981000298213</option>
     </select>
     <br />
     <button id="Submit">Submit</button>
   </form>
   <div id="displayData"></div>
 </body>
 </html>

I am confident in the functionality of getData.php. If you wish to review it, kindly leave a comment below.

The issue likely lies not in syntax errors but instead in the overall approach taken towards solving the problem.

Answer №1

Make sure to include jQuery on your webpage and alter the <button> element to <input type="button" as it will automatically submit the form when clicked.

<html>
      <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="style.css">
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="app.js"></script>
      </head>
     <body>
       <p class='title'>Displaying UDP Packet Data</p><hr />
       <center><div class='data-window'>
       <form id="getSearchNumber">
         <label for="imei">IMEI of desired devices</label> 
         <select name="imei" id="imei">
           <option value="Alldata">All Data</option>
           <option value="012981000298213">012981000298213</option>
         </select>
         <br />
         <input type="button" id="Submit" value="Submit"/>
       </form>
       <div id="displayData"></div>
     </body>
     </html>

Update your JavaScript code to:

$(document).ready(function(){
    $( "#Submit" ).click(function() {
        $( "#displayData" ).load( "getData.php" );
    });
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible in JavaScript to have three different input values contribute to a sum without using HTML event attributes?

I've been working my way through the 57 programming exercises book by Brian P. Hogan. For most of these exercises, I've been attempting to create a GUI. In this particular exercise, the goal is to calculate the Simple Interest on a Principal am ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

Difference between Vue 3.0 and the Breadcrumb error: Modifying the "items" property

I'm currently in the process of building a website with the vuesax theme and vue cli 3.0. Custom Default Layout: <template> <div class="main-wrapper"> <!---Navigation--> <Navbar :topbarCo ...

When a variable is brought into another JS file in Vite, it undergoes a transformation and

Currently, I am working on a vanilla JavaScript project using Vite and I have encountered an issue that I need help with: In my app.js file, I am initializing a variable using the let command and exporting it as follows: let activePoint = null; export { a ...

Effortless AJAX authentication verification

I am seeking assistance with a piece of code that I have been struggling with. I would appreciate it if someone could help me identify the mistake in my code. Any guidance or advice would be greatly appreciated. $('#username').change(functi ...

Error: Cannot serialize object of type Reporter to JSON format

I've been attempting to use AJAX to add a reporter, but I'm encountering issues. Sending JSON data with {'reporter':reporter.name} successfully creates the object in the database, however, it doesn't appear in the select option wit ...

"Keep an eye on the server with Backbone.js by running periodic checks

In an effort to keep my backbone application constantly checking the server for model updates, I aim to create a system similar to Twitter's auto-refresh feature for new tweets. Currently, I am connecting to an external application through their API ...

Exploring JSON Data with Mustache Templates

Dealing with a significantly large JSON object that I can't control, I'm struggling to output a list of records (related to people in this case) using Mustache.js. Despite simplifying the complex object into a more manageable one with just the ne ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

Instructions for developing an offset plugin for an HTML5 video player

I'm currently working on developing an offset plugin that allows playing a specific portion of a video in an HTML5 video player. While there is an existing plugin for video.js available at videojs-offset plugin, I am now experimenting to adapt this p ...

The luminosity of MeshBasicMaterial in Three.js

In my current setup with threejs, I am utilizing MeshBasicMaterial for lighting effects. Each element contains a simulated point light within. I have assigned a variable named color, defined as rgb(random value, random value, random value). I am looking ...

What is the correct way to write a for loop in Angular/JavaScript to initialize a form?

I am working on a form and I am trying to create a loop based on the size of my matches array: pronoPlayer0:['',Validators.required] pronoPlayer1:['',Validators.required] pronoPlayer2:['',Validators.required] I am unsure o ...

Convert a JavaScript array into an HTML table sorted by time

I am looking to convert an array into an HTML table sorted by time, including a rank and calculating the time loss for the first place. Here is an example of the array: let array = [ ["McNulty Oscar", "USA", "108:45.1"], ["Johansson Anton", "SWE", "87 ...

Creating a canvas with multiple label introductions can be achieved by following these

I am looking to group labels and sublabels on the x-axis of a canvas component. Currently, I only have sublabels like: RTI_0, RTI_1... I would like to add labels to these sublabels like: RTI = {RTI_0,RTI_1,RTI_2] BB = {BB_0, BB_1,BB_2,BB_3] <div cla ...

Tips on changing tabs by simply clicking the save button or linking the save button to tab-switching functionality

import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms'; import { CustomValidators } from 'ng2-validation'; import { Busi ...

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

Unfulfilled Peer Dependency in react

Encountering javascript issues with react. Chrome error message when rendering page: Uncaught TypeError: Super expression must either be null or a function, not undefined at _inherits (application.js:16301) at application.js:16310 at Object.232.prop-types ...

The comment received an error due to the undefined method `errors` for nil:NilClass

I have successfully implemented Ajax to create comments on my article show page. Now, I am trying to use Ajax to display errors for the comments as well. However, I am encountering the following error: undefined method `errors' for nil:NilClass Ev ...

Please restrict all scores to only one decimal point and ensure that all integer scores include a ".0" at the end, except for scores of 10 or 0

Ensure scores are rounded to a single decimal point and update all integer values with .0, except for 10 and 0. For example: 0.972 should be 0.9 2.83 should be 2.8 All integer scores will be updated as: 0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 I have ...

How can you use three.js to easily create a cylinder with a slice removed from it?

Can someone guide me on creating a 3D model of a cylinder with a slice cut out using three.js? Something similar to this: Image Your input is highly valued. Thank you. ...