Guide to seamlessly integrating form data into MySQL using JavaScript and HTML without redirecting the user from the current page

Having trouble inserting a new user into MySQL database? I've attempted using both jQuery and pure JavaScript, but it doesn't seem to be working. There's no response when I click on the submit button. Any ideas on what might be causing this issue?

var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);

function submitForm() {

    var acR = document.getElementById("ac2");
    var pw1 = document.getElementById("pw1");
    var shop = document.getElementById("shop");

    var http = new XMLHttpRequest();
    http.open("POST", "http://xyz.php", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "ac=" + acR.value + "&pw1="+pw1.value "&shop="+ shop.value;
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    };
}

Answer №1

Your JavaScript code had a few issues, but I've cleaned it up and tested it on a local page named xyz.php. This should make the AJAX call work, but you'll need to share your PHP code for assistance with the database queries.

    var regBtn = document.getElementById("regBtn");
    regBtn.addEventListener("click", submitForm, false);

    function submitForm() {

        var acR = document.getElementById("ac2");
        var pw1 = document.getElementById("pw1");

        var http = new XMLHttpRequest();
        // Removed the http:// protocol assuming a local AJAX call
        http.open("POST", "xyz.php", true);
        http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        // Retrieve form field values instead of submitting the full element
        // Added plus (+) character before final pw1
        var params = "ac=" + acR.value + "&pw1=" + pw1.value;
        http.send(params);
        http.onload = function() {
            alert(http.responseText);
        }
    }

I've included a screenshot demonstrating Chrome Dev Tools capturing successful AJAX requests

https://i.sstatic.net/rVpUM.png

Answer №2

Consider utilizing JQuery post method for this task.

var acElement = document.getElementById("ac2");
var pw1Element = document.getElementById("pw1");

$.post( "xyz.php", { account: acElement, password: pw1Element })
.done(function( data ) {
   alert( "Data has been successfully inserted: " + data );
});

The backend is responsible for processing this post request and executing the insert action, for instance in NodeJs using Express framework.

app.post("/xyz", function(req, res, next) {
    var obj = {};
    obj[account] = body.account;
    obj[password] = body.password;
    mysql.insert(obj);

});

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

Difficulty arises when collapsed text in Bootstrap clashes with the footer design

Hey there! I'm working on this website using Bootstrap, and I've encountered a problem. When you click the "See Wikipedia" button, the content expands and overlaps the footer in a strange way without changing the page height. I've tried adju ...

What is the best way to retrieve the duration of an object tag using JavaScript or jQuery?

My goal is to determine the duration and length of only mp4 type videos. Although I used the video tag to retrieve these values, it does not support mp4 files. Despite several attempts, I was unable to get the video tag to play only mp4 files, as it stric ...

Switch tabs with JavaScript

I'm encountering an issue with changing tabs using JavaScript and Ajax. The script I have works when not using Ajax but fails to work properly with it. Here is the script: $(document).ready(function(){ $("#mtabs li").click(function() { ...

Changes are being made to the state, but the updates are not showing up in the user interface of my photo feed

Welcome everyone, I'm currently immersed in learning react and have developed several apps using react, such as a hotel website (using react and contentful cms), an e-commerce website (using react, contentful cms, paypal), githubfinder app, todos app, ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

Exploring the usefulness of `bind(this)` within a ReactJS constructor

I have a good understanding of the Javascript function bind. However, I'm puzzled by why in the React.js snippet below, this is being bound again to itself. Is this related to the constructor, as this in the constructor can vary depending on how it&ap ...

Dynamic PHP AJAX XML search feature that requires minimal input characters

I'm encountering an issue with the Ajax PHP Live search feature from W3Schools. I want to only display results that are longer than 2 characters, but I can't seem to locate where to make this change. I've been searching for a solution for qu ...

Ensure the video frame stretches to fit the full width

I am struggling to make my video frame fill the entire width of the screen. Even though I have tried using CSS, the video container does not stretch to the full width as expected. https://i.sstatic.net/kxyE0.png How can I ensure that the video plays acro ...

Strategies for resolving the problem of null values from getParameter() being passed from AJAX to servlet

After reading numerous answers on Stack overflow, I have tried various solutions to fix this issue without success. My goal is to send a JavaScript variable to a servlet using AJAX within an else statement in JS. However, I keep receiving null in the alert ...

Managing JSON data retrieval and manipulation with REST API in Node.js and MongoDB

My technology stack includes Node.js and MongoDB with a rest api. The input data I'm dealing with looks like this: var doc={"name":"ABX", duedate : new Date() } Before sending it to the server, I stringify the data: /rest/update?doc=JSON.s ...

Unable to attach an onClick event handler to <TableRowColumn> element using Material-UI in React

In the past, I had a feature that allowed me to change the color of the text from red to green by clicking on a table cell. After introducing Material-UI in my React app and replacing the <td> tags with <TableRowColumn> tags, I noticed that th ...

When the input is altered, retrieve all input values within the div and then proceed to update the corresponding

The HTML provided is structured as follows: <div class="filters"> <div class="filter-label">6</div> <div class="filter-inputs"> <input type="number" name="i1" id="i1" value="1" min="0" step="1" /> & ...

Tips for showcasing timestamps within a Vue.js/Firebase application

In my current project, I am working on developing a chat application using Vue.js and Firebase. The codebase I am referring to can be found at https://github.com/jsfanatik/vuestacks-chat-vue-firebase. I have successfully implemented the Chat component to a ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

How to dynamically add list items to a jQuery Mobile list using Ajax requests

Included in my index.html is a list view: <section id="dashboard" data-role="page" data-transition="slide"> <header data-role="header"> <h1>Trips</h1> <a href="#addTrip" id="createNewTrip" d ...

The $resource.query function will now return an array of characters instead of a single string when splitting strings

Recently, I've been working on utilizing an Angular $resource in my project. Here's a snippet of the code: angular.module('app') .factory('data', function ($resource) { var Con = $resource('/api/data', {}, { ...

The function get() in p5.js will provide you with an array of pixels that is empty

I am currently working on a project that is inspired by this particular video. Within p5.js, I have been utilizing the get() function. My goal is to divide a large tileset into smaller images and store them in an array. However, I have encountered an issue ...

Screen content of a post request in Node.js

Can this code in node.js + express be simplified? // Code snippet for registering a new participant app.post('/api/participant', function (req, res, next) { var data = req.body; // Ensure only specific fields are uploaded var parti ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

Is there a way to identify if the parent page has completed loading while within an iframe?

Is there a way to detect properties or events within the iframe that can help determine this? The src of the iframe and the parent page belong to different domains. ...