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

Inappropriate functionality of jQuery Code

Take a look at Demo Gallery I'm encountering some bugs that I can't seem to resolve. In Safari, there's a flickering issue when hovering over other elements In Safari and Chrome, the images are not displaying at the correct size (270x128) ...

The proper way to close file descriptors on a terminated HTTP connection in a Node.js environment

I am currently experimenting with Node.js, where I am attempting to stream files from the filesystem over HTTP. However, my experience on an OS X Lion machine has been hindered by a buggy Apache Bench (ab) app that prematurely aborts connections. This issu ...

Surprising outcome of Vue

As a newcomer to vue.js, I am struggling with a side effect issue in a computed property. The unexpected side effect error is popping up when running the code below, and ESlint is pointing it out in the console. I understand the concept of side effects, bu ...

Encountering an issue with Meteor and node-celery: "Unable to access property 'slice' of null"

Check out the Github repository for reproducing this issue Run localhost:3000 to replicate the problem. In my setup with Meteor 1.4.4.1, I am utilizing the node-celery npm packages on the server side. Upon Meteor initialization, the client automatically i ...

What is the best way to modify this state without altering the original array?

I am seeking guidance on how to avoid mutating state in a specific scenario: In my React Hooks setup, I have a TodoList component that displays a list of TodoItems. Each TodoItem can be clicked to trigger a function called toggle, which switches its compl ...

Transform stereo sound to mono using JavaScript

Recently, I encountered an audio file in stereo with a .raw extension that needs to be converted into mono using Node. Despite my efforts, I haven't been successful in finding examples or libraries outlining the process. Any assistance on this matter ...

Tips for updating the selected date format in a Material Table component using React

In the context of using a material table in React, the columns set up are as follows: columns={[ { title: 'Name', field: 'name', type: 'string', }, ...

Validating Laravel emails with JavaScript blur and utilizing AJAX and jQuery

Looking for a way to validate a form in Laravel without hitting the submit button? I've tried some code, but only the email format validation seems to be working. Any tips on what I should do next? I'm new to Ajax. PS: When I enter a valid email ...

Encountered an error while trying to set up the route due to Router.use() needing

Within my app.js file, I have the following code: app.use('/', require('./routes')); //old routes app.use('/api', require('./api')); Additionally, I have an api folder containing an index.js file. This is what the ...

Node application experiencing issues retrieving SVG files during production

When testing my application locally, the svg files display correctly with the code below (Angular.js variables are used within curly brackets): <img ng-src="img/servant_{{servant.personality}}.svg" draggable="false"> However, once deployed on Herok ...

Tips for getting UpdateTargetId to function properly in Ajax.ActionLink!

Within the controller, I have a method like this: [HttpDelete] public void DeleteDocument(int id) { //Handling document deletion in the database } In the view, there is a call to a method that returns a partial view: @{ Html.RenderAction("GetDocument ...

The 'INSERT' command in SQL is duplicating the value instead of inserting it just once

Hey everyone, I've encountered a problem while working on a like system that captures and saves user likes in a database. The issue lies with the SQL INSERT statement as it seems to be duplicating entries instead of saving them as intended. I initial ...

Tips for transferring data and events between named views within Vue Router

I have a layout structured like this: .------------------------+----------------. | Current Tab Title | Controls | +------------------------+----------------+ | Tab1 Tab2 [Tab3] | +---------------------------------------- ...

Revealing a concealed element by sliding it upwards on a single page, then repeating the

Can someone assist me in achieving a specific effect on my website? I have a top banner section with a button at the bottom. When the button is clicked, a form should slide up into view. The form will initially be hidden. I also need the same effect at the ...

React does not allow objects as a valid child element. This error occurs when an object with keys {nodeType, data, content} is found

I am encountering an issue with displaying content from Contentful on the server component. Everything is functioning correctly with no runtime errors, but I am receiving this specific error message: "Objects are not valid as a React child (found: object w ...

Having trouble creating a report with an HTML screenshot using Protractor

Need assistance with generating reports using a html screenshot in Protractor. I have followed all the necessary steps but encountered an error. Any help would be appreciated. Here is my conf.js: // Sample configuration file. var HtmlReporter = require(& ...

What causes the cursor in an editable div to automatically move to the front of the div?

<div className="min-w-[600px] min-h-[36.8px]" > <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} > ...

Dynamic styles object for React components with inline styles

I have a styles object let styles = { step_div:{ height:'150px', } } I'm trying to display multiple div elements with different colors using React class Layout extends React.Component{ constructor(props) { super(props); ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...