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

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

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

How to load wp ajax for not logged users?

I understand I should be using wp_ajax_nopriv as per the doc says
but I am not sure how tho.
On the front end I do:
var ajaxscript = { ajax_url : '<?php echo admin_url("admin-ajax.php"); ?>' };
$.ajax({
url: ajaxscript,
type: 'post',
dataType: 'json',
data: { action: 'data_fetch', dates: datesSearch },
success: function(data) {
...
}
});
I know I could define the url in function like:
function myAjaxUrl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'myAjaxUrl');
And that would make the ajax call on the front end like:
$.ajax({
url: ajaxurl...
But how would I use the wp_ajax_nopriv in order to be able to access wp-ajax for not logged in users?
All you need to do is just register your function to a hook named as wp_ajax_nopriv_{your_function_name}
So, for your case, add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' ); should do the trick.
Registering an ajax function in WordPress:
1. Registering an ajax function in WordPress: You can add this in the theme functions.php file.
// Simple Ajax function
add_action( 'wp_ajax_nopriv_simple_ajax_func', 'simple_ajax_func' );
add_action( 'wp_ajax_simple_ajax_func', 'simple_ajax_func' );
function simple_ajax_func() {
echo json_encode(array('success' => true));
wp_die();
}
2. Calling that ajax function from JavaScript:
var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
jQuery.ajax({
url : ajax_url,
type : 'post',
data : {
action : "simple_ajax_func",
},
success : function( response ) {
console.log('Success');
}
});
you misunderstand the wp_ajax action.
You must create a PHP function inside your theme using the wp_ajax filter.
add_action( 'wp_ajax_foobar', 'my_ajax_foobar_handler' );
add_action( 'wp_ajax_nopriv_foobar', 'my_ajax_foobar_handler' );
// This is the function that you will fire when your ajax code hits the admin_url('admin-ajax.php')
function my_ajax_foobar_handler() {
// Make your response and echo it.
// Don't forget to stop execution afterward.
wp_die();
}
So, for the WP admin ajax understand that need to fire this function, you must pass it inside your ajax request.
//Note that the action here is what cames after the wp_ajax PHP function
var my_php_ajax_action_name = 'foobar'
$.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data: { action: my_php_ajax_action_name, dates: datesSearch },
success: function(data) {
// ...
}
});

Wordpress make Ajax call to my theme

This is my situation: I have a slide, like the image below, that needs to be responsive. This slide was created from scratch and its working fine, however it's not responsive.
In order to be responsive I need to know the width of the screen of the user so instead of showing 4 slides, I show 3, 2 and 1 (if its a phone).
With that said, I need my slider to be loaded through ajax and I will pass through params the user screen width.
My theme folder is structured this way:
wp-contents/themes/my-theme
...functions.php
...header.php
...footer.php
...index.php
...single.php
I need to make a Ajax call to functions.php to a function that I have created. So I added the following:
add_action('wp_ajax_posts_list', 'my_ajax_posts_list_handler');
function my_ajax_posts_list_handler()
{
echo 'hello, width: ' . $_POST['width'];
wp_die();
}
In the footer.php file I added some testing javascript code:
$(function()
{
var width = $(window).width();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; // Dunno what is this..
$.ajax(
{
url: ajaxurl,
data:
{
action: 'wp_ajax_posts_list',
width: width
},
type: 'GET',
success: function(response)
{
console.log(response);
}
});
});
My problems:
The URL being executed is this http://localhost/wordpress/wp-admin/admin-ajax.php?action=wp_ajax_posts_list
The URL response code is 400
The URL responde value is '0'
The action is actually called post_list. wp_ajax_ is just a prefix. You also should add the same action with prefix wp_ajax_nopriv_ otherwise it wil not work when you are logged out. I also see you do type: 'GET' in your javascript but use $_POST in your PHP. Do one of the two.
add_action('wp_ajax_posts_list', 'my_ajax_posts_list_handler');
add_action('wp_ajax_nopriv_posts_list', 'my_ajax_posts_list_handler');
function my_ajax_posts_list_handler()
{
echo 'hello, width: ' . $_POST['width'];
wp_die();
}
Here the JS:
<script>
$( function () {
var width = $( window ).width();
// var ajaxurl = "http://localhost/wordpress/wp-admin/admin-ajax.php"
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
$.ajax( {
url: ajaxurl,
data: {
action: 'posts_list',
width: width
},
type: 'POST',
success: function ( response ) {
console.log( response );
}
} );
} );
</script>

Load contents of alexa php results with parameters into html page - Maybe using jquery or ajax

