Display "Page Loading Error" when submitting a form with jQuery Mobile via JavaScript

While working on my jQM project, I encountered an issue with form submission. Instead of using the "action" URL to submit the form, I opted to use JavaScript to submit the form after validation by another JS addon. Once validated, the form is submitted using jQM $.post().

I found this approach on the jQM page:

Example: Send form data using ajax requests
$.post( "test.php", $( "#testform" ).serialize() );

Everything was functioning correctly, including the return data. However, my problem arose when trying to handle the "action" in the form. Removing it would result in the app redirecting to the jQM first page, and using "#" or "/" caused errors such as "Error Loading Page."

My question is, is there a way to eliminate the "Error Loading Page" message? I've attempted adding [data-ajax="false"] in the form tag, but it yielded the same result.

Please provide guidance, thank you.

Here is my JS code: This code resolved the issue. However, uncommenting the commented line to perform the actual task resulted in redirection to the first page of my multipage structure, seemingly ignoring the preventDefault function. What could be the root cause here? Please advise, thank you.

$(document).on("click", "#registerButton", function (e) {
    e.preventDefault();
    var registerForm = $( "#registerForm" );
    if (registerForm.valid() === true) {
        document.getElementById("regDeviceName").value = intel.xdk.device.model;
        document.getElementById("regDeviceOs").value = intel.xdk.device.platform;
        $.post("http://domain.com/api/user/register",
        $("#registerForm").serialize(),
            function(data,status){
                alert(data);
//                if (data == "registered") {
//                    $.mobile.pageContainer.pagecontainer("change", "#regSuccess");
//                }
//                elseif (data == "unverified") {
//                    $.mobile.pageContainer.pagecontainer("change", "#unverified");
//                }
//                elseif (data === "duplicate") {
//                    $.mobile.pageContainer.pagecontainer("change", "#duplicate");
//                }
//                else {
//                    $.mobile.pageContainer.pagecontainer("change", "#suspended");
//                };
//                $.mobile.pageContainer.pagecontainer("change", "#regSuccess");
            });
        }
});

Second attempt at JS code:

$("#registerButton").click(function (e) {
    e.preventDefault();
    var registerForm = $( "#registerForm" );
    if (registerForm.valid() === true) {
        document.getElementById("regDeviceName").value = intel.xdk.device.model;
        document.getElementById("regDeviceOs").value = intel.xdk.device.platform;
        $.post("http://domain.com/api/user/register",
        $("#registerForm").serialize(),
            function(data,status){
                alert(data);
//                if (data == "registered") {
//                    $.mobile.pageContainer.pagecontainer("change", "#regSuccess");
//                }
//                elseif (data == "unverified") {
//                    $.mobile.pageContainer.pagecontainer("change", "#unverified");
//                }
//                elseif (data === "duplicate") {
//                    $.mobile.pageContainer.pagecontainer("change", "#duplicate");
//                }
//                else {
//                    $.mobile.pageContainer.pagecontainer("change", "#suspended");
//                };
//                $.mobile.pageContainer.pagecontainer("change", "#regSuccess");
//                $("#registerResult").html("Data: " + data + "<br>Status: " + status);
            });
        }
});

HTML Form Structure (jQM multipage layout):

    <div data-role="page" id="register">
         <div data-role="header"><h1>Register</h1></div>
         <div data-role="content" class="pageWithHeader">
            <div id="formContainer">
                <form id="registerForm">
                <label for="regFirstName">First Name</label>
                <input class="registerVal" type="text" name="regFirstName" id="regFirstName" value="">
                <label for="regLastName">Last Name</label>
                <input class="registerVal" type="text" name="regLastName" id="regLastName" value="">
                <label for="regEmail">Email</label>
                <input class="registerVal" type="email" name="regEmail" id="regEmail" value="">
                <label for="regPassword">Password</label>
                <div id="regPassDiv">
                    <input class="registerVal" type="password" name="regPassword" id="regPassword" value="">
                </div>
                <input type="hidden" id="regDeviceName" name="regDeviceName" value="">
                <input type="hidden" id="regDeviceOs" name="regDeviceOs" value="">
                <div data-role="controlgroup" data-type="vertical">
                    <button id="registerButton" class="ui-btn ui-corner-all ui-icon-plus ui-btn-icon-left">Register</button>
                    <a href="#verifyRegister" class="ui-btn ui-corner-all ui-icon-check-square-o ui-btn-icon-left">Go to Account Verification</a>
                </div>
                </form>
             </div>
<!--             <div id="registerResult"></div>-->
         </div>
    </div> 

Answer №1

Here's a solution: To prevent the default action of your form tag, make sure to add the following code snippet before submitting.

Check out the code below:

$("#formid").submit(function(e){
     $.post( "test.php", $( "#testform" ).serialize() );  

});

If you are using jQuery validator, ensure to include this code within the successHandler function. You do not need to prevent the default action on the form tag in this case.

