Wordpress - backend AJAX call returning 0 - php

I have create a backend plugin for my website and I would like it to work with AJAX. But all I am getting from the AJAX response is readyState: 4 and responseText: 0.
script.js
jQuery(document).ready(function($){
$.ajax({
url: ajaxurl,
type: "POST",
data: {
action: 'my_action',
param: 'st1'
},
error : function(response){
console.log(response);
},
success : function(response){
console.log(response);
}
});
});
members_loop.php
add_action('wp_ajax_my_action', 'my_ajax_action_function');
add_action('wp_ajax_nopriv_my_action', 'my_ajax_action_function');
function my_ajax_action_function(){
$reponse = array();
if(!empty($_POST['param'])){
$response['response'] = "I've get the param a its value is ".$_POST['param'].' and the plugin url is '.plugins_url();
} else {
$response['response'] = "You didn't send the param";
}
header( "Content-Type: application/json" );
echo json_encode($response);
wp_die();
}
I am using three files inside my plugin to do this, I have my plugin.php file where I declare my plugin and enqueue my script.js file. Then I have a templates file with two folders inside it one being members_loop.php and the other index.php (The "homepage" for the plugin). Then I have an assets file with my script.js file. Not sure if this information is needed but I don't think my ajax call is wrong so I'm wondering what is going wrong.
Issue Update
I just cut and paste the my_ajax_my_action funciton and the actions to the plugin.php file where I declare the plugin and now it works. So how do I get it to work in an external file? do I have to require the members_loop.php file inside the plugin.php file?

If your file path is "/wp-content/plugins/your_plugin/members_loop.php", so inside file "plugin.php" add require_once plugin_dir_path( __FILE__ ) . 'members_loop.php'; or require_once dirname(__FILE__) . '/members_loop.php';

Related

Problem with my first basic wordpress plugin

I am trying to create my first worpress plugin!
Actually, the idea is when i click on the button, an ajax request is sent toward php file file (ajax-process.php ), it contains a very basic code to pull some data from database and then displaying it as an alert or other in my home page .
This is my plugin floder (inside wordpress plugins folder)
DB-Puller :
- DB-Puller.php
- ajax-process.php
And js (js_file.js) + css (css_file.css) folders.
Here what contains DB-Puller.php
<?php
/**
* Plugin Name: DB-Puller
* Plugin URI: https://my-web-site.com/
* Description: This is a my firt plugin, it(s allows to display data from database.
* Version: 0.1
* Author: Firest Last name
* Author URI: https://my-web-site.com/
* License: GPL3
*/
function scripts_files_enqueue_scripts() {
// Adding css file
wp_enqueue_style('css_file',plugins_url( 'css/css_file.css', __FILE__ ) );
// Adding JS file
wp_enqueue_script( 'js_file', plugins_url( 'js/js_file.js', __FILE__ ), array('jquery'), '1.0', true );
}
add_action('wp_enqueue_scripts', 'scripts_files_enqueue_scripts');
?>
And This what contains ajax-process.php
N.B : the database table is very basic, it contains just id + text columns
<?php
function my_ajax_action_callback()
{
if (isset($_POST['req']))
{
global $wpdb;
$quer = $wpdb->get_results( "SELECT * FROM wp_custom_table_1" );
$arr = $quer[0]->text;
echo $arr;
die();
}
wp_die(); // required. to end AJAX request.
}
What contains js file
jQuery(function($){
$('body').prepend('<button class="btn" type="button">PULL DATA</button>');
$('button.btn').on('click', function()
{
$.ajax({
url:'http://127.0.0.1/wp522/wp-content/plugins/DB-Puller/ajax-process.php',
method:'POST',
data:{
req:'',
action:'my_ajax_action',
},
success:function(data)
{
alert(data);
},
error:function()
{
alert(erooor);
}
})
})
})
The Alert is sent empty ! Please help me to detect where is the problem!
Thank you.
Looking on the code it does not seem like the Wordpress way of doing this kind of thing.
First you need to include your ajax-process.php in the plugins main file e.g:
require_once plugin_dir_path(__FILE__) . '/ajax-process.php';
Second, you need to register your ajax callback like this:
add_action('wp_ajax_my_ajax_action', 'my_ajax_function');
add_action('wp_ajax_no_priv_my_ajax_action', 'my_ajax_function');
Then register the ajaxUrl in scripts_files_enqueue_scripts() so it accessible from your javascript. The admin-ajax.php file handles all ajax requests:
wp_localize_script(
'js_file',
'ajax',
array(
'ajaxUrl' => admin_url('admin-ajax.php'),
)
);
Then in your javascript you need to use the ajaxUrl and specifying the action which will tell Wordpress which callback should be triggered:
jQuery(function($) {
$('body').prepend('<button class="btn" type="button">PULL DATA</button>');
$('button.btn').on('click', function() {
$.post({
url: ajax.ajaxUrl,
data: {
req: '',
action: 'my_ajax_action',
},
success: function(data) {
alert(data);
},
error: function() {
alert('error');
}
});
});
Here is a good article AJAX in Plugins, explaining how to use ajax in a plugin.

Ajax call not working out in wordpress

I referred to some examples online and modified functions.php and the front end template to fire an ajax call to fetch some data. But I've hard time understanding on hoe the data is returned from the requested url.
At the end of functions.php, I added,
wp_enqueue_script('jquery');
function myFunction(){
echo "hi";
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
add_action('wp_ajax_nopriv_myFunction', 'myFunction');
In my custom template page, I added,
var datavalue = 'test data string';
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: { 'datavar' : datavalue }
}).success(function(data) {
console.log("successfully run ajax request..." + data);
}).done(function(){
console.log("I am from done function");
}).fail(function(){
console.log("I am from fail function.");
}).always(function(){
console.log("I am from always function");
});
});
After running it, I get these response.
I am from fail function.
I am from always function
I don't understand how to fetch data from a specific url and display the result in ajax's success function.
I don't even know how the function defined in function.php would be called by this ajax call? How are they related?
Please explain. Also I would like to fire ajax call to query database by passing keyword, how can I do that in wordpress?
Your AJAX function should include an action parameter to tell admin-ajax which function you would like to execute.
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
}
(or, if you are set up for it, then you can include it in your url, as below)
url: "/wp-admin/admin-ajax.php?action=myFunction"
Also, your function in functions.php should be written in PHP:
function myFunction(){
echo 'hello';
die();
}
You have to use a action on ajax like.
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
'datavar' : datavalue,
}
});
PHP function need to edit.
function myFunction(){
echo 'success calling functions';
wp_die();
}
you are not passing the "action" parameter in "data". Which contains callback function's name. Please check the attached link.
https://www.sitepoint.com/how-to-use-ajax-in-wordpress-a-real-world-example/
In this you've to make a callback functions.
Wordpress dsnt work with the specific url.
But if you still want to use the specific url. Follow the steps:-
1. Make a wordpress template.
2. Add your specific url code there.
3. Make a page in the admin panel and assign the template you've created above.
4. Now the permalink of that page can be used as a specific url in the jQuery ajax.
In addition to above answers, in your function.php, make use of $_REQUEST. The $_REQUEST contains all the data sent via AJAX from the Javascript call. Something like this
function myFunction() {
if ( isset($_REQUEST) ) {
{
global $wpdb;
$keyword = $_REQUEST["keyword"];
if($keyword){
$query = "
SELECT `$keyword`, COUNT($keyword) AS Total
FROM `profileinfo` GROUP BY `$keyword`
";
$result = $wpdb->get_results($query);
$data = array();
foreach($result as $row)
{
$data[] = $row
}
echo json_encode($data);
}
}
}
die();
}
add_action( 'wp_ajax_myFunction', 'myFunction' );
add_action('wp_ajax_nopriv_myFunction', 'myFunction');

