wordpress adding plugin for ajax - ajax

i am new to wordress. trying to test creating a plugin to combine my js and ajax for a module. I did the following:
[Not sure if i need to add anything in admin-ajax.php.]
created my new plugin under wp-content/pluging/test-plugin
created 2 files: test.php and test.js
test.php content as the following:
/**
* Plugin Name: Test
*/
add_action("wp_ajax_my_test", "my_test");
add_action("wp_ajax_nopriv_my_test", "my_test");
function my_test()
{
echo "in ajax";
}
add_action( 'init', 'test_script_enqueuer' );
function test_script_enqueuer() {
wp_register_script( "test", WP_PLUGIN_URL.'/my_plugin/test.js', array('jquery') );
wp_localize_script( 'test', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'test');
}
test.js code as the following:
$(document).ready(function()
{
console.log('in js!');
$('#testDiv').on('click', '#test', function()
{
console.log('clicked!');
jQuery.ajax(
{
type: 'POST',
url: myAjax.ajaxurl,
data:
{
action: 'my_test'
},
dataType: 'json',
cache: false,
success: function(response)
{
alert(response);
},
error: function(xhr, textStatus, errorThrown)
{
alert('error');
}
});
})
});
Note that I can't even see the "in js!" message in my console.

Change
add_action( 'init', 'test_script_enqueuer' );
to
add_action("wp_enqueue_scripts", "test_script_enqueuer");
But first, try to echoes something from your php file. If nothing happened your file isn't call.
Try then tell me.

Related

Wordpress Ajax returning full html of same page

