Having difficulties grasping the concept of how to communicate effectively with my MySQL database

Apologies in advance for asking a question that may have been answered elsewhere, but I've been struggling for hours to transfer the information into my own program. Despite my attempts, I always encounter the same obstacles. So, I decided it would be best to ask my own question.

The Task

I am currently working on a booking form where parents can sign their children out of school if they are absent. The goal is to streamline the process and reduce the burden on year group assistants who constantly handle phone calls about absences. By automating this task, they can focus on other important aspects of their role such as student relations.

To achieve this, I created an HTML form:

https://i.stack.imgur.com/9OD7R.png

Once the form is filled out and submitted, an object is generated:

class Teacher
{
    constructor(TeacherObject)
    {
        this.Tutor = TeacherObject.Tutor;
        this.YearGroup = TeacherObject.YearGroup;
        this.FullName = TeacherObject.FullName;
        this.ID = TeacherObject.ID;
    }
}

class Student
{
    constructor(Teacher, StudentName)
    {
        this.StudentForm = Teacher;
        this.StudentName = StudentName;
    }
}

class Request
{
    constructor(Student, Dates)
    {
        this.AbsentStudent = Student;
        this.AbsenceDates = Dates;
    }
}

A 'Request' object containing all necessary details is then supposed to be sent to MySQL to be saved in a database.

The Issue

As far as I know, PHP executes server-side and precedes any Javascript/jQuery/HTML code. If the code responsible for adding data to the database is written in PHP, wouldn't it run before the code creating the object for the database? Using include() or require_once() results in the PHP file running entirely before receiving any data input, which usually comes at the end of the program.

I came across AJAX, which seems like it can somehow delay the execution of the PHP code. Could someone explain how I could utilize AJAX if that's what I'm missing?

I have set up a function in the PHP file:

function addData($requestDataInJSONFormat)
{
    echo "Just testing....";
}

But if everything runs before the page finishes loading, how do I ensure that I can wait until I have the final student object to pass to the PHP function and add it to the database? This concept has left me perplexed!

Any guidance would be greatly appreciated, Jake

Answer №1

Initially, it appears that you have grasped your issue correctly – PHP is a server-side language, operated by the server to provide an HTML page to the browser.

This means that you can transfer a PHP variable to a JavaScript one like so:

...
var javascript_var = <?php echo $php_var; ?>;
...

Regarding your query, utilizing AJAX allows communication with the server without navigating to another page. When creating a simple PHP form, data is sent to a PHP file for backend operations such as saving it in the database.

AJAX facilitates similar functionality (transferring data to a PHP file or other destinations) without reloading the entire page, thanks to its asynchronous nature.

You need to create a PHP file to store data in the database and utilize AJAX to send information from the frontend to this file.

Remember, AJAX does not directly interact with the database but enables running PHP scripts without forcing users to navigate away from the current page.

I won't provide the code here as numerous tutorials are available online. You can begin by referring to this resource:

This tutorial closely aligns with what you seem to be aiming for based on my understanding.

Hoping this explanation clarifies things for you,

Best regards,

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

What exactly is a doclet as defined in JSDoc documentation?

//Sample 1 /** * Here we have a simple function that returns a message * @param {String} msg The message to be returned * @returns {String} The message */ function showMessage(msg) { return msg } //Sample 2 /** * This is a function that also retur ...

Incorporating a personalized image to create custom icons on the Material UI bottom navigation bar

Is it possible to replace the default icon with a custom image in material ui's BottomNavigation component? I'm curious if Material UI supports this feature. If you'd like to take a closer look, here is the link to the codesandbox. ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Capturing all response requests from the main process in Electron: A step-by-step guide

I am looking to retrieve the responses for all requests made in my electron app from the main process. In this image, it shows that the desired response can be found in the Response tab rather than the Headers tab on Chrome Dev Tools. Instead of using a ...

Encountering a 500 internal server error while accessing the web server

Anyone out there able to assist? My web service seems to be throwing an error. Receiving a 500 Internal Server Error and 304 Not Modified message The requested XML data is not displaying the body content as expected. var soapMessage ='<soap:E ...