Call php function with Jquery in wordpress using xampp

I'm trying to do some basic stuff but my php code seems not to be called.
I have a button with an onclick event with points to a js function
<button type="button" onclick="tryphp()">go!</button>
and this is in my index.php file.
Then I have a subfolder called js with inside my js file and the function is as follows
function tryphp() {
jQuery.ajax({
url: 'php/try.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert('success!!!!');
}
});
}
finally, I have another subfolder "php" with inside my try.php
<?php
echo 'hello';
?>
I expect the button to fire a "success!!!!" when clicked but nothing happens.
I'm trying to figure out if the error is in the "url" paramether of the ajax call?
The file structure is as below
/main/index.php
/main/js/file.js
/main/php/try.php
Any help would be great!
Last but not least, my functions.php file is as follows
<?php
function newtheme_script_enqueue() {
wp_enqueue_style('style1', get_template_directory_uri() . '/css/newtheme.css', array(), '1.0.0', 'all');
wp_enqueue_script('script1',get_template_directory_uri() . '/js/newtheme.js', array(), '1.0.0', TRUE);
wp_enqueue_script('script1',get_template_directory_uri() . '/js/jquery.js', array(), '1.0.0', TRUE);
}
add_action('wp_enqueue_scripts','newtheme_script_enqueue');
and inside jquery.js I have downloaded the compressed version of jquery.
thanks in advance!
-----------UPDATE------------
SOLVED!
There were 2 mistakes:
-i did not specify the dependency in the script enqueue
wp_enqueue_script('script1',get_template_directory_uri() . '/js/newtheme.js', array('jquery'), '1.0.0', TRUE);
-the path to the php file was missing the "template directory" part
Thanks everybody!
First of all you have to know that Wordpress integrate ajax as well.
On file functions.php you must have the function that fires out results to ajax calls
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die(); // this is required to terminate immediately and return a proper response
}
And on your javascript file there should be something like:
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
Please read reference at this link that's made for plugins but works for themes as well.
If you make a lot of ajax requests, you might want to use something like this to help find problems:
jQuery.ajax({
url: 'php/try.php',
dataType: 'text',
success: function (response) {
console.log('Success: ' + response);
},
error: function (x) {
//loop though error response
$.each(x, function(y, z){
console.log('Error: ' + y + ' ' + z);
});
},
});
If you have an error somewhere in your php file you should see it after "Success" response in your console.log. If your url is incorrect you should see the error somewhere in the "Error" response - it's usually towards the end of the responses. (Unless you love the sound of your browser's alert, I would give your responses to console.log as the error response will produce quite a few alerts.)