Am trying to run Ajax call in my Woocommerce checkout page, but am always getting the full html of same page return.
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
wp_enqueue_script( 'theme_scripts', get_stylesheet_directory_uri() . '/assets/js/theme.js', array(), '1.0.0', true );
wp_localize_script( 'theme_scripts', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
Am calling the ajax when address is changed
add_action('wp_footer','my_custom_ajax');
function my_custom_ajax(){
?>
<script>
(function($){
$( document.body ).on( 'updated_checkout', function(){
$.ajax({
url: my_ajax_object.ajaxurl,
data: {
'action':'example_ajax_request',
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
})(jQuery);
</script>
<?php
}
The example Function
function example_ajax_request() {
echo 'ok';
wp_send_json_success( 'It works' );
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
Fixed by using 'nonce'
refer to this sample project

Wordpress AJAX Form

I have the oddest issue and I have a feeling I am missing something easy. I am trying to process a form through Wordpress and AJAX. But when pointed to the right url it gives me a 400 error. I have a feeling I have my action setup wrong or something. The processing function is a method in the same class called process_registration_form.
//JS
$('#user-registration').submit(function(e){
e.preventDefault();
var registrationForm = jQuery(this).serialize();
jQuery.ajax({
action: 'tribe_process_registration_form',
type: "POST",
url: tribe_process_user_registration.ajaxurl,
data: registrationForm,
success: function(data) {
console.log(data);
//jQuery("#feedback").html(data);
}
});
});
//PHP
wp_enqueue_script( 'tribe_process_user_registration', plugin_dir_url( __FILE__ ) . 'js/tribe-product-gifting-public.js', array( 'jquery' ) );
wp_localize_script( 'tribe_process_user_registration', 'tribe_process_user_registration', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action('wp_ajax_tribe_process_user_registration', array($this,'process_registration_form'));
add_action('wp_ajax_nopriv_tribe_process_user_registration', array($this,'process_registration_form'));
I don't thing there is any issue in the above code but might be i have missing something. so here is the way i can do my ajax call.
The enqueue the script file with wp function.
wp_enqueue_script( 'pc-frontend-js', plugins_url( 'Scripts/front-end.js', __FILE__ ), false );
wp_localize_script( 'pc-frontend-js', 'pc_var_arguments', array(
'woopb_nonce' => wp_create_nonce('woopb_nonce'),
'ajax_url' => admin_url('admin-ajax.php')
)
);
Ajax call
function callback_function(quantity) {
var condition = 'ajax_callback_condition';
jQuery.ajax({
url: pc_var_arguments.ajax_url,
type : 'post',
dataType: 'json',
data : {
action : 'ajax_callback_action',
condition :condition,
data : data,
},
success : function(response) {
console.log(response);
}
});
};
Hooks for ajax
add_action( 'wp_ajax_ajax_callback_action', array($this,'callback_function' ));
add_action( 'wp_ajax_nopriv_ajax_callback_action', array($this,'callback_function' ));

insert data in WordPress database as non-logged in user

I created a custom post type called 'visitor'. and I have an input in the front end. when the user saves input, I want to grab that data and post it as 'title' in my 'visitor' post type.
in functions.php-
$secureInfo= array(
'site_url' => get_site_url(),
'nonce' => wp_create_nonce("wp_rest")
);
wp_localize_script( "main-js", "data", $secureInfo);
in main.js-
sendUserInfo(){
var grabbingInfo = {
"title" : this.alertBoxInput.val() //my targeted input
}
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader("X-WP-Nonce", data.nonce);
},
url: data.site_url + "/wp-json/wp/v2/visitor", //custom post type
data: grabbingInfo,
type: "POST",
success: (res) => {
console.log("success");
console.log(res);
},
error: (res) => {
console.log("sorry");
console.log(res);
}
});
}
however, this code works for logged in user and says unauthorized for public users. but I don't care if a user is logged in or not. any suggestion?

Making an ajax call in wordpress, undefined variable

Im trying to open Wordpress posts in a modal popup by following this guide : https://premium.wpmudev.org/blog/load-posts-ajax/
However when I try I get an error saying : Uncaught ReferenceError: modalpost is not defined
I have this code in my functions file so far :
wp_localize_script( 'modal-post', 'modalpost', array(
'ajaxurl' => admin_url( 'modal-post.php' )
));
And this code in my js file :
(function($) {
$(document).on( 'click', '.itemtoshow', function( event ) {
event.preventDefault();
$.ajax({
url: modalpost.ajaxurl,
type: 'post',
data: {
action: 'modal-post'
},
success: function( result ) {
alert( result );
}
})
});
})(jQuery);
Any ideas what Im doing wrong ?
Many thanks in advance,
Scott
You have make some changes in your code like
wp_localize_script( 'modal_post', 'modalpost', array(
'ajaxurl' => admin_url( 'modal-post.php' )
));
to
wp_localize_script( 'modal-post', 'modalpost', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
Then in your jQuery
(function($) {
$(document).on( 'click', '.itemtoshow', function( event ) {
event.preventDefault();
$.ajax({
url: modalpost.ajaxurl,
type: 'post',
data: {
//action: 'modal-post' change function name here
action: 'modal_post'
},
success: function( result ) {
alert( result );
}
})
});
})(jQuery);
Now code response function in your plugin or functions.php file like
// Add hooks for handle ajax request
add_action( 'wp_ajax_nopriv_modal_post', 'model_post' );
add_action( 'wp_ajax_ajax_modal_post', 'model_post' );
function model_post(){
// Your modal code goes here
// echo your modal code and then exit / die
die();
}

laravel 5 ajax error request

Hi I was wondering why my Laravel 5 Ajax request doesnt work
<input type="hidden" class="_token" value="{{Session::token()}}" name="_token">
$.ajax({
url: "{{ route('groups.store') }}",
method: 'post',
data: {
name: 'name',
_token: $("input[name=_token]").val()
},
success: function(response) {
if (response.success == true) {
// remove error message
alert('success');
}
},
error: function(xhr) {
alert('error');
}
});
on the Route File I put:
Route::post('search/store', [
'uses' => 'SearchController#store',
'as' => 'groups.store'
]);
and on my controller I put:
public function store(Request $request)
{
return response()->json(['success' => true]);
}
then I keep getting error 404 while I simply wants to display the json result from my controller much help appreciated thx
btw heres the full routes.php
<?php
carbon()->setLocale('id');
Route::get('/', function () {
return view('welcome');
});
Route::post('search/SearchController','SearchController#postMapSearchResult');
Route::get('/getRequest', function(){
if(Request::ajax()){
return 'getRequest has loaded';
}
});
Route::group(['middleware' => ['web']], function () {
// Backend Area
Route::controller('login','Backend\LoginController');
Route::get('admin-cp' , function(){
return redirect('login');
});
if(request()->segment(1) == webarq()->backendUrl)
{
include __DIR__.'/backendRoutes.php';
}
//
// Frontend Area
Route::get('account/confirmation/{token}', 'Auth\AuthController#activateUser')->name('user.activate');
Route::controller('faq','FaqController');
Route::controller('blog','BlogController');
Route::controller('social','SocialController');
Route::controller('account','AccountController');
Route::controller('iklan','IklanController');
Route::controller('search','SearchController');
Route::controller('/','HomeController');
Route::post('search/store', [
'uses' => 'SearchController#store',
'as' => 'groups.store'
]);
});
Put the route outside of middleware group
Below is a code which work perfect for me.
var count = 100;
$('#ID').on("click", ".CLASS",function() {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'URL',
type: 'POST',
data: {_token: CSRF_TOKEN,id:count},
dataType: 'html',
success: function (data) {
alert('success');
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});

Resources