I've been reading questions about this problem for a little over a week now, and have tweaked my code to try every answer but have not found a working solution yet. I created a very basic plugin and at this point, I'm just trying to get the response to come through. Here's what I have starting with the main php file:
<?php
add_action('init', 'letsgo');
function letsgo() {
wp_register_script('profile', plugin_dir_url(__FILE__ ) . 'js/profile.js', array('jquery'));
wp_localize_script('profile', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
wp_enqueue_script('profile');
}
function tecprofile() {
$result = array(
'verify' => 'yes'
);
echo json_encode($result);
die();
}
add_action('wp_ajax_tecprofile', 'tecprofile');
add_action('wp_ajax_nopriv_tecprofile', 'tecprofile');
?>
And profile.js:
$(document).ready(function() {
$.ajax({
type: "post",
url: myAjax.ajaxurl,
data: {action: 'tecprofile'},
dataType: 'json',
success: function(response){
console.log(response.verify);
},
error: function(xhr, status, error) {
console.log('error');
}
});
});
All I get in the console is "error."
Any advice or help would be huge, thanks!
Related
I have the following situation trying to use Ajax in Wordpress.
1. The file to be called has only a tiny code like: <?php echo "Whatever" ?>
2. it is to be called to and by button onclick:
<button id="ajaxbtn" onclick="showPopup()" class="btn-shape"></button>
<div id="ajax-input"></div>
3. Functions.php
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data() {
wp_localize_script('ajax-wear', 'myajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');
function tablo() {
ob_start();
get_template_part(get_stylesheet_directory_uri() . 'extra-wear' );
$result = ob_get_contents();
ob_end_clean();
$return = array('content' => $result);
wp_send_json($return);
wp_die();
}
4. Jquery
jQuery("#ajaxbtn").click(function() {
jQuery.ajax({
type: 'post',
dataType: 'json',
url: myajax.ajax_url,
data: {
action: 'tablo'
},
success: function(response) {
jQuery('#ajax-input').html(response.content);
}
});
});
5. Present output.
In the console there is information that XHR finished loading: Post "http//....." but nothing is really posted.
Has someone any idea what could be wrong with that code? my quess is point. 3
Any good advise highly appreciated.
get_stylesheet_directory_uri() is apparently not a correct way to build a path to call a file in that function. Once amended the content returned.
For what I see, you have two problems:
the dataType: 'json' parameter, most probably because you're not sending data in a json format
the "response.content" should be just "response"
Also, no idea if the URL you pass in "myajax.ajax_url" has been declared before this bit of code?
One more thing, "success" is depreciated since jQuery 1.8, and you should now use done() instead.
With all of that considered, how about trying this and see if it works?
$.ajax({
type: 'post',
url: 'path/to/your-ajax-file.php',
data: { action: 'tablo' }
}).done(function(response) {
console.log(response);
$('#ajax-input').html(response);
});
I added a console.log(response); line in the function so you can also see the result in your JavaScript console, remove it once your script works!
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.
So for my AJAX tabs I have the following script:
<script>
jQuery(document).ready(function() {
jQuery('.royal_private_menu a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'my_tab_menu', id: tab_id}),
success: function(data){
jQuery('#private_menu_'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
</script>
I got following error with url: "wp-admin/admin-ajax.php" and the error is example.com/wp-admin/admin-ajax.php?action=my_tab_menu 404 Not found.
Then I changed it to the following and got the same error: url: "admin_url('admin-ajax.php')" then, example.com/admin_url('admin-ajax.php');?action=my_tab_menu 404 Not found.
What is going on and what am I doing wrong?
Thanks
EDIT
Here is my files:
So I feel like I am really close to getting Ajax working but I am getting an error:
Here is php:
<div class="royal_private_menu">
Items
Received Order
My orders
Points
Setting
</div>
<div id="private_menu"> <!--Default page -->
<?php get_template_part('page-parts/03_private_items'); ?>
</div>
<div id="private_menu_received_order_id"> </div>
<div id="private_menu_my_orders_id"> </div>
<div id="private_menu_points_id"> </div>
<div id="private_menu_setting_id"> </div>
<script>
jQuery(document).ready(function() {
jQuery('.royal_private_menu a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: 'html',
data: ({ action: 'my_tab_menu', id: tab_id}),
success: function(data){
jQuery('#private_menu_'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
</script>
And in my function.php:
function my_tab_menu() {
$template_part_path = 'page-parts/03_private_' . $_GET['id'];
get_template_part($template_part_path);
}
add_action('wp_ajax_my_tab_menu', 'my_tab_menu');
add_action('wp_ajax_nopriv_my_tab_menu', 'my_tab_menu');
And here is my file names:
03_private_items.php
03_private_my_orders.php
03_private_points_id.php
03_private_received_order_id.php
03_private_setting_id.php
EDIT 2
I changed the success to alert("Success!"); and I got the Success alert. So everything is working except it is not fetching any data from other php files. What am I missing?
EDIT 3
With console.log(data);, this is the script that I see in the console:
jQuery(document).ready(function() {
jQuery('.royal_private_menu a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "http://example.com/wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'royal_private_tab', id: tab_id}),
success: function(data){
jQuery('#private_menu_'+tab_id).html(data);
console.log(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
Then I changed it to the following and got the same error: url: "admin_url('admin-ajax.php')" then, example.com/admin_url('admin-ajax.php');?action=my_tab_menu 404 Not found.
If the URL contains the literal string admin_url('admin-ajax.php'); then that means you PHP isn't being parsed.
Try:
url: "<?php echo admin_url('admin-ajax.php'); ?>",
You can also use wp_localize_script to set the ajax URL when you enqueue a script:
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
https://codex.wordpress.org/AJAX_in_Plugins#Separate_Javascript_File
In this case you would set the URL like this:
url: ajax_object.ajax_url,
The advantage of doing it this way is that you don't have to inline your javascript; you can just enqueue a JS file like you normally would.
From the comments:
So, when I went to example.com/wp-admin/admin-ajax.php I get "0" on a blank page. And that is exactly what is shown on the console on the ajax tab page. Is it normal?
Getting a 0 result either means your hook is not attached to the action or your hook generates no output and fails to exit.
In your JS, you're setting your action like this:
action: 'royal_private_tab'
In your PHP your declaring your hooks like this:
add_action('wp_ajax_my_tab_menu', 'my_tab_menu');
add_action('wp_ajax_nopriv_my_tab_menu', 'my_tab_menu');
You need to either use royal_private_tab or my_tab_menu in both places, ex:
add_action('wp_ajax_royal_private_tab', 'my_tab_menu');
add_action('wp_ajax_nopriv_royal_private_tab', 'my_tab_menu');
Also, you should exit at the end of your hook:
function my_tab_menu() {
$template_part_path = 'page-parts/03_private_' . $_GET['id'];
get_template_part($template_part_path);
exit;
}
I am trying to insert into DB data from an ajax query. When I test the function with simple text it works :
array('reference_id'=> 'test'),
array('checkin_time'=> 'test'),
but my PHP variables do not while they are correct (tested by alert(), they are both strings)
array('reference_id'=> $calendartime),
array('checkin_time'=> $reference_id),
Here is the full code in my template functions.php:
wp_enqueue_script('jquery');
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
function addCheckin(){
global $wpdb, $calendartime, $reference_id;
$calendartime = $_POST['calendar_time'];
$reference_id = $_POST['reference_id'];
if($wpdb->insert('checkin',
array('reference_id'=> $calendartime),
array('checkin_time'=> $reference_id),
array( '%s'),
array( '%s') )===FALSE){
echo "Error";
}else {}
die();
}
add_action('wp_ajax_addCheckin', 'addCheckin');
add_action('wp_ajax_nopriv_addCheckin', 'addCheckin');
And the jquery :
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data:{
action: addCheckin,
reference_id: $('.reference input').val(),
calendar_time: calendar
},
success: function(response) {
alert(response);
},
error: function(){
alert("failure");
}
});
Thanks for your help
Your WordPress Insert seems to be wrong. It should be:
$wpdb->insert('checkin',
array('reference_id' => $calendartime,
'checkin_time' => $reference_id),
array( '%s', '%s') )
I also think your AJAX post JavaScript should be like:
$.post( MyAjax.ajaxurl, {
data:{
action: addCheckin,
reference_id: $('.reference input').val(),
calendar_time: calendar
},
success: function(response) {
alert(response);
},
error: function(){
alert("failure");
}
});
Update : I added the following code to my theme header.php (It was for a page using Contact Form 7) :
<script type='text/javascript' src='/wp-content/plugins/contact-form-7/includes/js/jquery.form.min.js?ver=3.40.0-2013.08.13'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var _wpcf7 = {"loaderUrl":"\/wp-content\/plugins\/contact-form-7\/images\/ajax-loader.gif","sending":"Sending ..."};
/* ]]> */
</script>
<script type='text/javascript' src='/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=3.5.2'></script>
and now it works with the following code :
var data = {
'action': 'form',
'reference_id': $('.reference input').val(),
'calendar_time': calendar
};
$.post( form.ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
Hope it will help
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.