Additional Code for Validation:

 $('#myform').validate({
  rules:{
  firstname:"required",
  lastname:"required",
  username:"required" ,
  employeeid:"required",
  email:{
  required:true,
  email:true
  },
  password:{
  required:true,
  minlength:5
  },
  phoneno:{
  minlength:9,
  maxlength:10,

  }
  },
  messages:{
  username:"Please enter your username..!",
  password:"Please enter your password..!"
  },

  submitHandler: function(form) {
              $.post( "test.php", $( "#testform" ).serialize() );  
  }
  });

Answer №2

Everything in the code looks good except for one minor issue with the use of "elseif".

The correct syntax should be "else if". By including "e.preventDefault();" and fixing this small error, the code behaves exactly as intended.

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

Select from a variety of backgrounds using the dropdown menu on the site

I seem to be struggling with javascript and php, but I know that in order to make this function properly, I need to utilize both languages. My goal is to set up a "select box" featuring 4 different images. There will be a default image displayed, but user ...

Values are being set back to '1' within the popup dialog

After recently incorporating Twitter Bootstrap into my web app project, everything seemed to be going smoothly until I encountered an issue with a modal window. Following the Bootstrap documentation, I set up a button that triggers a modal window to appea ...

What is the reason behind fullstack-angular generator utilizing Lo-Dash's merge rather than document.set?

This is the original code snippet used for updating: exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Thing.findById(req.params.id, function (err, thing) { if (err) { return handleError(res, err); } if(!thing) { ...

Adding TypeScript types to an array within a function parameter: A step-by-step guide

Having some trouble defining the array type: The code below is functioning perfectly: const messageCustomStyles: Array<keyof IAlertMessage> = [ 'font', 'margin', 'padding' ]; r ...

Touch target for scrollbars

While developing the modal in HTML, I encountered an issue where keyboard-only users cannot access all content within the modal. I came across a note stating that the scrollbar touch target should be 44px by 44px. I tried reading this documentation https ...

Set values for all variables that begin with a specific string

[WARNING! Proceed with caution] One of my most recent coding dilemmas involves creating a JavaScript script that can identify specific surveys. These surveys use variables that share a common string followed by a random number, like this: variableName_46 ...

Storing HTML, JavaScript, and CSS files using HTML5 local storage: A comprehensive guide!

Could you provide guidance on how to store HTML, JavaScript, and CSS files in HTML5 local storage? I am looking to optimize the speed of my web application! Thank you! ...

Using JQuery's Ajax method to dynamically update a div in real-time while querying PHP

When importing 4000 rows from a CSV file, I encounter a scenario where Page 1 displays the CSV file on the server along with a PROCESS button. Upon clicking the button, the JQuery Ajax function is triggered to call the necessary PHP code responsible for th ...

Dynamic text in Bootstrap 5 Popovers

Having some trouble setting the text on a bootstrap popover: Here's the HTML: <span class="d-inline-block" id="searchPredict" tabindex="0" data-bs-toggle="popover" data-bs-trigger="hover focus" tit ...

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

Refreshing a series of forms in Javascript

One of the features on my website is a comment section where users can reply to comments. Each comment has a reply form and I am fetching comments from the database using a loop. @foreach($responses as $response) <form action="{{action('Discussio ...

Utilize JavaScript to trigger a gentle notification window to appear on the screen

Whenever I click a link on my HTML page, I want a popup element (just a div box) to appear above the clicked link. I have been using JavaScript for this, but I am facing an issue where the popup element appears below the link instead of above it. Can you ...

Clicking on a link in HTML with the onclick event

I am looking to create a button that will direct me to a different page. Here is the code snippet I have: <div align="right" ><input type="submit" id="logout" onclick="location.href='/login?dis=yes'" value="Sign Out" ></div>& ...

"Combining Array Elements in jQuery: A Guide to Merging Two Array Objects

enter : var b= [{ "cat_id": "1", "cat_name": "teaching" }]; var a= [ { "username": "r", "password": "r" }]; I desire the following result: [{"username":"r","password":"r","cat_id":"1","cat_name":"teaching"}] ...

Perform both creation and updating tasks within a single transaction using sequelize

Is it feasible to add a new row and update it within the same sequelize transaction? Here's what I've tried: let transaction; try { transaction = await dbcontext.sequelize.transaction(); const newEmployee = await dbcontext.Empl ...

Tips for accessing the selected button in notification.confirm() within a PhoneGap app

Recently, I implemented the Phonegap notification.confirm in this way: navigator.notification.confirm( 'Do you wish to proceed?', function() { console.log("Function Called"); }, 'Game Over', 'Continu ...

Tips on using Ajax to post in HTML

Here is the code I have been working on: <script type="text/javascript"> var xmlDoc; var xmlhttp; function loadRates() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = readRates; xmlhttp.open("GE ...

Ways to determine if a user is using a PC using JavaScript

I am developing a website using node.js that will also serve as the foundation for a mobile app. The idea is to have users access the website on their phones and use it like an app. But I want to implement a feature that detects when the site is being vi ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

What is the correct way to specify a property for a Type within a function component? Issue TS2339 encountered

Looking at the code provided below, we can see an implementation in React that works well in JS/JSX but encounters errors when using TypeScript. import React, { useContext, useReducer, useEffect, } from 'react'; const AppContext = React.createC ...