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
Related
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!
I want to pass a variable from jquery to PHP on the same page (I am using WordPress).
I tried using using ajax post like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("li.year-item a").click(function(){
$post = $(this);
$.ajax({
type : "POST",
url: "https://example.com/exhibition/",
data: {yearValue: $($post).attr("value")},
success: function (data) {
console.log(data);
}
})
});
});
</script>
and I get the post variable below the script tag:
<?php var_dump($_POST['yearValue']); ?>
but the var_dump result is null..
I have no idea.. anyone can help me? thanks in advance :)
In Wordpress you should use the built in Ajax mechanism.
$.ajax({
type : "POST",
url: "https://your-site.com/wp-admin/admin-ajax.php",
data: {
action: 'retrieve_yearvalue',
yearValue: $($post).attr("value"),
test: 'Test is ok'
},
success: function (data) {
console.log(data);
}
})
On PHP-Side:
add_action( 'wp_ajax_retrieve_yearvalue', 'my_year_retrieve_function' );
add_action( 'wp_ajax_nopriv_retrieve_yearvalue', 'my_year_retrieve_function' );
function my_year_retrieve_function() {
$yearValue = $_REQUEST['yearValue'];
$test = $_REQUEST['test'];
$response = array(
'recieved_year' => $yearValue,
'test_data' => $test
);
wp_send_json( $response );
}
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 ;) )
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;
}