Attempting to execute a PHP script through a JavaScript if statement

I have a form that requires validation with JavaScript. In one of the if statements, after all other conditions have been validated, I want to execute my PHP script that updates an SQL database with one of the passwords.

Here is the final validation code:

function passwordCheck() {
    var password = '<?php echo $password; ?>';
    if (document.passwordform.inputedPassword.value == password)
    {
        if (document.passwordform.Password1.value == document.passwordform.Password2.value)
        {
            *********************************************************
        } else 
        {
            document.getElementById("equalpasswords1").innerHTML = "Passwords must be the same";
            document.getElementById("equalpasswords2").innerHTML = "Passwords must be the same";
        }
    } else 
    {
        text = "Please insert the correct password";
        document.getElementById("editpassword").innerHTML = text;
    }
    return true;
}

I would like to place a call to my PHP script where the asterisks are located. However, since it is not possible to directly insert PHP into JavaScript, the PHP code needs to be in an external file. Here is my SQL update code:

<?php              
$x = $_POST['Password2'];

define('DB_NAME', 'Students');
define('DB_USER', 'Students');
define('DB_PASSWORD', 'Password');
define('DB_HOST','HOST');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!link) {
  die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) {
  die('Can\'t use'. DB_NAME. ': ' . mysql_error());
}    


$result = "UPDATE  `1956218_students`.`Students` SET  `Password` =  '$x' WHERE  `Students`.`StudEmail` = '$email'  ";
if (!mysql_query($result)) {
die('error: ' .mysql_error());
} 

?>

Answer №1

It's important to understand that JavaScript runs on the client's side, in the browser, while PHP code is executed on the server's side.

In order for PHP code to handle and process data (such as validating passwords and generating responses in JSON format), you need to make a request to the server. This can be done by sending another request from the client-side using technologies like JQuery or Ajax.

If you're looking for guidance on how to validate usernames and passwords using jQuery/Ajax, you may find this resource helpful:
How to validate a username / password via JQuery / Ajax?

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

The image in the row wrap container spills over slightly

Even though all the items within that container are wrapped properly as article, there is an issue with the right border of the image overflowing the container's article border. My temporary solution involves adding a mediaquery @1041px and a small a ...

Use AppScript to exclude the first row (which contains the column names) when filtering a table

Considering the limitations of Google Sheets with the ImportRange function, I decided to develop an AppScript as a replacement. Although I am new to JavaScript, here is what I have so far: function My_ImportRange() { var clearContent = SpreadsheetApp.ge ...

Issue with Bootstrap checkbox buttons not rendering properly

I'm attempting to utilize the checkbox button feature outlined on the bootstrap webpage here in the "checkbox" subsection. I copied and pasted the html code (displayed below) from that page into a jsfiddle, and checkboxes are unexpectedly appearing in ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

A step-by-step guide on changing an image

Is it possible to change an image when the user clicks on a link to expand its content? <ul class="accor"> <li> Item 1 <img src="../plus.png"> <p> Lorem ipsum dolor sit amet</p> </li> </ul> $(' ...

What is the best way to conceal the HTML video controls for multiple videos displayed on a single webpage?

I have a web page that displays a collection of movies generated using a PHP foreach loop. The code snippet looks like this: foreach ($movies as $movie) { $pos = strrpos($movie, '/'); $id = $pos === false ? $movie : substr($movie, $pos ...

Stopping the animation of scrollLeft upon user interaction can be achieved by utilizing JavaScript

Here is my current code snippet: <script> $(document).ready(function() { $('.scrolls').stop().animate({ scrollLeft : 4000 },100000, 'linear') }) </script> I am looking for a way to halt the animation once ...

Sending a post request using an AngularJS service

I have implemented the following code in my application. The dataService holds all the $http requests in my app. In the controller, I am using this function to call a Web Api service which returns the correct response. However, when the function customer ...

What steps can I take to prevent BeautifulSoup from interpreting commas as tab characters?

My recent project involved creating a web scraping code to extract information from a local news website. However, I have encountered two issues with the current code. One problem is that when the code retrieves paragraph data and saves it to a CSV file ...

Creating nested JSON from an array using PHP

How can I generate a JSON from an array of values like this? [items_list] => Array ( [0] => FattureInCloud\Model\ReceivedDocumentItemsListItem Object ( [openAPINullablesSetToNull:protected] => Arra ...

Can you suggest an alternative for the "return" statement within a "for loop" in order to retrieve all values from the loop?

When using numInOrder + " : " + nameInOrder;, the console only displays one value: "1 : a". However, I would like to see: "1 : a 2 : b 3 : c 4 : d 5 : e 6 : f" in the console.log output. Additionally, I do not want to use consol.log(numInOrder + " ...

What could be causing the sporadic functionality of my jQuery image resizing code?

Seeking help for an issue I am facing with my jQuery code. I have been trying to scale a group of images proportionally within an image carousel using jCarousel Lite plugin. However, the resizing code seems to work randomly and I can't figure out why. ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...

Using regular expressions in JavaScript, eliminate all characters preceding a specified final character

I am attempting to eliminate all text that precedes the last character in a Regex pattern. For example: rom.com/run/login.php Would turn into: login.php Can someone guide me on how to achieve this using JavaScript? I have limited experience with regul ...

What is the information stored inside the div element?

How can I extract the contents of a div using bs4? >>> Doc <div class="document"> <p>Text.</p> <p>More text</p> </div> >>> type(Doc) bs4.element.Tag I am looking to retrieve: <p>Text.</p> ...

The popularity of AJAX in JavaScript is continuing to rise

I am facing an issue with my website that features a configurable 3D object with various properties. Whenever I reload the div containing the 3D object to reflect new properties, the script data keeps adding on. This not only slows down the functionality a ...

Implementing a function to navigate to a different page using jQuery mobile

I'm attempting to pass a function when changing pages in jQuery Mobile, but I keep getting an error that points to `$.ajax` $( ":mobile-pagecontainer" ).pagecontainer( "change", "#schoolperformance", { reload : true, showLoadMsg : false, ...

Unable to determine the data type of the JSON object during the

I'm having trouble reading an Object type of json... Here is the json I'm working with: body: { "111": { "name": "name1", "status": 10000 }, "222": { "name": "name2", "status": 20000 }, "333": ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Choose either nth-child or nth-of-type within a nested element

Here is the HTML code snippet: <div class="homepage-body"> <a href="#"> <div class="homepage-item"> <div class="homepage-icon"></div> <div class="homepage-text"> Test1 </di ...