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

Ending JavaScript promises

I am currently utilizing the Google JS closure library which can be found at https://developers.google.com/closure/library/ Below is the code snippet that I have: if (endDate >= wap.com.ifx.util.IfxComponentUtil.yyyymmdd(currentDate) && goog.o ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

Searching for specific data within an embedded documents array in MongoDB using ID

While working with mongodb and nodejs to search for data within an embedded document, I encountered a strange issue. The query functions as expected in the database but not when implemented in the actual nodejs code. Below is the structure of my data obje ...

How to manage access controls for the Admin Page in node.js

Hi everyone, I am facing an issue with my admin page access control on my application. I want to restrict access to all users except the one named John. In my app.js file, here is what I have: app.get('/admin', requireLogin, function(req, res){ ...

Displaying a date and time beautifully in jQuery/JavaScript by providing the day of the week along with the specific time

Does anyone know of a Javascript library, preferably a jQuery plugin, that can take datetimes in any standard format (such as ISO 8601) and convert them into user-friendly strings like: Wednesday, 5:00pm Tomorrow, 9:00am Saturday, 11:00pm I'm not c ...

What are the appropriate situations for utilizing getStaticPaths()?

Right now, an API call is being made in a main component and the fetched data is saved in a Singleton. This singleton data needs to be accessed by the getStaticPaths() function. However, due to the fact that getStaticPaths() pre-renders it, the singleton ...

In the iOS app when the Ionic HTML5 select keypad is opened, a bug causes the view to scroll upwards and create empty space after tapping the tab

I am currently working with Ionic v1 and AngularJS, utilizing ion tabs: <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <!-- Home Tab --> <ion-tab icon-off="ion-home" icon-on="ion-home" href="#/tab/home"> <ion-nav ...

Getting the most out of your weather API: optimizing search parameters for precise location results and avoiding any confusion with similar locations

When experimenting with new platforms, I often utilize the openweathermap.org's api. However, I have encountered a recurring issue where I struggle to define a precise query for finding certain cities. The api functions smoothly for major cities like ...

Could not complete operation: EPERM error indicating permission denied for 'stat' operation

Recently delving into Firebase Functions for my Flutter project has been a game-changer. Discovering the code generator, firebase_functions_interop, that seamlessly transforms Dart code into Javascript has made developing cloud functions in Dart a breeze. ...

A pop-up window displaying an electron error message appears, but no errors are logged in the console

In a Nutshell: While developing a single-page website with Electron, I encountered the common issue of jQuery not being globally accessible. To tackle this problem, I decided to simplify it by using a quick start example, but unfortunately, I'm strugg ...

AngularJS 2 - error when trying to bind inner properties: ERROR: Unable to access property value due to undefined variable

I have been troubleshooting a problem with my AngularJS 2 app using Typescript. The issue arises when I attempt to access a property from the Typescript class in the HTML page using data binding. I have provided the relevant files below for reference. If t ...

My script is unable to access the session variable

Two $_SESSION variables seem to be inaccessible in any script on my page, yet I can confirm their existence in the PHP code of the same page by using echo to display their values. When trying to display these $_SESSION variables in jQuery using the code b ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

Efficiently Passing Data Between jQuery Dialog Boxes

English is not my strong suit, so please bear with me. I am currently working on a project using Jquery Dialog and I need to display multiple dialogs one after the other (dialog1 opens dialog2 which opens dialog3...) The issue I'm facing is that when ...

How can I go about refreshing my mapbox gl source data?

Hey there, I'm encountering an issue when attempting to update my mapbox source on click. I currently have two sources (cells, heatmap), and I am trying to add a new source using this code snippet: this.map.addSource("points", { type: "geojson", ...

Design with Internal Elements

Seeking a pattern similar to the code snippet provided below. Interested in learning how to create MyComponent. render(){ <MyComponent> <MyComponent.Something> These children will be displayed </MyComponent.Something> <MyC ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more. ...

What causes the Object expected error in jQuery?

Looking for a way to demo horizontal collapse pane with a simple web page that includes html, css, and jquery. <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script> <title>Sa ...

I'm encountering problems when attempting to display the image/png response from an xmlHTTPRequest. Instead of the correct data, I

I have implemented the following code to integrate a captcha generating web service. The response data is successfully obtained, but when I attempt to display the result within a div element, the image appears as distorted text. var xmlHttp = new XMLHtt ...

Stylus Vue Vite: The Trio of Global Variables

I'm trying to figure out how to globally import and use stylus variables in my Vue Vite project. How can I achieve this and access the variables within the script section of my Single File Component (SFC)? Below is an excerpt from my Vite config: exp ...