Submitting multiple forms using AJAX and PHP

I am currently trying to send the form data to another page for processing, but I am not receiving any data. Below are the forms in question: The default form is the login form for requesting a username and password, with only one submit button.

                <div id="form_wrapper" class="form_wrapper">
                <form class="register">
                    <h3>Register</h3>
                    <div>
                        <label>Username:</label>
                        <input type="text" name="regname"/>
                        <span class="error">This is an error</span>
                    </div>
                    <div>
                        <label>Password:</label>
                        <input type="password" name="regpass" />
                        <span class="error">This is an error</span>
                    </div>
                    <div class="bottom">
                        <div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
                        <input type="submit" value="Register"></input>
                        <a href="index.html" rel="login" class="linkform">You have an account already? Log in here</a>
                        <div class="clear"></div>
                    </div>
                </form>
                <form class="login active">
                    <h3>Login</h3>
                    <div>
                        <label>Username:</label>
                        <input type="text" name="username"/>
                        <span class="error">This is an error</span>
                    </div>
                    <div>
                        <label>Password: <a href="index.php" rel="forgot_password" class="forgot linkform">Forgot your password?</a></label>
                        <input type="password" name="password" />
                        <span class="error">This is an error</span>
                    </div>
                    <div class="bottom">
                        <div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
                        <input type="submit" value="Login"></input>
                        <a href="index.php" rel="register" class="linkform">You don't have an account yet? Register here</a>
                        <div class="clear"></div>
                    </div>
                </form>
                <form class="forgot_password">
                    <h3>Forgot Password</h3>
                    <div>
                        <label>Username or Email:</label>
                        <input type="text" name="forgotuser" />
                        <span class="error">This is an error</span>
                    </div>
                    <div class="bottom">
                        <input type="submit" value="Send reminder"></input>
                        <a href="index.php" rel="login" class="linkform">Suddenly remembered? Log in here</a>
                        <a href="index.php" rel="register" class="linkform">You don't have an account? Register here</a>
                        <div class="clear"></div>
                    </div>
                </form>
            </div>

I want to submit the current form data.

                $form_wrapper.find('input[type="submit"]')
                         .click(function(e){
                            e.preventDefault();
                              $.ajax({
                                    url: 'locallogin.php',
                                    type: 'POST',
                                    data: $(this).serialize(),
                                    success: function (results) {
                                      alert(results);
                                    }
                                    });
                         });

locallogin.php

<?php
print_r($_POST);
?>

Currently, the response is just an empty Array. Any solutions?

Answer №1

There are a couple of issues that need to be addressed. One, as mentioned in the comments, is the use of $_POST.

Another issue can be found in the following code snippet:

data: $(this).serialize(),

The problem here is that $(this) is referring to the button element, resulting in the serialization of the button itself. To fix this, modify the code like so:

data: $(".register").serialize(),

Answer №2

Just a reminder, don't forget to update the $(this) to $("#form_wrapper") and change $POST to $_POST. Here's how your JS code should be modified:

$('#form_wrapper').find('input[type="submit"]')
.click(function(e){
    e.preventDefault();
    $.ajax({
        url: 'locallogin.php',
        type: 'POST',
        data: $(this).closest('form').serialize()+'&buttonName='+$(this).val(),
        success: function (results) {
            alert(results);
        }
    });
});

Once you've addressed the question regarding the button name, remember to include the additional code in the ajax call's data line.

Answer №3

Initially, the serialization of $(this) is being done in the click event of an input element. Consider utilizing

data: $(this).closest('form').serialize()
instead. Additionally, ensure to correctly include the underscore in print_r($_POST).

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

What is the best way to verify the number of values stored within a variable in JavaScript?

My goal is to calculate the sum of 6 values by inputting them into a single field using a button. To achieve this, I am seeking knowledge on how to determine the number of values contained within a variable. This will allow me to implement an "if" conditi ...

