Issues arise when attempting to send an AJAX POST request within WordPress

After going through multiple resources, all mentioning the same approach that I am following, I have two essential files for this process:

In the receiver.php file:

<?php 
    add_action( 'wp_enqueue_scripts', 'my_enqueue' );
    add_action( 'wp_ajax_my_action', 'theActionFunction' );

function my_enqueue() {
    wp_register_script( 'ajax-script', plugins_url( '/src/WyrRoute.js' , __FILE__ ), array('jquery') );
    wp_enqueue_script('ajax-script');
    wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
function theActionFunction(){
   $theQuestion = $_POST['question_id'];
   echo $theQuestion; //doesn't show anything in the frontend
   wp_die();
}
echo "hello" //works if outside the function

The problem arises when nothing within the theActionFunction is being displayed on the frontend. Anything typed outside appears without trouble. There seems to be a fundamental aspect that I might be overlooking.

WyrRoute.js

clickHandler(e) {
    var ajax_url = my_ajax_object.ajax_url
    var data ={
        'action': 'my_action',
        'question_id': '10183'
    }
    $.ajax({
        type: 'POST',
        url: ajax_url,
        data: data,
        dataType: 'json',
        success: function (xhr, x, checkStatus) {
            console.log(xhr);
            console.log(checkStatus.status)
            console.log("success")
        },
        error: function(e) {
            console.log(e.statusText);
            console.log("failure")
        }
    });
}

Despite receiving a 200 success message from Ajax, I am unable to extract the value using $_POST['value'] and display it on the frontend using PHP.

Answer №1

Greetings. Upon reviewing the code, everything seems to be in order. One observation I made is that you have defined a function called "theActionFunction", but it appears that you have not invoked it anywhere in your code. To ensure that the function executes properly, consider adding this line right after its declaration:

theActionFunction();

By implementing this change, your code should now resemble the following:

function theActionFunction(){
   $theQuestion = $_POST['question_id'];
   echo $theQuestion; // This print statement will now function as expected
   wp_die();
}

theActionFunction();

Best of luck with your coding endeavors.

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

Tips for creating synchronous AJAX requests

Although I understand that Ajax functions asynchronously, my current code is not working and I require assistance in finding an alternative solution. The situation is as follows: I am inserting data into my database using the following function: self.in ...

Design an expansive dropdown menu in Wordpress that stands apart from the traditional navigation bar

Seeking help with creating a full-width dropdown menu that functions independently from the main navigation, triggered by a specific navigation item. The current setup involves using the Bootstrap accordion component to show/hide the dropdown. The problem ...

Running npm start in a React development environment on Linux without automatically opening a browser can be achieved by configuring

As I dive into learning React, I've noticed that I keep running npm start in the terminal multiple times. However, it can be quite frustrating how a new browser window opens each time. I'm currently attempting to prevent this from occurring on my ...

jQuery Ajax error: unexpected token!

I've been attempting to retrieve a JSON file using the following code: $.ajax('/file.json', { contentType: 'application/json', dataType: 'jsonp', success: function (data) { console.log(data); }, ...

The jQuery Cookie is failing to be set with every click as expected

I am currently working on a layout switcher feature. When a user clicks on a specific div with the class name display, it triggers the toggling of another class called display-grid for visual enhancements. This functionality also involves switching classe ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

Creating an extensive amount of HTML content through the use of JSON

When I request data from my API, it returns JSON objects which then populate numerous divs with content. However, I find myself continuously using concatenation to insert object properties. Is there a more efficient method for achieving this? $.each(JSO ...

Is AJAX the key to securing Paypal Payflow Transparent Redirect with SecureToken?

Currently, I am developing a C# MVC application within the VS2012 Framework 4.5 to ensure PCI compliance using Payflow Pro from PayPal (https://pilot-payflowpro.paypal.com). We have been utilizing PayflowPro for an extended period, and this is the tool we ...

Apply a specific image layout once the drop event occurs

I have a container with 5 image pieces that need to be dropped into another container to complete the image. Once an image is dropped, I want to apply the style "position:absolute" so that it sticks to the previous image in that container. Although I have ...

`Angular RxJS vs Vue Reactivity: Best practices for managing UI updates that rely on timers`

How can you implement a loading spinner following an HTTP request, or any asynchronous operation that occurs over time, using the specified logic? Wait for X seconds (100ms) and display nothing. If the data arrives within X seconds (100ms), display i ...

Strategies for removing duplicate items from an array of objects

My array consists of objects with the following structure: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', 'de ...

Change the term to its corresponding translation

I have developed an Ionic Multilingual App that includes a select feature. Within this select, choosing a specific option disables certain page elements. However, I am facing an issue where one of the elements needs to change its text based on the selected ...

CodeIgniter encountering an issue with inserting AJAX data

I've encountered an issue while inserting data into the database using CodeIgniter Controller. The problem arises when all the form fields are filled, and upon clicking any input field after that, the data gets inserted without even pressing the "Save ...

Is it possible to replicate a stale closure similar to React's useEffect hook without the use of the useEffect hook?

I have a good understanding of closures, but I am struggling to grasp how a stale closure can be created in React's useEffect without providing an exhaustive dependencies array. In order to explore this concept further, I am attempting to replicate a ...

Is it possible to transmit image form data to a PHP function in order to facilitate uploading?

Trying to implement image upload using both jquery and PHP: Here is the HTML code snippet: <form id="form-photo" enctype="multipart/form-data">< <span class="btn btn-small fileinput-button"> <span>Add Photo</span> < ...

Enhancing the background of a website with the power of CSS

I am looking to create a customized table without the balls/pots in it. The number of rows on the y-axis will vary depending on the number of names I have, and can be more or less. The values on the x-axis are determined by a parameter included in the URL ...

Laravel: The current configuration does not support the experimental syntax 'classProperties' at this time

When compiling my javascript files using npm run dev, I encountered a warning in my resource/app.js file where I require my custom validation script. The warning stated the following: Module build failed (from ./node_modules/babel-loader/lib/index.js): Syn ...

What is the process for converting this Greasemonkey code to JavaScript specifically for Android devices?

Having trouble loading a page and running a JavaScript code on it? Don't worry, you're not alone. I came across a Greasemonkey script that does the trick, but now I'm struggling to make it work on Android. It's probably because of my la ...

Is it possible for an animation to complete even if it is stopped midway?

I am currently working on a media player project where I have implemented a scrolling marquee effect for the song meta information using JavaScript and CSS. The scrolling effect only occurs when the track is playing, and I achieve this by adding/removing ...