Easy jQuery Mobile and AJAX login solution

My current project involves creating a mobile app with user login capabilities using PhoneGap, jQuery Mobile, AJAX, and PHP. I am starting with a basic HTML and PHP structure as I am not an experienced programmer, but even my simple user login form is not functioning correctly.

Below is the HTML code for the user login page (sampleindex.html):

<!doctype html>
<html>

<head>

<meta charset="UTF-8">

<title>Untitled Document</title>

<link rel="stylesheet" type="text/css" href="/themes/P32-Manager.css">   
<link rel="stylesheet" type="text/css" href="/themes/jquery.mobile.icons.min.css">
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css">    
<link rel="stylesheet" type="text/css" href="/themes/jQuery-Overrides.css">    
<link rel="stylesheet" type="text/css" href="/css/styles.css">

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<script>
function userLogin(email) {
    if (email == "") {
        document.getElementById("logincontainer").innerHTML = "";
        return;
    }
    else {
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        }
        else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("logincontainer").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET","samplehome.php?UserName="+email,true);
        xmlhttp.send();
    }
}
</script>

</head>

<body>

<div data-role="page" id="logincontainer">

    <form action="sampleindex.html" method="get">

        <div style="text-align:center; display:inline-block;">

            <div data-role="fieldcontain" style="text-align:center; position:relative; top:0em; left:0.5em; width:100%; margin:auto; border:0;">
                <label for="username" style="display:block; width:350px; text-align:left;">Username (Email)
                    <input data-clear-btn="false" name="UserName" type="text" value="" class="ui-input-text" style="height:40px; font-size:18px;">
                </label>
            </div>

            <div data-role="fieldcontain" style="text-align:center; position:relative; top:-1.25em; left:0.5em; width:100%; margin:auto; border:0;">
                <label for="password" style="display:block; width:350px; text-align:left;">Password
                    <input data-clear-btn="false" name="Password" type="password" value="" class="ui-input-text" autocomplete="off" style="height:40px; font-size:18px;">
                </label>
            </div>

        </div>

        <div data-role="fieldcontain" style="text-align:center; position:relative; top:-0.5em; left:-1em; width:100%; margin:auto; border:0;">
            <div id="login-button" style="position:relative; left:0em; width:300px; height:62px; margin:auto; border:0; background-color:#ffffff;" data-inline="true">
                <input data-role="button" name="loginbutton" type="submit" value="Login" style="position:absolute; left:0em;" onClick="userLogin(UserName);">
            </div>
        </div>

    </form>         

</div>

</body>

</html>

We are utilizing FileMaker for our database (similar to MySQL) connected through the FileMaker PHP API. The database layout used is "Demo php," and we want to retrieve values such as "UserName" and corresponding "FirstName" from the database via URL parameters. Additionally, we aim to obtain the RecordID for each logged-in user to provide specific information. Despite focusing on proof of concept rather than security, when clicking "Login," the page remains blank, indicating potential issues with jQuery and AJAX implementation. Any insights on troubleshooting and passing ID values using jQuery without page refresh are greatly appreciated.

This is the PHP file (samplehome.php):

<?php
session_start();
$_SESSION['logged-in']=0;
?>

<?php 

include ("../../dbaccess.php"); 

$username = urldecode($_GET['UserName']);

if(isset($_GET['loginbutton']) and (!empty($_GET['UserName']) and !empty($_GET['Password'])) )
{
$username = '==' . urldecode($_GET['UserName']);
$password = md5($_GET['Password']);
$request = $fm->newFindCommand('Demo php');
$request->addFindCriterion('UserName', $username);
$request->addFindCriterion('Password', $password);
$result = $request->execute();

if (FileMaker::isError($result)) 
{
$request = $fm->newFindAllCommand('Demo php');
$result = $request->execute();
}

$found = $result->getFoundSetCount();

$records = $result->getRecords();

if($found == 1)
{
$_SESSION['logged-in']=1;

echo '<table border="1">
              <tr>
                    <th>First Name</th>
              </tr>';

foreach ($records as $record)
{
echo '<tr>';
echo '<td>' . $record->getField('FirstName') . '</td>';
echo '</tr>';
}

echo '</table>';

}

else
{
$_SESSION['logged-in']=0;

echo 'nope';
}

}   

?>

Currently, upon clicking "Login," the page remains blank without any data displayed, suggesting a malfunction in the authentication process. Assistance in resolving this issue and handling passed ID values efficiently using jQuery and AJAX would be greatly helpful.

Your help is much appreciated!

Answer №1

It appears that you may not be properly referencing the entered value.

 onClick="userLogin(UserName);"

In this context, UserName is a javascript variable that seems to be undefined.

Within your userLogin function, the initial check is:

