A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking the submit button. Upon clicking the button, a JavaScript function is called to check whether the entered username and password are correct or not. Below is the JavaScript function I have written for this purpose:

 var user, pwd ;
 var xmlHttp = null;
 var val;
 $("#Login").click(function(event){
 event.preventDefault();
 user = $("#username").value() ;
 pwd = $("#password").value() ;
 validateForm();
});

    function validateForm() {
        var url ="http://schoolsmartconnect.com/android/parent_login.php?key=agile89rise98&username="+user+"&password="+pwd;                
        xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = ProcessRequest;
        xmlHttp.open( "POST", Url, true );
        xmlHttp.send( null );
            if (val == "1") {
                window.location = "page2.html";
                return true;
            }
            else {
                alert ("Login was unsuccessful, please check your username and password");
                return false;
            }
      }

    function ProcessRequest() 
    {
        if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
        {
            if ( xmlHttp.responseText == "1" ) 
            {

                var val = xmlHttp.responseText;

            }                 
        }

    } 

Additionally, here is my server-side PHP script:

<?php 
require_once 'db.php';

$user = base64_decode($_REQUEST['username']);
$pass = base64_decode($_REQUEST['password']);
$key = $_REQUEST['key'];
$password = md5($pass);
if($key=="agile89rise98"){
//echo $password;
$query = mysql_query("SELECT * FROM puserprofile WHERE username ='$user' AND password = '$password' and Status=1");
$rownum = mysql_num_rows($query);

if(0 < $rownum)
{       
    echo 1; 
}
else
{
    $query2 = mysql_query("SELECT * FROM puserprofile WHERE username ='$user' and Status=1");
    $rownum2 = mysql_num_rows($query2);
    if(0 == $rownum2) {
        $query3 = mysql_query("SELECT * FROM puserprofile WHERE password = '$password' and Status=1");
        $rownum3 = mysql_num_rows($query3);
        if (0 == $rownum3) {
        echo 0;
        }
        else if(!preg_match('/^[A-Za-z]{1}[A-Za-z0-9]{5,31}$/', $user){
        echo "username invalid";
        }
        else {
        echo "Invalid username";
        }


    } else {    
        $query3 = mysql_query("SELECT * FROM puserprofile WHERE password = '$password' and Status=1");
        $rownum3 = mysql_num_rows($query3);
        if (0 == $rownum3) {
        echo "Invalid password";
        } else {
            echo 0;             
        }
    }   
}
}

?>

In conclusion, my aim is to effectively communicate with the server through my JavaScript function by sending username and password requests and receiving responses. If the response is equal to "1," then it should redirect to the appropriate page; otherwise, error messages should be displayed.

Answer №1

Instead of gathering username and password from the URL, why not simply retrieve them from the input fields? It's much easier to validate the values this way.
Try implementing something like this:

<input type="text" id="user"/>
<input type="password" id="pwd"/>
<input type="submit" id="submit"/>


In your script, you can do the following:

var user, pwd ;
$("#submit").click(function(event){
event.preventDefault();
user = $("#user").value() ;
pwd = $("#pwd").value() ;
validateForm();
});



UPDATE
Now, your script will appear as follows:

var user, pwd ;
 var xmlHttp = null;
 var val;
 $("#Login").click(function(event){
 event.preventDefault();
 user = $("#username").value() ;
 pwd = $("#password").value() ;
 validateForm();
});

function validateForm() {
    var url ="http://schoolsmartconnect.com/android/parent_login.php?key=agile89rise98&username="+user+"&password="+pwd;                
    xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", url, true );
    xmlHttp.send( null );
  }

function ProcessRequest() 
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
    {
        if ( xmlHttp.responseText === "1" ) 
        {

            var val = xmlHttp.responseText;
            if (val == "1") {
                window.location = "page2.html";
                return true;
            }
            else {
                alert ("Login was unsuccessful, please check your username and password");
                return false;
            }

        }                 
    }
} 

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

Codeceptjs does not have the capability to scroll or swipe down without being linked to a specific element

I'm facing an issue with scrolling/swiping down in an Android application while using codeceptjs. The method I'm currently using only works on the visible element, but I need to scroll down to the bottom of the page or a specific element without ...

retrieve all users who are not currently in the group

I'm currently struggling to retrieve all users who are not members of a particular group within a many-to-many association. After investing several hours into researching and experimenting, I've developed the following code. However, it falls sh ...

