Accessing form data from Ajax/Jquery in php using $_POST variables

Thank you in advance for any assistance on this matter.

I'm currently attempting to utilize Ajax to call a script and simultaneously post form data. While everything seems to be working correctly, the $POST data appears to come back blank when trying to echo or print it. Could someone please provide insight into what might have been overlooked here?

<form id="guestlist" name="guestlist">
<?php // Gather CLUBS data to send to guestlist script ?> 
<input type="hidden" name="gl_clubname" value="<?php echo $ptitle; ?>" />
<input type="hidden" name="gl_clubnumber" value="<?php echo $phoneno_meta_value; ?>" />
<input type="hidden" name="gl_clubemail" value="<?php echo $email_meta_value; ?>" />
<?php // Gather USERS data to send to guestlist script ?> 
<input type="hidden" name="gl_name" value="<?php echo $fullname;?>" />
<input type="hidden" name="gl_email" value="<?php echo $email;?>" />
<input type="hidden" name="gl_dob" value="<?php echo $birthday;?>" />
<input type="hidden" name="gl_propic" value="<?php echo $profile_url;?>" />

<div id="clubcontactleft">
<textarea id="clubmessage" name="gl_message" placeholder="Your message" rows="4" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/userreview.jpg');
 background-repeat:no-repeat; padding-left:40px; background-size:40px 94px; width:250px; margin-bottom:15px;"></textarea>
 <input type="text" name="gl_when" placeholder="Enquiry Date" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/calendaricon.jpg');
 background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
<input type="text" name="gl_phonenumber" placeholder="Phone Number" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/phonecall.jpg');
 background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
</div>
<div class="guestlistbutton"><a href="#" alt="Send Message" title="Send Message" class="calltoactionbutton">Send Message</a></div>
</form>


<script type="text/javascript">
    $(document).ready(function($){
        $(".guestlistbutton").on('click',function(event) {
            event.preventDefault();
            $("#clubcontactform").empty();
            var url = "http://www.xxxxxx.com/wp-content/themes/xxxxxx/guestlist.php"; // the script where you handle the form input.
            $.ajax({
                type: "POST",
                url: url,
                data: $("#guestlist").serialize(), // serializes the form's elements.
                success: function(data)
                {
                    $('#clubcontactform').append(data); // display response from the php script.
                }
            });
            return false; // prevent actual submission of the form.
        });
    });
</script>

Here is the included php file:

<?php
echo 'Including guestlist.php<br/>';
$gl_message = $_POST['gl_message'];
print_r($gl_message);
echo $gl_message;

?>

Appreciate your help!

Answer №1

It appears that everything is in order, but it seems you may have forgotten to include the jQuery file. Please add it and give it another try. If the issue persists, we can create a Jsfiddle to troubleshoot further.

Answer №2

Upon testing your code on my local machine, I encountered an issue displaying the error message "Caution provisional headers are shown". If you are experiencing the same message in your browser console, I suggest checking out this link for potential solutions: "CAUTION: provisional headers are shown" in Chrome debugger

Furthermore, it appears that the JavaScript functionality is working correctly. The problem may lie within your URL address. Consider attempting to submit your form to itself by combining the HTML and PHP code sections into a single file.

Answer №3