I'm trying to load the alexa rank of a website as a piece of text into a standard html file. I want to avoid setting up the whole page as php so I've created a php file called rank.php which works
<?php
$url=$_GET["url"];
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$url);
$rank=isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
echo $rank;
?>
I can load this to my server and call it with something like rank.php?url=google.com
This returns a number on the screen (in this case 1). So how do I get that number into a normal <p> tag in a html document.
Ie <p>Alex rank: </p>
I'm looking into jquery and using the get method but I'm getting lost.
eg putting this in the <head></head> tags
<script>
$(document).ready(function(){
$("#div1").load("code/rank.php?url=google.com");
});
</script>
Then in my html page adding
<p>Alex rank: <div id="div1"></div></p>
doesn't work for me.
I've also tried adding the following script within the <p></p> tag.
<script type="text/javascript">
function showGetResult( name )
{
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
}
showGetResult('test');
</script>
I just want a simple solution to pull that number across.
Any help greatly appreciated.
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
I made some tests - and it seems that this is a culprit:
dataType: 'text/html'
Why:
in documentation of jQuery - at http://api.jquery.com/jQuery.ajax/
dataType allowed values:
"xml"
"html"
"json"
"jsonp"
"text"
multiple, space-separated values
I tried
dataType: 'text'
Worked for me.
Be sure to put your script tag after if you are executing it inline of your page
<p>Alexa rank: <span id="div-1"></span></p>
<script>
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
</script>
But cleaner way to do it:
<html>
<head>
<script>
// comment:
// in jQuery
// $( yourFunction )
// is a shortcut for
// $(document).ready( yourFunction )
$(function(){
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
});
</script>
</head>
<body>
<p>Alexa rank: <span id="div-1"></span></p>
</body>
</html>
In this last code I am using cache: false because I feel it is good for this case. I am using dataType: 'text' because you are expecting just a number - so why not? It just fells more KISS for me. Perhaps it will work with 'html'.
By the way - there can be another place where another mistake can be hidden:
code/rank.php?url=google.com
If you current URL is
www.example.com/somefolder/
then it will be interpreted as
www.example.com**/somefolder/**code/rank.php?url=google.com
If your current URL is www.example.com/somefolder/another/
then it will be interpreted as
www.example.com**/somefolder/another/**code/rank.php?url=google.com
My advise - you can always use Firefox or Google Chrome Developer Tools > Network to see what is returning your ajax request - a '1' or 'PAGE 404 NOT FOUND' ^_^
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
I made some tests - and it seems that this is a culprit:
dataType: 'text/html'
Why:
in documentation of jQuery - at http://api.jquery.com/jQuery.ajax/
dataType allowed values:
"xml"
"html"
"json"
"jsonp"
"text"
multiple, space-separated values
I tried
dataType: 'text'
Worked for me.
Be sure to put your script tag after if you are executing it inline of your page
<p>Alexa rank: <span id="div-1"></span></p>
<script>
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
</script>
But cleaner way to do it:
<html>
<head>
<script>
// comment:
// in jQuery
// $( yourFunction )
// is a shortcut for
// $(document).ready( yourFunction )
$(function(){
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
});
</script>
</head>
<body>
<p>Alexa rank: <span id="div-1"></span></p>
</body>
</html>
In this last code I am using cache: false because I feel it is good for this case. I am using dataType: 'text' because you are expecting just a number - so why not? It just fells more KISS for me. Perhaps it will work with 'html'.
By the way - there can be another place where another mistake can be hidden:
code/rank.php?url=google.com
If you current URL is
www.example.com/somefolder/
then it will be interpreted as
www.example.com**/somefolder/**code/rank.php?url=google.com
If your current URL is www.example.com/somefolder/another/
then it will be interpreted as
www.example.com**/somefolder/another/**code/rank.php?url=google.com
My advise - you can always use Firefox or Google Chrome Developer Tools > Network to see what is returning your ajax request - a '1' or 'PAGE 404 NOT FOUND' ^_^
Answering comment:
Yes, you've got the gist of it right.
Here is one way how you could implement it
(it would be comfortable for my way of thinking and organizing code):
<html>
<head>
<script>
// defining tool:
function updateRankForSite( inUrl, $inInsertTo ) {
$.ajax({
url: 'code/rank.php?url=' + inUrl,
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
$inInsertTo.html(data);
}
});
}
</script>
<script>
// using tool:
$(function(){
outputRankForSite( 'google.com', $('#rank-google') );
outputRankForSite( 'yandex.com', $('#rank-yandex') );
// and here is example how to interact with user
$('button-1').click( function( event ) {
// comment
// event.preventDefault() blocks default behavior
// for clicking on ... tag
// that means you wouldn'd be redirected to href
event.preventDefault();
outputRankForSite(
'stackoverflow.com',
$('#rank-stackoverflow')
);
// comment:
// and you can leverage not just 'stackoverflow.com'
// but anything that user wants - he can
// put his request to <input="text" id="example-input" ...>
// and you could collect his input by using command like
// $('#example-input').val()
});
});
</script>
</head>
<body>
<p>Alexa rank for google.com: <span id="rank-google"></span></p>
<p>Alexa rank for yandex.com: <span id="rank-yandex"></span></p>
<p>
Alexa rank for stackoverflow.com (press button to get rank):
<span id="rank-stackoverflow"></span>
</p>
Press this button to update rank
</body>
</html>

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