"Unlocking the Power of mediaElementjs: Easy Steps to Accessing the Player Instance

I'm facing a small issue with the MediaElement.js player. To access the player instance, I usually use the following code (which works in HTML5 compatible browsers): // Retrieve player this.playerId = $('div#shotlist-player video').att ...

Guide on sharing Photo Blogs on Tumblr using the "tumblr.js" NodeJS module

I've been using the tumblr.js node module to interact with the Tumblr API, but I'm having trouble understanding what exactly should be included in the "options" when posting on my blog. So far, I've only used this module to retrieve my follo ...

Is it possible to integrate a GWT library into Dart programming?

Considering migrating to Dart, but unsure of its maturity. Can a library originally written in GWT be used in Dart? ...

using a route object to update the path in Nuxt

I need to navigate to a specific URL: myApp.com/search-page?name%5Bquery%5D=value The code snippet below works perfectly when I'm on the homepage myApp.com: this.$router.push({ path: "search-page", query: { name: { query: `${this.value} ...

How can I simulate keyboard events in Angular using a button click?

I've included separate buttons for Ctrl+z and Ctrl+y functionalities. When these buttons are clicked, I want them to perform the respective undo and redo actions programmatically. Below is the code snippet for this functionality. undoText(event:MouseE ...

What is the best way to ensure that the buttons remain in place once they have been clicked to reveal a drop-down menu?

Is there a way to keep 3 buttons inline and prevent them from moving when clicked to open a submenu? Changing their positions results in them stacking on top of each other. Any help or suggestions would be greatly appreciated, thank you! Here is the code ...

"The AJAX response returned a status code of 200, however, the PHP script being executed on the XAMPP localhost did not provide

The HTML code initiates a localhost function called getNodes which returns JSON data that is verified by JSON lint. However, when the same function is invoked using AJAX from a JavaScript file, a 200 response code is received without any response data. I h ...

Tips for retrieving next-auth authOptions from an asynchronous function

I need to retrieve values from AWS Secrets Manager and integrate them into the authOptions configuration for next-auth. The code implementation I have is as follows: export const buildAuthOptions = async () => { const secrets: AuthSecrets = await getS ...

Is it possible to access a component's function from outside an ng-repeat in Angular 1.5?

Recently delved into learning Angular 1.5 components and testing out some fresh concepts, however, I'm struggling to wrap my head around this particular issue: Here's the code snippet from my Main: angular.module('myapp',[]) .contr ...

What techniques can I use to merge alpha channels with compositing in images?

Utilizing an HTML5 Canvas along with the KineticJS(KonvaJS) canvas library, I have successfully incorporated an Image element. My current objective is to erase specific pixels while maintaining a certain level of transparency. The red dot erases pixels at ...

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

jQuery automatic slider for seamless transitions

I am in need of assistance with the coding for a website I'm currently constructing at www.diveintodesign.co.uk/ChrisMcCrone/index.html The coding being used is sourced from http://jquery.malsup.com/cycle/ The central large image functions as a slid ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

I am puzzled as to why my DataGrid MUI component is not functioning properly

I am taking my first steps with MUI, the MaterialUI React Component library. After following the installation instructions in the documentation, I am now attempting to integrate the DataGrid component into my React project. My goal is to replicate the fir ...

Execute JavaScript script once when route changes

I'm currently working on a system where I want to ensure that my animation-based JavaScript code only runs once after the route changes. The issue I'm facing is that when switching between pages and returning to the about page, the scripts are ca ...

Adobe Acrobat does not run JavaScript code in documents that are submitted for electronic signatures

Lately, I have been experiencing issues with pdfs that contain embedded javascript. The strange thing is that the javascript functions perfectly in the Acrobat Pro DC app but fails to execute when the document is sent for signature. To troubleshoot, I cre ...

Tips for inserting an item into the parent window: Chrome-specific (compatible with all other browsers)

In my HTML file, I have an iFrame element like this: <iframe src="frame.html" width="2000" height="1000"></iframe> When trying to use jQuery's append function from within the iFrame to add a DIV to the parent window, it works fine in Fir ...

"Navigate through the page by scrolling with your mouse all the way to 100

Is it possible to trigger an action when a user starts scrolling using the mousewheel? I've searched online but all I found was information on 100% scroll on click. I want the window to automatically be scrolled down to 100% as soon as the user starts ...