How to make ajax call in yii2?

In yii version 1.14 we used
CHtml::ajaxlink
for ajax call what about in yii2?
You can make an ajax link like
Html::a('Your Link name','controller/action', [
'title' => Yii::t('yii', 'Close'),
'onclick'=>"$('#close').dialog('open');//for jui dialog in my page
$.ajax({
type :'POST',
cache : false,
url : 'controller/action',
success : function(response) {
$('#close').html(response);
}
});return false;",
]);
From: http://www.yiiframework.com/wiki/665/overcoming-removal-of-client-helpers-e-g-ajaxlink-and-clientscript-in-yii-2-0/
You can easily create and combine all such client helpers for your
need into separate JS files. Use the new AssetBundle and AssetManager
functionality with the View object in Yii2, to manage these assets and
how they are loaded.
Alternatively, inline assets (JS/CSS) can be registered at runtime
from within the View. For example you can clearly simulate the
ajaxLink feature using a inline javascript. Its however recommended if
you can merge where possible, client code (JS/CSS) into separate
JS/CSS files and loaded through the AssetBundle. Note there is no more
need of a CClientScript anymore:
$script = <<< JS
$('#el').on('click', function(e) {
$.ajax({
url: '/path/to/action',
data: {id: '<id>', 'other': '<other>'},
success: function(data) {
// process data
}
});
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
$.get( "' . Url::toRoute('controller/action') . '", { item: $("#idoffield").val()} ) /* to send the parameter to controller*/
.done(function( data )
{
$( "#lists" ).html( data );
})
and give lists id for div
<div id="lists"></div>
for more visit https://youtu.be/it5oNLDNU44
<?=yii\helpers\Url::toRoute("site/signup")?>

Contao 2.11 call to module via ajax

I have question about call to my module action via ajax.
I'd like call to class in my module via ajax. But best solution for me is call to clean class. Not extends Module.
I don't know hot can I make url without add article to database and add module to him.
I use JQuery instead mooTools but js framework is not important. Most important is call to php class by ajax.
I have ajax module. But if I call to ajax.php required is module id from tl_module table. I don't want use this table. (Ajax will be very often calling, I prefer to don't load all contao mechanism. It should be very fast).
Thanks in advance for answers.
I found the answer for Contao >3.x in a GitHub issuse(german)
At first do in your Front-end Template:
<script type="text/javascript">
var data = {};
data["REQUEST_TOKEN"] = "<?php echo REQUEST_TOKEN ?>";
$(document).ready(function(){
$("#trigger").click(function(event){
$.post(
'<?php echo \Contao\Environment::get('requestUri')?>',
data,
function(responseText) {
alert(responseText);
}
).fail(function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown )});
event.preventDefault();
});
});</script>
Important is the
- data["REQUEST_TOKEN"] -> if you do not add it, the POST-request will not reach your module:
public function generate()
{
if ($_SERVER['REQUEST_METHOD']=="POST" && \Environment::get('isAjaxRequest')) {
$this->myGenerateAjax();
exit;
}
return parent::generate();
}
//do in frontend
protected function compile()
{
...
}
public function myGenerateAjax()
{
// Ajax Requests verarbeiten
if(\Environment::get('isAjaxRequest')) {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array(1, 2, 3));
exit;
}
}
If you want to do the ajax via GET you do not need the reqest token but the jquery funktion $get();
I would suggest you to use Simple_Ajax extension.
In this case you dont need to use Database and you can do pretty much anything you can do normally with Jquery ajax calls.
It works with Contao 2.11 and you can call your php class with it.
I find it much easier to use than ajax.php .
You can get it from : https://contao.org/de/extension-list/view/simple_ajax.de.html
Copy SimpleAjax.php to Contao's root folder.
Go to [CONTAO ROOT FOLDER]/system/modules and create a php file like following :
class AjaxRequestClass extends System
{
public function AjaxRequestMethod()
{
if ($this->Input->post('type') == 'ajaxsimple' )
{
// DO YOUR STUFF HERE
exit; // YOU SHOULD exit; OTHERWISE YOU GET ERRORS
}
}
}
Create a folder called config with a php file like following ( You can hook you class to TL_HOOKS with class name - class method, simple_ajax will execute you method whenever a ajax call is made ):
$GLOBALS['TL_HOOKS']['simpleAjax'][] = array('AjaxRequestClass','AjaxRequestMethod'); // Klassenname - Methodenname
Now you can easily make ajax calls with simply posting data to SimpleAjax.php:
$.ajax({
type: "POST",
url: "SimpleAjax.php",
data: { type: "ajaxsimple" },
success: function(result)
{
//DO YOUR STUFF HERE
}

Categories