Instructions on merging the firstName and lastName fields to display them in the Full name column within Sonata admin

I am attempting to display a column for Full name that combines the firstName and lastName properties from my entity. How should I go about this? Below is the Entity and Admin.php code snippets: class test{ private firstName; //other properties privat ...

To retrieve a CSV file on the frontend, simply click a button in an AngularJS application that communicates with NodeJS and ExpressJS

How can I download a .csv file from the frontend? This is the code I am currently using: $http.get('/entity/consultations/_/registerationReport' ) .success(function (data) { myWindow = window.open('../entity/consultations/_/r ...

Determine if the content within the YouTube iFrame has been updated

I currently have an iframe on my webpage that does not initially display a video. However, when the user clicks a button, a Youtube video will be loaded into the iframe. I am trying to detect when the video has finished loading by using the on() method t ...

What is the process to subscribe and obtain data from a server-to-user channel using pusher-js?

I am currently hosting my application using next.js on Vercel. I want to integrate Pusher to provide real-time messages to users in a private and secure manner. Despite successful log entries, I am facing challenges in subscribing to the channel and retrie ...

Issue with displaying the Bootstrap paginator stylingSomething seems to be

Currently, I am working on a PHP project that involves creating a table with Bootstrap styling. To achieve this, I referred to a tutorial which guided me through the process. After linking the necessary Bootstrap CSS file using the provided code snippet, ...

What is the process for transferring information from a Microsoft Teams personal tab to a Microsoft Teams bot?

Is it feasible to share data such as strings or JSON objects from custom tab browsers to a Teams bot's conversation without utilizing the Graph API by leveraging any SDK functionality? ...

Load images sequentially in a slideshow gallery using JQuery, showing the next five pictures at a time instead of loading all at once

Recently, I've been developing a slideshow for educational materials and images. However, a concern was raised by a colleague regarding the loading time of slideshows with over 50 images. Is there a way to optimize the loading process by only displayi ...

The 'string' Type in Typescript cannot be assigned to the specified type

Within the fruit.ts file, I've defined a custom type called Fruit which includes options like "Orange", "Apple", and "Banana" export type Fruit = "Orange" | "Apple" | "Banana" Now, in another TypeScript file, I am importing fruit.ts and trying to as ...

Having trouble retrieving data item with JQUERY's getJSON method

I am currently using a getJSON request in my code snippet: $.getJSON(url + "&callback=?", { postData: myText }, function(data) { alert('data : ' + data); }); During testing, I have an application running on "localhost:8080" where I ...

Assign the private members of the class to the arguments of the constructor

class Bar { #one #two #three #four #five #six #seven #eight #nine #ten #eleven #twelve #thirteen #fourteen #fifteen #sixteen constructor( one, two, three, four, five, six, seven, eight, ...

Searching for an array of IDs in Mongoose

I have created an API using Express.js and mongoose to find users based on their ids in an array. // Here is the array of user ids const followedIds = follow.map((f) => f.followed); console.log(followedIds); // This will log [ '5ebaf673991fc60204 ...

Python code allowing users to navigate back to the previous page while retaining elements

After my script scrapes the page, it automatically clicks a button if a new element meeting certain criteria is found. Everything works perfectly when there is only one element, but an issue arises when the button click leads to a new page opening. If ther ...

Is it possible to exclusively target a child div using JavaScript in CSS, without affecting the parent div?

I'm in the process of developing a calendar feature where users can select a specific "day" element to access a dropdown menu for time selection. The functionality is working fine, but I've encountered an issue. When a user selects a time from th ...

Issue: Attempting to access the `userName` property on an undefined object (`tem`), resulting in a TypeError while using flalist

A concern has arisen with the React Native Flatlist as it fails to render properly. What steps should be taken in this scenario? Below is the code snippet for reference: Image description available here import React, {useState, useEffect} from 'react ...

using database URL as an AJAX parameter

I am currently working on a Python CherryPy controller that needs to validate a database URL by attempting a connection. However, I am facing challenges with passing the parameter to the method. Below is my AJAX call: $.ajax({ async: false, ty ...