how to create a plugin with ajax - ajax

Hi everyone I am trying to call a ajax function in my plugin, for this I saw this
tutorial But in my case never execute de ajax call.
First in the constructor I have this:
function __construct(){
add_action('init', array( $this, 'register_script'));
....
add_action('wp_ajax_aad_get_results', array($this, 'aad_process_ajax'));
}
function register_script(){
wp_register_script('myplugin', plugins_url('/includes/myplugin.js', __FILE__), array('jquery'));
wp_enqueue_script('myplugin');
wp_enqueue_script('add-ajax', plugin_dir_url(__FILE__).'includes/js/add-ajax.js', array('jquery'));
}
this function has to execute when I click in the buttom of this form
public function rbk_show_box( $post ) {
// get post meta values
$values = get_post_custom( $post->ID );
// echo '<input type="hidden" name="',$post->post_title.'_add_box_nonce" value="',wp_create_nonce(basename(__FILE__)),'" />';
echo '<form id="camposMeta" name="este" method="POST">';
echo'</form>';
echo '<form id="camposMeta" name="este" method="POST" >';
echo '<input type="hidden" name="',$post->post_title,'">';
echo '<fieldset id="campos1" class="clonedInput">';
echo '<label>Name</label>';
echo '<input type="text" name="name1" id="name1" />';
echo '<select name="select1" id="select1">';
echo '<option >Selecciona el tipo</option>';
echo '<option>Text</option>';
echo '<option>TextArea</option>';
echo '<option>File</option>';
echo '</select>';
echo'</fieldset>';
echo '<input type="button" id="btnAdd" value="+" />';
echo'<input type= "submit" id="btn_submit" value="Crear Meta Box">';
echo'</form>';
}
I create dynamic field in my form so now I need take all this field to create a metabook.
I know that a take my field like this:$('#camposMeta').serialize() but when I call the file createMetaBox.php to pass this params the program don't work!!
$('#btn_submit').click(function(){
alert('ready')
$.ajax({
// url: createMetaBox.php
data: {
action: 'aad_get_results',
//valores:$('#camposMeta').serialize()
},
success:function(){
}
});
});
any idea!!!

If you're using OO techniques, I suspect that your ajax hook should be like:
add_action('wp_ajax_aad_get_results', array( $this, 'aad_process_ajax' ) );
If you want the Ajax to execute for users who are not logged in(for example front end), you should also add:
add_action('wp_ajax_nopriv_aad_get_results', array( $this, 'aad_process_ajax' ) );

