I’m working on a WordPress project where I need to display some detailed data in a modal when a user clicks on a specific element. The content of the modal is fetched through an AJAX call to a PHP script that resides on the WordPress backend.
The element triggering the AJAX call is classed as "modal-trigger". When the user clicks on this element, the AJAX call fires, the PHP script processes the request, and should return the content to be displayed in the modal.
However, I’m running into an issue: whenever the AJAX call is made, I receive an HTTP 400 error. Here is the code I am using for the AJAX call:
jQuery(document).ready(function($) {
$(".modal-trigger").on("click", function() {
var type = $(this).data("type");
var month = $(this).data("month");
var data = {
action: 'get_fluxo_details',
type: type,
month: month
};
$.ajax({
type: 'POST',
url: fluxoAjax.ajax_url, // switched from ajax_object.ajaxurl to fluxoAjax.ajax_url
data: data,
success: function(response) {
// Insert the result into the modal
$('.modal-content p').html(response);
$("#myModal").show();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
$(".close").on('click', function() {
$("#myModal").hide();
});
$(window).click(function(event) {
var modal = document.getElementById('myModal');
if (event.target == modal) {
modal.style.display = "none";
}
});
});
And here is the corresponding PHP code in the backend:
function get_fluxo_details_callback() {
$type = $_POST['type'];
$month = $_POST['month'];
// Your code to fetch fluxo details here...
// Remember, you should echo the response, not return
echo $response;
wp_die(); // always necessary to finish the callback with wp_die();
}
add_action('wp_ajax_get_fluxo_details', 'get_fluxo_details_callback');
add_action('wp_ajax_nopriv_get_fluxo_details', 'get_fluxo_details_callback');
I have done some checks and it seems the JavaScript code is loaded correctly. I’ve also confirmed that the fluxoAjax object contains the correct URL for the WordPress AJAX API. However, whenever the AJAX call is made, the server returns a 400 error.
Any suggestions or help in resolving this issue would be greatly appreciated. Thank you.
I’ve implemented an AJAX call to fetch data on a button click, but I’m getting a 400 error instead of the expected data to populate a modal.
2
Answers
in browser inspect. then network tab
check the ajax request details.
then see if ajax sent to right url
You’re echoing $response, whereas the response variable is not set in PHP. Try
Replace
With
Or set a response variable first and then echo.