function userLogin(email) {
    if (email == "") {
        document.getElementById("logincontainer").innerHTML = "";
        return;
    }

Here, email is undefined due to UserName being undefined, causing JavaScript to compare undefined to "", resulting in the page being cleared.

To resolve this issue, you need to pass in the value of the UserName input or retrieve it within your function.

Firstly, assign an id to your username input:

<input data-clear-btn="false" name="UserName" type="text" value="" class="ui-input-text" style="height:40px; font-size:18px;" id="UserName">

Next, update your onclick event:

 onClick="userLogin(document.getElementById('UserName').value);"

This adjustment should prevent the initial blanking caused by the HTML clearing out. Further troubleshooting may be required beyond this point.

You might also consider replacing the HTML clearing with an alert message to avoid having to reload the page if the username field is empty.

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

Customizing the initial search parameters in Vue InstantSearch: A step-by-step guide

I am utilizing the Vue components from Algolia to perform a search on my index. The search functionality is working correctly, but I am curious about setting the initial values for the refinement list upon page load. This is how I have set up the search: ...

Pass additional parameter while calling a function in Vue

Visit Element on GitHub Check out the upload component <el-upload class="avatar-uploader" action="/upload" :show-file-list="false" :on-error="handleUrlError" :on-success="handleUrlSuccess"> <i v-else class="el-icon-plus avatar-uploade ...

A guide to extracting functions from a `v-for` loop in a table

Beginner here. I am attempting to create a dropdown menu for the div with an id matching my specific name. For instance, let's say my table column names are: A, B, C. I only want to have a dropdown menu for column A. The template of my table looks ...

Exploring the Depths of Javascript Variable Scope

bar: function () { var cValue = false; car(4, function () { cValue = true; if (cValue) alert("cvalue is true 1"); }); if (cValue) alert("cvalue is true 2"); } car: function (val, fn) { fn(); } I have encountered a similar is ...

What is the best way to JSON serialize a Django queryset in python?

When working with AJAX responses, I encountered an error while trying to serialize a queryset. The error message was: TypeError: 'Font: FontName' is not JSON serializable The code snippet using JSON response looks like this: ... return Json ...

Troubleshooting Query Param Problems in EmberJS Route Navigation

("ember-cli": "2.2.0-beta.6") A search page on my website allows users to look for two different types of records: Users or Organizations. The URL for this search page is /search and I have implemented query parameters to maintain the state and enable ba ...

Exploring the location where an XMLHttpRequest/Ajax link is executed

I am relatively new to the world of Ajax/XMLHttpRequest and I am currently trying to wrap my head around its functionality. My current project involves developing an inventory program that essentially allows users to add tools to a digital box. On the mai ...

Issue with GLTF Loader Trial: Encountering TypeError when trying to resolve module specifier "three". Invalid references detected; relative references must begin with either "/", "./", or "../"

I'm relatively new to working with three.js and I am currently attempting to load a model into my canvas. However, when I import the GLTFLoader, I encounter the error message mentioned in the console above. Despite checking the syntax and relative pat ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Customizing ExtJS 4.1: Mastering field overrides

Seeking guidance on applying a plugin to all fields(numberfield, textfield, datefield, etc.) within the ExtJS 4.1 library. Does anyone have suggestions on how to achieve this? I understand that all fields are derived from BaseField. I attempted the follow ...

Changing all object values to true with React useState

In a certain file, I have defined an object with the following structure: export const items = { first: false, second: false, third: false } Within a component, I am using this object as shown below: import { items } from 'file'; const [el ...

Material-UI web application experiencing crashes due to worn-out cards, resulting in element type being declared as invalid and raising an error

After reviewing numerous similar SO questions, it appears that the issue always comes down to problems with imports. Typically, these involve mistyped import destinations or missing braces, but I have double-checked and found no such issues in my code. Th ...

Is it feasible to showcase collections from MongoDB and every individual element from all collections on a single EJS page?

I am currently working on developing a forum for my website using NodeJs, Express, MongoDB, and EJS for HTML rendering. However, I encountered an error message saying: "cannot set headers after they are sent to the client." I am a bit confused about this i ...

Request to convert jQuery Ajax code into Vanilla JavaScript code

Are there any vanilla JavaScript alternatives available for the code snippet below? function verifyEmail() { var apiUrl = "https://apilayer.net/api/check?access_key=c5118f1f9827f42a5fc4b231932130a8&email=" + document.getElementById('email&apos ...

Discovering routes in Angular2

I'm attempting to replicate something similar to this example here: AngularJS show div based on url/condition <span id="page-locator" *ngIf="location.path() == '/overview'">test</span> Unfortunately, it's not working as ex ...

Attempting to transfer various files using a text box, yet upon submission, the form does not contain any input for the name or date text

The issue I am facing is that although this code successfully saves the file and the name to the database, the textbox values for Name and Date are empty even though they were filled in. Below are the PHP and HTML Files along with JavaScript: index.html ...

Impressive javascript - extract file from formData and forward it

Presented here is my API handler code. // Retrieve data. const form = formidable({ multiples: true }); form.parse(request, async (err: any, fields: any, files: any) => { if (!drupal) { return response.status(500).send('Empty ...

Using a PHP variable within an AJAX modal window: A step-by-step guide

The main page (main.php) is currently holding a variable called $var = "hello". A modal window (modal.php) is being loaded through AJAX utilizing the following script: var modal_xhr = $.ajax({ 'type' : 'GET', ...

Adding plain HTML using jQuery can be done using the `.after()` and `.before()` methods

I have encountered a situation where I need to insert closing tags before an HTML element and then reopen it with the proper tags. The code snippet I am using is as follows: tag.before("</div></div>"); and then re-open it by adding proper tag ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...