<div>
<form id="Get_FRm_Data">
/*
Some fields in use.....
/*
</form>
<button type="button" name="submit" class="submit_act">Click to Submit</button>
</div>
<script>
var file_link = window.location.protocol + "//" + location.host + "/foldername/";
$(document).on("click", ".submit_act", function ()
{
    var $this_value=$(this);
    $this_value.html("Processing...").prop("disabled",true);
    var $data_reference = new FormData($("#Get_FRm_Data")[0]);
    $data_reference.append("action", "file_process_name");
    $pathname = file_link + "filename.php";
    $.ajax({
        url: $pathname,
        type: 'POST',
        data: $data_reference,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (result, response)
        {
            console.log(result);
            if (response == "success")
            {
                $this_value.html("Submit").prop("disabled",false);
            }
        }

    });

});
</script>
<?php
if (isset($_POST['action']))
{
    $action_performed = $_POST['action'];
    if($action_performed=="file_process_name")
    {
        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

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

Is there a way to hide the <v-otp-input> field in a Vue.js application?

For more information, please visit https://www.npmjs.com/package/@bachdgvn/vue-otp-input <script> export default { name: 'App', methods: { handleOnComplete(value) { console.log('OTP completed: ', value); } ...

Angular 6 tutorial: Creating a dynamic side navigation bar with swipe and drag functionality using Angular Material/Bootstrap

I am currently working on implementing a vertical swipeable/stretchable side nav-bar with angular-material in angular 6. However, I have encountered an issue with mouse interactions for stretching the nav-bar. Below is the code snippet: Here is the HTML c ...

Having difficulty with processing SOAP response in PHP using simplexml

I'm using cURL to send a SOAP request and receive the following response: <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"> <wsa:To>http://www.w3.org/2 ...

Utilizing Google Fonts offline without the need for an API

Instead of relying on Google Fonts API to access a variety of fonts for my website, I took matters into my own hands. I downloaded a snapshot of fonts from this GitHub repository: https://github.com/google/fonts and transferred them to my web directory. T ...

What is the best way to choose all elements that fall between two specific elements?

Looking to grab content situated between two specific elements within an HTML structure. The HTML snippet in question is as follows... <h2>This is firsty</h2> <p>Some para</p> <ul> <li>list items</li> <li&g ...

jQuery quiz feature that allows for matching arrays with user selections to calculate scores efficiently

Help! I'm a beginner with jQuery Quiz and my brain is fried. Here's the JSFiddle link for reference: https://jsfiddle.net/CeeSt/644eqae3/16/ I'm struggling with matching the correct answer within an array of an array to the dynamically crea ...

Update gridview information with a redirect response

The print button in the grid view below opens a print page in a new tab. This is achieved using the following Java Script code: Java Script <script type="text/javascript"> function SetTarget() { document.forms[0].target = "_blank"; ...

Reordering sections in a dynamic manner

I'm working on a single-page website with four sections arranged like this: <section id=“4”> <section id=“3”> <section id=“2”> <section id=“1”> Now, I want to change the order of these sections when scrolling ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

Uncertainty surrounding asynchronous file uploads in Python

Looking to implement asynchronous file uploads for a website that runs on a combination of Python and JavaScript. I've found several informative posts on the topic, but they all recommend different methods, leaving me confused about which one to choos ...

Symfony 3.4 is not compatible with installing dotenv via composer

I am currently working on a Symfony 3.4 project and I'm encountering some issues while trying to install the Dotenv component. After running the command composer require symfony/dotenv:^3.4, Composer indicates that there is "Nothing to install update. ...

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

Switch between Light and Dark Modes effortlessly with just one button

I've created a code that effortlessly switches between light mode and dark mode with the press of buttons. However, I'm looking to combine these two functionalities into a single toggle button for ease of use. If anyone can provide insight on how ...

JQuery Multiple Selection

Can someone please explain how to execute a multi match in jQuery? For example, matching id = a + num + b + num or id = a + num + c + num (where num ranges from 1-99). Any assistance would be greatly appreciated. Thank you. if($(this).attr("id").match(/ ...

Refresh the emberJS layout following an ajax call

I've been attempting to send a custom action to my server using ajax and then update the EmberJS model in the callback. Here's what my controller code looks like: PlatformUI.CampaignItemController = Ember.ObjectController.extend({ actions: { ...

Leveraging the power of Javascript/jQuery to manipulate form

On my website, I have implemented a form that requires a customized response for certain zip codes. To achieve this, I am developing a code that validates the first 3 digits of the entered zip code against a predefined array in my system. Although the code ...

Issue with IE preventing Selenium from triggering Onchange event and causing page to fail to Postback

I am currently working on a web application where selecting an item from one drop-down list triggers the loading of another. However, when using Selenium to automate this process, I have encountered an issue where the page post back is prevented and the se ...

Steps for capturing a screenshot of the canvas while utilizing the react-stl-obj-viewer component

I recently started using a component called react-stl-obj-viewer to display a 3D STL image. The rendering of the image itself is working fine. However, I encountered an issue when trying to move the rendered image around and implement a button for capturin ...