Passing data attribute from Ajax to PHP using Wordpress - php

I am developing a WordPress plugin and I am trying to pass a variable from function.php(ajax) to pass_userid.php. Both files are inside my plugin folder. I am attempting to pass the data attribute from function.php(ajax) to pass_userid.php but it did not send the data and received error 500.
Plugin structure:
-plugin folder
--function.js
--pass_userid.php
This is my function.php
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function custom_ajax(){
?>
<script>
jQuery(document).ready(function( $ ) {
$('[data-source-id="13487"]').on("load", function() {
$('[data-source-id="13487"]').contents().find('button.button.ld-gb-gradebook-component-grade-add').click(function() {
var ajaxurl = "https://<?php echo $_SERVER['HTTP_HOST'];?>/wp-content/plugins/gradebook-custom/pass_userid.php";
var user_id = $('[data-source-id="13487"]').contents().find('.ld-gb-gradebook-component-overall-grade').attr('data-user-id');
alert(user_id);
$.ajax({
type: 'POST',
url: ajaxurl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {
'action' : 'call_userid',
'userid' : user_id},
success: function(data)
{
console.log("data pass success!");
},
error: function(errorThrown){
console.log("no data pass!");
}
});
});
});
});
</script>
<?php
}
add_action('wp_head', 'custom_ajax');
?>
This is pass_userid.php:
<?php
function call_userid(){
if(isset($_REQUEST)){
$testing = $_REQUEST["userid"];
console.log("Test 123");
}
}
add_action("wp_ajax_call_userid", "call_userid");
add_action("wp_ajax_nopriv_call_userid", "call_userid");
?>

Related

Can not pass variable from jquery to php

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 );
}

Using Ajax and PHP in wordpress

Hi guys i am new to wordpress and ajax , i use this code for checking an input value before submitting the form :
$j("#ninja_forms_field_75").focusout(function(){
var content = document.getElementById("ninja_forms_field_75").value;
$j.ajax({
url : 'check.php',
data : {'mid':content},
type : 'POST',
success : function(resp){
if(resp == '1'){
//success message or whatever
},
error : function(resp){
alert("some error occured !");
}
});
});
problem is i dont know where shall i put that php file to work with database...
please help me!!!
pardon my english...
Inside your js file write your code above:
javascript.js
$j("#ninja_forms_field_75").focusout(function() {
var content = document.getElementById("ninja_forms_field_75").value,
my_data = {
'action': 'my_action',
'mid': content
};
$j.ajax({
url: ajaxurl,
data: my_data,
type: 'POST',
success: function(resp) {
if (resp == '1') {
//success message or whatever
},
error: function(resp) {
alert("some error occured !");
}
});
});
});
Then the php part begins, I prefer to store it inside the functions.php if it's just one ajax request. If it is more than one create a file like ajax-handler.php and include it inside your functions.php
functions.php
if ( defined( 'DOING_AJAX' ) ) {
include_once( 'ajax-handler.php' );
}
ajax-handler.php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'wp_ajax_my_action', 'my_custom_ajax_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_custom_ajax_action' );
function my_custom_ajax_action() {
$result = 'Hello';
wp_send_json( $result );
}
You can try in the functions.php, I have made a form by steps and I do it on functions.php in yout theme directory.

$.ajax( type: “POST” POST method to php file

I'm trying to use the POST method in jQuery to send mobile to a php file called save.php. So this is the code in the html page:
<script>
function saveit(userid){
var number = userid;
number = number.replace(/[^0-9.]/g, "");
var transaction = sendNumber(number);
if(transaction === '0'){
//alert("Transaction Successfull");
console.log('Success');
}else{
console.log('Failed');
}
userid=userid;
$.ajax({
type: "POST",
url: "./ajax/save.php",
data: { userid: userid },
beforeSend: function ( ) {
}
}).done(function ( data ) {
alert("Vielen Dank, Sie wurden erfolgreich registriert");
window.history.back();
if( console && console.log ) {
console.log("Sample of data:", data);
}
});
return false;
}
</script>
My question is now, what should I write in save.php to see all the numbers?
You will need a server running, are you doing this on your own computer via xampp or similar, or do you have a hosting provider ?
<?php echo $_POST['userid']; ?>

AJAX (admin_url('admin-ajax.php');?action=) Not Found

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;
}

add php variable into wordpress mysql query

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

Categories