I'm setting up a plugin. Now I'm trying to get an AJAX-PHP code working but I don't get the succeed data and all end with an error.
tracker.php is the main plugin file.
This is the function on my tracker.php that prints the title and some HTML code:
require_once dirname(__FILE__) . '/user-listing.php';
function trez_tracker_user_listing(){
?>
<h1>Tracker - User List</h1>
<div class="clicker">Click here</div>
<div id="printer"></div>
<?php
}//trez_tracker_user_listing
So in user-listing.php I added the following code:
function user_listing_enqueuer() {
wp_register_script( "ajax_user_request", WP_PLUGIN_URL.'/tracker/script/ajax_user_request.js', array('jquery') );
wp_localize_script( 'ajax_user_request', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_user_request' );
}
add_action( 'init', 'user_listing_enqueuer' );
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
add_action("wp_ajax_user_fetcher", "user_fetcher");
And finally the javascript code in /script/ajax_user_request.js:
/* ajax_user_request.js */
jQuery(document).ready( function() {
jQuery(".clicker").click( function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "user_fetcher"},
success: function(response) {
if(response.type == "success") {
jQuery("#printer").html(response)
}
else {
alert("AJAX error")
}
}//success
})//jQuery.ajax
})//Clicker function
})//document ready
When clicking on the <div>, I just get the alert message "AJAX error".
How can I fix it?
Thank you!
You are getting the error because you are not returning the JSON data, you are return string through your user_fetcher function.
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
Change the user_fetcher function so that it will return the JSON data to the AJAX call.
function user_fetcher(){
$result = 'Message to display';
echo json_encode(array('type'=>'success', 'message'=>$result));
die(0);
}//user_listing
And in jquery check the response like this:
success: function(response) {
if(response.type == "success") {
// Add message
jQuery("#printer").html(response.message)
}
else {
alert("AJAX error")
}
}//success
For the hook wp_ajax_user_fetcher, make sure you are using this after logged in, if you are not logged in in the admin section then you have to use wp_ajax_nopriv_user_fetcher. Or you can use both:
// Work if user is login
add_action("wp_ajax_user_fetcher", "user_fetcher");
// Work if user is not login
add_action("wp_ajax_nopriv_user_fetcher", "user_fetcher");
Related
i have worked for wordpress project which need to call back some result from database via ajax .
the problem is the response will be in string form which is not as i aspect .
here is whats my try :
//The PHP
function edit_something() {
if ( isset($_REQUEST) ) {
global $wpdb;
$ID = intval( $_REQUEST['ID'] );
$query= "SELECT * FROM `TABLE` WHERE `ID` = '$ID';";
$result= $wpdb->get_results( $queryHavadesEnsani, 'ARRAY_A' );
print_r( $resultsHavadesEnsani );
}
}
die();
}
add_action( 'wp_ajax_edit_something', 'edit_something' );
and the endpoint
function myplugin_ajaxurl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'myplugin_ajaxurl');
at the end the jquery
function sendAjax( ID ) {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
'action' : 'edit_something',
'ID' : ID
},
success:function(data) {
console.log(data)
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
i realy need your guidance
more info :
i also tried json_encode for php and JSON.parse for js but error the response will be Object object .
I guess instead of "echo" you should use wp_send_json_success
https://developer.wordpress.org/reference/functions/wp_send_json_success/
How to call ajax in Wordpress
I have odd (for me) problem with ajax in Wordpress. I do not receive proper response from server. I read Wordpress Codex to find out what I doing wrong, but still I have no clue.
I don't know if it is important or not, but when I tried add a type to ajax syntax, I received an error message.
class databaseClass
{
function __construct()
{
if ( isset($_SERVER['HTTPS']) )
$protocol = 'https://';
else
$protocol = 'http://';
wp_enqueue_script( 'ajaxScript', '/wp-content/themes/bulk/js/ajaxScript.js');
wp_localize_script( 'ajaxScript', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php', $protocol ),
'nonce' => wp_create_nonce( '111')
) );
add_action('wp_ajax_save_sort', 'ajaxFunctionInPHP');
add_action( 'wp_ajax_nopriv_save_sort', 'ajaxFunctionInPHP');
}
function ajaxFunctionInPHP(){
/*check_admin_referrer();
$response['custom'] = "ssss";
$response = json_encode($response);
wp_send_json($response) ;*/
ob_clean();
$response['custom'] = "TEST";
echo $response;
die();
}
}
class ajaxClass extends databaseClass
{
function __construct()
{
parent::__construct();
}
public function ajaxPage()
{
echo '<form name="ajaxTest" type="POST">
<input id="ajaxButton" type="button" value="KLIK"/>
</form>
';
}
}
jQuery( document ).ready( function () {
jQuery('#ajaxButton').click(function() {
var dataFromFunction="";
jQuery.ajax({
url: my_ajax_object.ajaxurl,
type: 'POST',
data: {
action: 'save_sort',
order: dataFromFunction
},
success: function (response){
console.log("success message");
console.log(response.custom)
},
error: function (response){
console.log("error message");
}
});
});
} );
success message
ajaxScript.js?ver=5.0.4:15 undefined
Your code seems to be correct but I am sharing my personal approach to doing this in hopes that this might be helpful. Make changes to JS as mentioned below:
jQuery( document ).ready( function ($) {
$('#ajaxButton').click(function() {
var dataFromFunction="Test Data";
$.ajax({
url: my_ajax_object.ajaxurl,
type: 'POST',
data: {
action: 'save_sort',
order: dataFromFunction
},
}).done( function (response){
console.log("success message");
console.log(response.custom)
}).fail(function (response){
console.log("error message");
}).always(function(){
console.log('Ajax Completed');
});
});
});
Also for your script localization, it is good to define the scheme parameter in admin_url function but not necessary so 'ajax_url' => admin_url( 'admin-ajax.php') should be just fine.
You seem to have created nonce but haven't used it and a good practice would be to use create nonce function in your form section and not in localization.
I do have a suggestion for your ajax response function but this is just an advice. Change your function to return as follows:
function ajaxFunctionInPHP(){
$response['dataFromFunction'] = sanitize_text_field($_POST['dataFromFunction']);
wp_send_json( $response);
}
Good Luck!!
hi i am unable to call my ajax function in codeigniter , below is my script :
whenever i click edit button from my data table i got error (Error get data from ajax) , could u pls help me where i am doing wrong.
<script type="text/javascript">
var save_method;
function edit_question(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
// document.write("test");
//Ajax Load data from ajax
$.ajax({
// document.write("test");
url : "<?php echo base_url('index.php/test_cont/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="question_id"]').val(data.question_id);
// $('[name="cid"]').val("<?php //echo $a; ?>");
$('[name="cid"]').val(data.cid);
$('[name="ques"]').val(data.question);
// $('[name="opa"]').val(data.options);
// $('[name="opb"]').val(data.options);
// $('[name="opc"]').val(data.options);
// $('[name="opd"]').val(data.options);
$('[name="ra"]').val(data.answer);
$('[name="marks"]').val(data.marks);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Questions'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
i have a controller name test_cont , here's code :
public function ajax_edit($id)
{
$data = $this->m->get_by_id($id);
echo json_encode($data);
}
public function question_update()
{
$data = array(
'course_id'=>$this->input->post('cid'),
'question'=>$this->input->post('ques'),
'marks'=>$this->input->post('marks'),
'options' => $options,
'answer' => $this->input->post('ra'),
);
$this->m->question_update(array('question_id' => $this->input->post('question_id')), $data);
echo json_encode(array("status" => TRUE));
}
I have this button:
bla bla
This button is located on my homebage and is generated by a page builder. What I want to accomplish is when somebody click on the button, it will take them on the checkout, and add a product to the cart. I know that this can be accomplished via a URL, but I need to have this button do other things as well(client idea).
So right now I'm stucked here:
JQuery
jQuery(document).ready(function($){
$(".remove-all").click(function(){
$.ajax({
url: "wp-admin/admin-ajax.php",
data: 'myajax'
});
});
});
PHP
add_action('wp_ajax_myajax', 'myajax');
add_action('wp_ajax_nopriv_myajax', 'myajax');
function myajax() {
global $woocommerce;
$product_id = 264;
$woocommerce->cart->add_to_cart($product_id);
die();
}
I'm a javascript noob, so can you please point me to the right direction, or maybe give me a hint on what I'm doing wrong.
Thanks in advance!
As I mentioned in the comments, you can pretty much borrow from core WooCommerce functions.
First, here's the button we'll be trying to ajaxify:
bla bla
Secondly, we'll load our custom script and pass it important variables such as the admin ajax and checkout urls.
add_action( 'wp_enqueue_scripts', 'so_load_script', 20 );
function so_load_script(){
wp_enqueue_script( 'so_test', plugins_url( 'js/test.js', __FILE__ ) );
$i18n = array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'checkout_url' => get_permalink( wc_get_page_id( 'checkout' ) ) );
wp_localize_script( 'so_test', 'SO_TEST_AJAX', $i18n );
}
Now we will write our ajax callbacks, which is copied almost verbatim from WooCommerce core with only a few small modifications:
add_action('wp_ajax_myajax', 'myajax_callback');
add_action('wp_ajax_nopriv_myajax', 'myajax_callback');
/**
* AJAX add to cart.
*/
function myajax_callback() {
ob_start();
//$product_id = 264;
$product_id = 34;
$quantity = 1;
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
$product_status = get_post_status( $product_id );
if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity ) && 'publish' === $product_status ) {
do_action( 'woocommerce_ajax_added_to_cart', $product_id );
wc_add_to_cart_message( $product_id );
} else {
// If there was an error adding to the cart, redirect to the product page to show any errors
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id )
);
wp_send_json( $data );
}
die();
}
And finally the contents of test.js:
jQuery(document).ready(function($){
$(".test-button").click(function(e){
e.preventDefault(); // Prevent the click from going to the link
$.ajax({
url: wc_add_to_cart_params.ajax_url,
method: 'post',
data: {
'action': 'myajax'
}
}).done( function (response) {
if( response.error != 'undefined' && response.error ){
//some kind of error processing or just redirect to link
// might be a good idea to link to the single product page in case JS is disabled
return true;
} else {
window.location.href = SO_TEST_AJAX.checkout_url;
}
});
});
});
You likely need to cancel/prevent the default action of clicking the link, and then redirect once the AJAX call finishes (this is just one way to do it):
jQuery(document).ready(function($){
$(".remove-all").click(function(e){
e.preventDefault(); // Prevent the click from going to the link
var $redirect = $(this).attr('href');
$.ajax({
url: "wp-admin/admin-ajax.php",
data: 'myajax',
success: function () {
window.location.href = $redirect;
}
});
});
});
PHP
add_action('wp_ajax_myajax', 'myajax');
add_action('wp_ajax_nopriv_myajax', 'myajax');
function myajax() {
$product_id = 264;
// Avoid using the global $woocommerce object
WC()->cart->add_to_cart($product_id);
die();
}
In the latest version of wp I created a theme, on the index.php page I have the following HTML:
<p><input type="hidden" name="GreetingAll" id="GreetingAll" value="Hello Everyone!" /> <input type="submit" id="PleasePushMe" /></p>
<div id="test-div1"></div>
My theme functions.php file, I added the following functions:
function add_myjavascript(){
wp_enqueue_script( 'js', get_template_directory_uri().'/lib/js/js.js', array( 'jquery' ));
//wp_localize_script( 'js', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'add_myjavascript' );
function MyAjaxFunction(){
//get the data from ajax() call
$GreetingAll = $_POST['GreetingAll '];
$results = "<h2>".$GreetingAll."</h2>";
// Return the String
die($results);
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_MyAjaxFunction', 'MyAjaxFunction' );
My JavaScript js.js:
jQuery(document).ready(function() {
var GreetingAll = jQuery("#GreetingAll").val();
jQuery("#PleasePushMe").click(function(){
jQuery.ajax({
type: 'POST',
url: 'http://localhost/brenda/wordpress/wp-admin/admin-ajax.php',
data: {
action: 'MyAjaxFunction',
GreetingAll: GreetingAll,
},
success: function(data, textStatus, XMLHttpRequest){
alert(data);
jQuery("#test-div1").html('');
jQuery("#test-div1").append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
My Ajax request works fine:
---------------
Request Method:POST
Status Code:200 OK
Form Data
action:MyAjaxFunction
GreetingAll:Hello Everyone!
---------------
Inside my admin-ajax.php the do_action fires. I echoed out a message in plugin.php to test to see if it was firing. However my function MyAjaxFunction() does not get executed. Note the add_actions are carried out, I tested that. My output into the target test-div1 is zero, which is the default status, see below.
if ( is_user_logged_in())
{
do_action( 'wp_ajax_' . $_REQUEST['action'] ); // Authenticated actions
}
else
{
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ); // Non-admin actions
}
//Default status
die('0');
Content-Type - application/json
in file /wp-admin/admin-ajax.php
test send data ($_POST, $_REQUEST...)
if necessary, apply a fix
$headers = getallheaders();
if (strpos($headers['Content-Type'], 'application/json') !== false) {
$input = json_decode(file_get_contents("php://input"), true);
$_REQUEST['action'] = $input['action'];
}
inserted after
/** Load WordPress Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );
here ...