Im having an issue with calling ajax from front of my wordpress site The data just dose not go through to the other file when the ajax is called on change. The value in ajax this.value is passed ok from .
<?php
function my_enqueue()
{
wp_enqueue_script('ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery'));
wp_localize_script('ajax-script', 'my_ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'my_enqueue');
....
<script>
jQuery('#courseid').on('change', function() {
jQuery.ajax({
type: 'POST',
url: '<?= get_template_directory_uri(); ?>/inc/ssc/public_ajax_options_topics.php',
data: {
action: 'g6_options_topics',
product_id: this.value
}
}).done(function(data) {
jQuery("#topicid").html(data);
});
});
</script>
This is the file that response is send to
<?php
require_once('../../../../../wp-load.php');
$mysqli = db();
$product_id = 0;
if ($_POST['product_id']) {
$product_id = $_POST['product_id'];
}
Related
add_action( 'wp_footer', function () { ?>
<script type='text/javascript' id='ajax'>
const ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
async function httpRequest(url = '', data = {}, method = 'POST') {
const response = await fetch(url, { method: method,
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cache-Control': 'no-cache',
},
body: new URLSearchParams(data)
});
return response.text();
}
document.querySelector('#roll-title-btn').addEventListener('click', async function() {
const searchTerm = document.getElementById('roll-title');
if (searchTerm.value.trim().length) {
const result = await httpRequest(ajaxUrl, { action: 'filter_ajax', 'roll-title': searchTerm.value });
console.log(result);
}
})
</script>
<?php } );
add_action( 'wp_ajax_nopriv_filter_ajax', 'filter_ajax' );
add_action( 'wp_ajax_filter_ajax', 'filter_ajax' );
function filter_ajax() {
echo "TESTING";
wp_die();
}
Whenever I am trying to send an HTTP request it is throwing 400 bad requests and prints 0 as result. Trying to implement a filter plugin but the above code snippets aren't working at all. I have tried multiple solutions from StackOverflow but none worked.
Here I am sharing my working code which I was developed by today so you can check here.
//First I enqueue script using action in function.php file
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
//Then I localize custom js for admin ajax
wp_localize_script( 'custom-js', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
//I choose action and javascript object "my_ajax_object"
//Now I create custom.js as per mentioned above path
$(function(){
$('#capture').click(function(){
//capture is button id.
//here is the ajax call
var value = '123';
jQuery.ajax({
type: "post",
dataType: "HTML",
url: my_ajax_object.ajax_url,
data : {action: "my_ajax_object","value":value},
success: function(msg){
console.log(msg);
}
});
});
});
//Now I wrote ajax function
add_action( 'wp_ajax_nopriv_my_ajax_object', 'my_ajax_object' );
add_action( 'wp_ajax_my_ajax_object', 'my_ajax_object' );
function my_ajax_object()
{
$value = $_POST['value'];
$response = '<p>value is '.$value.'<p>';
return $response;
wp_die();
}
I sent an ajax request by a button, ajax requests work perfectly also responding. I checked the browser Network it is fine. My problem is I am not getting value by PHP request. Here is my code given below:
function my_enqueue(){
wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ) . '/assets/js/awqvCustom.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
/* Custom Ajax */
function data_custom_ajax(){
if ( isset($_POST)) {
$id = $_POST['id'];
echo $id;
}
die();
}
add_action('wp_ajax_nopriv_data_custom_ajax', 'data_custom_ajax');
add_action('wp_ajax_data_custom_ajax', 'data_custom_ajax');
/* Modal Markup*/
function modalBody(){?>
<div class="my-modal">
<div id="ajax_result"></div> //getting ajax success value here
<?php
$getId = (isset($_POST['id']) ? $_POST['id'] : '');
echo $getId; //nothing get
?>
</div>
<?php }
add_action('get_footer', 'modalBody');
jQuery ajax code:
jQuery(document).ready(function () {
'use strict';
jQuery(".btn-container").on('click','.open-modal', function(e){
e.preventDefault();
var id = jQuery(this).data('id');
jQuery.ajax({
type: "POST",
url: my_ajax_object.ajax_url,
dataType:"json",
data: {
action: 'data_custom_ajax',
id: id,
},
cache: false,
success: function(data){
if(data !=''){
jQuery('#ajax_result').html(data);
var modal = jQuery(".my-modal").wgModal();
modal.openModal();
}
}
});
});
I checked with the debugger. The ajax variables seem to be sent
Hello everyone I am trying to use ajax in my custom plugin for wordpress but got an issue in my console showing 400 bad request in admin-ajax
JS scripts
public static function register_script(){
wp_enqueue_script('ajaxscript', substr(plugin_dir_url(__FILE__), 0, -10) . '/assets/js/register-post.js', array( 'jquery', 'json2' ), '1.0.0', true );
wp_localize_script( 'ajaxscript', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajaxnonce') ) );
}
Ajax
function signup(){
// alert("working");
jQuery('#registration').on('submit', function(e) {
var data = jQuery("#registration").serialize();
e.preventDefault();
// e.stopPropagation(); // only neccessary if something above is listening to the (default-)event too
jQuery.ajax({
type: 'POST',
url: my_ajax_object.ajax_url,
processData: false,
data: {
action: 'register_ajax_request&nonce='+ my_ajax_object.nonce,
data: data
},
dataType: 'json',
success: function(response) {
if(response.success === true) {
// jQuery("#vote_counter").html(response.vote_count)
}else {
// alert("Your vote could not be added")
}
}
});
});
}
Registration Function
<?php
add_action('wp_ajax_register_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_nopriv_register_ajax_request', 'ajax_handle_request');
function ajax_handle_request(){
if (isset($_POST['register_trigger'])){
$nonce = $_POST['nonce'];
print_r($nonce);
exit();
}
}
Location of the registration.php is plugindirectory/inc/pages/. This is not a function.php like the wordpress theme.
Sorry I just forgot to include a php file that the action is looking for.
AJAX Post is not returning success call in wordpress. I have the following code and I can get to the first dialog box in testing, but no mater what I do its not getting to the second. It's not finding the function in functions.php even though I have it declared.
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var datastring = $("#redemmpointsForm").serialize();
var points = $('#points').val();
var comments = $('#comments').val();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {"action": "redeempoints", "points":points},
success: function(response) {
if(response.type == "success") {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
functions.php file
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
die();
return true;
}
add_action("wp_ajax_functionRedeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints");
Ok so i treid the following
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var allData = {
action: 'functionRedeempoints',
points: points,
comments:comments
}
var data = JSON.stringify(allData);
alert( data);
jQuery.ajax({
type : "post",
dataType : 'json',
url : myAjax.ajaxurl,
data : data,
success: function(response) {
if(response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
And iN MY FUCNTIONS php Its like its not fidning the php function.
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
wp_send_json_success(true);
}
add_action("wp_ajax_redeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_redeempoints", "functionRedeempoints");
The problem is that your function functionRedeempoints does not return anything that the ajax call can handle.
It just dies even before the return statement.
Also a return by the PHP end will never actually be interpreted by the JS. JS can only read from the http request, so you need to actually write to it by an echo statement.
Wordpress provides a convenient way of handling this for you:
What you need would be something like:
function functionRedeempoints() {
wp_send_json_success(true);
}
This already takes care of stopping execution and properly JSON encoding your response.
Also the correct response handling on the JS side is a little different than in your example code.
You can find the details on this here:
https://codex.wordpress.org/Function_Reference/wp_send_json_success
But what it boils down to is that the success is encoded in the result.success property of the response.
Hence you want your check to be
if(response.success)
instead of if(response.type == "success")
With these changes your example should work though :)
Working example ( in plugin form) based on your code:
Put this in hello.php in the plugins folder
<?php
/*
Plugin Name: Ajax demo
*/
function test_load_js() {
wp_register_script( 'ajax_demo', plugins_url( 'hello.js' ), array( 'jquery' ) );
wp_localize_script( 'ajax_demo', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'ajax_demo' );
}
function functionRedeempoints() {
wp_send_json_success( true );
}
add_action( "wp_ajax_functionRedeempoints", "functionRedeempoints" );
add_action( "wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints" );
add_action( "init", "test_load_js" );
if ( ! defined( 'DOING_AJAX' ) ) {
echo '<input type=button value="send" id="send_btn">';
}
Put this in hello.js in the plugins folder
jQuery(document).ready(function () {
jQuery("#send_btn").click(function () {
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var data = {
action: 'functionRedeempoints',
points: points,
comments: comments
};
alert(JSON.stringify(data));
jQuery.ajax({
type: "post",
dataType: 'json',
url: MyAjax.ajaxurl,
data: data,
success: function (response) {
if (response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
});
Hope this helps you to get a start here, works just fine when you click the button that should appear on the upper left of your admin screen ( zoom in ;) )
I want to send an AJAX request in WordPress which tracks my clicks. So far, I have added this in my functions file:
add_action('init', 'my_script_enqueuer');
function my_script_enqueuer() {
wp_register_script("history_script", get_template_directory_uri() . '/js/history_script.js', array('jquery'));
wp_localize_script('history_script', 'myAjax', array('ajaxurl' => get_template_directory_uri().'/functions.php'));
wp_enqueue_script('jquery');
wp_enqueue_script('history_script');
}
add_action("wp_ajax_history_trace", "history_trace");
function history_trace() {
echo 'fasfasgasgas'; die;
}
And this in my js file :
jQuery(document).ready( function() {
jQuery("#searchsubmit").click( function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "history_trace"},
success: function(response) {
if(response.type == "success") {
alert('success')
}
else {
alert("false")
}
}
})
})
})
But in my console, the request appears in red, and there is no response. Please Help!
In WordPress, use the following url to process AJAX requests:
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
It's also important to localize a script after it has been enqueued.