You have to post to the ajax url.
First localize your javascript after enqueing it, and make the ajaxurl available as a variable
wp_localize_script( 'quote_script', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
Then call your ajax with the ajax url variable
$('#btn_submit').click(function(){
$.ajax({
url: MyAjax.ajaxurl;
data: {
action: 'aad_get_results',
},
Also, if you echo from your php function, you'll need to do something with it in the ajax callback, eg
success: function(response) {
alert(response);
};

Related

Wordpress, admin menu, Ajax 400 bad request

I am trying to delete database row using button, (this is inside my plugin in admin area)
but i am not able to figure out why my ajax call is not working.
Every time i try i recive: 400 bad request all the time.
So i did not manage it yet to call the function properly
this is my button:
<button class="deletebutton" <?php echo 'value="' . $data->id . '"' ?> class="delete"> delete</button>
And i use:
add_action('wp_ajax_delete_data', 'delete_data');
MY function: (i know it work i have use it many times before
'function delete_data($element_id){
global $wpdb;
$tablename = $wpdb->prefix . 'my_table';
$wpdb->delete($tablename, array('id' => $element_id));
}'
And Jquery/AJAX <- here is the problem i think
<script>
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).ready(function() {
jQuery(".deletebutton").click(function(){
var element_id = this.value;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
action: 'delete_data',
data: element_id
dataType: 'data',
});
});
});
</script>
You have given the wrong actions name. see more information here
Change this line
`add_action('wp_ajax_worktmp_delete_absence', 'delete_data');`
With this
`add_action('wp_ajax_delete_data', 'delete_data');`
So the proper of doing this is
Create a separate js file or you can use it upon the existing js file like following while you are enqueuing your script:
wp_register_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . '{your_js_file_location}', array( 'jquery' ), $this->version, false );
wp_localize_script( $this->plugin_name, 'test_ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script($this->plugin_name);
Then
add_action('wp_ajax_delete_data', 'delete_data');
if it is for normal user hten add the folowwing as well
add_action('wp_ajax_nopriv_delete_data', 'delete_data');
Then in your js file
jQuery(document).ready(function($) {
$(".deletebutton").click(function(){
var element_id = this.value;
$.ajax({
url: test_ajax_object.ajaxurl,
type : 'post',
data : {
"action" : 'delete_data', "data_id":element_id},
success: function( response ) {
console.log(response);
}
});
});
});
And in your php file
function delete_data(){
global $wpdb;
$element_id = $_POST['data_id'];
$tablename = $wpdb->prefix . 'my_table';
$wpdb->delete($tablename, array('id' => $element_id));
}
This might work, try once

Laravel ajax is not returning success data

I am trying to achieve a functionality, If I select a category in dropdown, then in next dropdown, subcategory of that chooces category will appear. I wrote below ajax in script tag for it.
$("#category").change(function(e){
e.preventDefault();
var category = $("#category").val();
$.ajax({
type:'POST',
url:"{{ route('ajaxRequest.post') }}",
data:{category:category},
success:function(data){
alert(data.success);
$("#subcategory").replaceWith(data.subcats);
}
});
});
Here is my route setup for the same
Route::get('add_product', [dashboardController:: class, 'addProduct']);
Route::post('add_product', [dashboardController::class, 'getSubCategories'])->name('ajaxRequest.post');
This is my controller function
function getSubCategories(Request $request){
//$input = $request->all();
$subCategoryList = DB::table('ajax_categories')->where('pid', $request->post('category'))->get();
$sub = '<option desabled selected>Choose sub category</option>';
foreach($subCategoryList as $subCategory):
$sub .= '<option value="'.$subCategory->id.'">'.$subCategory->category.'</option>';
endforeach;
return response()->json(array(
'success' => 'Success',
'subcats' => $sub
));
}
Everything seems fine, I am not getting what causing it to be fail.
Screenshot of network tab
On clicking on checkbox, I got this in reponse
You are echoing result before returning response so ajax is not able to parse json properly.And other is csrf token not passed properly.
In ajax you can pass csrf token like below
data:{_token: "{{ csrf_token() }}",category:category},
instead of appending in controller better do like this
function getSubCategories(Request $request){
$subCategoryList = DB::table('ajax_categories')->where('pid', $request->post('category'))->get();
$view=(string)view('dropdown',['subCategoryList'=>$subCategoryList])
return response()->json(array(
'success' => 'Success',
'subcats' =>$view
));
}
in your view dropdown.blade.php you can
#if(isset($subCategoryList)&&count((array)$subCategoryList))
#foreach($subCategoryList as $key=>$value)
<option value="{{$subCategory->id}}">{{$subCategory->category}}</option>
#endforeach
#endif

Wordpress: AJAX not working

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

CakePHP AJAX call

I am using CakePHP and this is my first project on this framework. I am going to send the value of an input to UsersController's check_username() action. And fill an element having id na with the string returned by check_username(). So far what I did is:
//in my form
<input type="text" name="data[User][username]" style="width: 60%" required="required" id="username" oninput="check_username(this.value)">
<label style="margin-left: 20px; color: red" id="na">Not Available!</label>
//after the form
<script type="text/javascript">
function check_username(un) {
$.ajax({
type: 'POST',
url: '/oes/users/check_username',
data: {username:un},
cache: false,
dataType: 'HTML',
beforeSend: function(){
$('#na').html('Checking...');
},
success: function (html){
$('#na').val(html);
}
});
}
</script>
//and my check_username() is
public function check_username(){
return 'Test string';
}
But this isn't working. Anybody know why or how to modify it so that it works?
It could be problem with your check_username controller action. CakePHP-way is to use JsonView class to send any data throw XHR (see http://book.cakephp.org/2.0/en/views/json-and-xml-views.html). It allows you to call any action with .json extension (ex.: /oes/users/check_username.json) and get response in serialized JSON format without manual conversion beetween array data and JSON.
This method is recommended for your needs, but not obligated, of course.
Now I think that CakePHP tries to render check_username view, but could not do this because you have not specified or created it. Try to change your action code to something like this:
public function check_username(){
$this->autoRender = false;
echo 'Test string';
}
Also, try not to use such code construction in the future.
CakePHP has a JS Helper to help write aJax functions. The only catch is to include jquery in your head our cake will throw jQuery errors.
Your Form:
<?php
echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
echo $this->Form->input('username');
echo $this->Form->submit('Check Username');
echo $this->Form->end();
?>
The Ajax Function:
<?php
$data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourForm')->event(
'submit',
$this->Js->request(
array('action' => 'checkUsername', 'controller' => 'user'),
array(
'update' => '#na',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
)
);
echo $this->Js->writeBuffer();
?>
The Function in User Controller
function checkUsername(){
$this->autoRender = false;
//run your query here
if ( $username == true )
echo 'Username is taken';
else
echo 'Username is not taken';
}
There are many examples through google. Here is a good one to visit.

Using Ajax in WordPress

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 ...

Resources