The best way to consistently execute setTimeout in order, regardless of the timing, is by utilizing a Promise

I have the following code snippet: var timeOne = new Promise(function(resolve,reject) { setTimeout(function(){ console.log('This is one'); }, Math.random() * 1000); }); var timeTwo = new Promise(function(resolve,reject) { s ...

What could be causing the angular Data table to not display properly?

I am currently exploring Angular Datatables and have a question about re-rendering the datatable after it has been hidden. Can anyone provide guidance on how to achieve this? In my project, I have two components - Parent and Child - that can be hidden or ...

What is the best way to generate bootstrap rows from this code in React JS?

In my current array of objects, I have twelve items: { data:[ { type:"tweets", id:"1", attributes:{ user_name:"AKyleAlex", tweet:"<a href="https://twitter.com/Javi" target="_blank"> ...

I am interested in scraping a webpage, how should I go about it?

Similar Questions: How to create a web crawler? Top techniques for parsing HTML I've always been curious about accomplishing a task like this. Although I do not own or manage the website (), the information I am interested in is publicly acce ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Updated server configurations have resolved the issue with duplicate email script malfunctioning

I'm encountering an issue with a simple form on my website that is supposed to prevent users from entering the same email twice and validate it as a valid email address. It was working fine until I migrated my site to a new server, after which it stop ...

What is the best way to convert an object to JSON and transmit it to a web service?

Is there a way to convert an object into json and then send it to a web service? var object = something.... function BindJson() { $.ajax({ type: "POST", url: "NewPage.aspx/GetJson", data: "{}", conte ...

What is the best way to achieve a full width table in an HTML format on a smartphone browser?

Apologies for my limited English proficiency. I am currently working on creating a horizontal scrollable table in HTML. My goal is to make the width of the table span beyond the browser's viewing area, so that sticky cell functionality can be implem ...

"Implementing a Jquery event to handle the closing of a select

Is there a way for me to detect when the select tag is closed by clicking on the screen elsewhere? I can easily hook into the change event of the select fine, which will close the select. However, other methods such as body click, body focus, select blur, ...

Remove the javascript file once the modal dialog has been closed

One of the challenges I'm facing is with a modal dialog that has been customized to appear on the right side of the customer's browser. Depending on the icon clicked in the navigation bar, an ajax call is made and an HTML fragment is loaded into ...

Trouble with useEffect not triggering in NextJS 13.4 (app router) application

When trying to fetch data from the next API route, I encountered an issue where the useEffect method did not trigger on page reload. Additionally, I was unable to make this component async as Next.js does not allow async functions in client components. pa ...

Trouble with innerHTML in a for loop when using getJSON

My current challenge involves displaying a series of JSON results within a div tag using innerHTML. <script> $(document).ready(function() { var html2 = ''; var thread_id = ''; var created_thread_ids ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

Tips on how to extract particular JSON information from an HTTP request by utilizing jQuery

I am attempting to extract the exchange rate from the JSON http response below by using jquery. Assume that jquery has already been included within the <head></head> tags. { "Realtime Currency Exchange Rate": { "1. From_Currency Co ...

Having trouble with the basic function of jQuery radio buttons, unable to make them work properly

Struggling with my first attempt at incorporating jQuery into my project. I have set up 2 radio buttons on a form, and I want the selected option to update the value of an input text box within the same form. However, despite my best efforts, I just can&ap ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...

Unsuccessful Invocation of Servlet by Ajax Function

I have a situation where I am trying to trigger an Ajax javascript function from my jsp file, with the intention of loading a servlet for further processing. The issue I am facing is that even though I am able to pass values from the jsp to the ajax functi ...

What is the best way to retrieve the current font size of a link element?

Is there a way to determine the font size of an element in pixels or points? Are there alternative methods available to achieve this? I am looking to increase the size of <a href="...">MAKE ME BIGGER</a> by 130%, 140%, N% based on its current ...