There is a plugin page with this code:
<?php
function my_action() {
check_admin_referrer();
echo(json_encode( array('status'=>'ok','request_vars'=>$_REQUEST) ));
wp_die();
}
add_action( 'wp_ajax_my_action', 'my_action');
add_action( 'wp_ajax_nopriv_my_action', 'my_action');
if (isset($_POST['my_action']))
if ( wp_verify_nonce( $_POST['nonce'], 'my_action' ) ) my_action();
?>
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action: "my_action",
//"nonce" : "<?php echo wp_create_nonce( 'my_action' ); ?>"
},
success: function (response) {
console.log('AJAX response : ',response);
}
});
});
</script>
When executed on the page the plugin returns
400 Bad Request
Although the action parameters of the request is set
Related
If I add the CPTs ('applicazione' and 'miscele') to 'post' and 'page' in the array they are not searched. If I leave just the CPTs it works. What am I doing wrong?
This is the code I am using.
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query(
array(
'post_type' => array('post','page','applicazione','miscele'),
'post_status' => 'publish',
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] )
)
);
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h4><?php the_title();?></h4>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
Solved.
The problem was the Polylang plugin. Adding the CPTs to the translation settings fixed the issue.
I need to send AJAX request using link.
<a href="#" class="messages_close">
<i class="far fa-window-close"></i>
</a>
May be construction like this?
<?php
$js = <<<JS
$(".messages_close").click(function () {
var id = 8;
$.ajax({
url: "'.\yii\helpers\Url::toRoute(['messages/exclude','id'=>8]).'",
type: "get",
data: "id="+this.id,
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR :: ' + 'id=' + this.id);
}
});
});
JS;
$this->registerJs($js);
Is it possible? Thank you
UPDATE 1
Thanks for #vvpanchev and #Serghei Leonenco
I did some changes:
added use yii\helpers\Url and changed url:;
removed data: "id="+this.id
removed var id = 8 it used in URL
I still get ERROR alert! ((
How can I get SUCCESS, or better return message from controller?
Here is my code looks like:
view\messages.php
<?php
use yii\helpers\Url;
?>
...
<a href="#" class="messages_close">
<i class="far fa-window-close"></i>
</a>
...
<?php
$js = <<<JS
$(".messages_close").click(function () {
$.ajax({
url: "' . Url::toRoute(['messages/exclude','id'=>8]) . '",
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);
MessageController.php (it opens in browser without problem)
<?php
namespace app\controllers;
use Yii;
use app\models\MessagesUsers;
use yii\web\Controller;
class MessagesController extends Controller
{
public function actionExclude($id)
{
return 'Success ID=' . $id;
}
}
Thank you for your help!
SOLUTION
<?php
$url = Url::toRoute(['messages/exclude']);
$js = <<<JS
$(".messages_close").on('click', function () {
$.ajax({
url: "{$url}",
data: {id: 8},
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);
<?php
$url = Url::toRoute(['messages/exclude']);
$js = <<<JS
$(".messages_close").on('click', function () {
$.ajax({
url: "{$url}",
data: {id: 8},
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);
I want to update meta_key with ajax in wordpress i use this form
this is my code but not work for me
<?php
add_action( 'wp_head', 'ajax_the_clike' );
function ajax_the_clike() {
?>
<script>
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
var formd = "#like";
$(formd).submit(function(event) {
event.preventDefault();
$.ajax({
url: $(formd).attr('action'),
type: $(formd).attr('method'),
data: $(formd).serialize(),
success: function(data) {
console.log("SUCCESS!");
},
error: function(data) {
console.log("FAILURE");
}
});
});
</script>
<?php
}
add_action('wp_ajax_the_clike', 'the_clike'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_the_clike', 'the_clike');
function the_clike() {
echo '<form action="'.site_url() .'/wp-admin/admin-ajax.php" method="post" id="like">';
echo '<input type="submit" value="VoteUp" id="submit" name="submits">';
if(isset($_POST['submits'])){
$postsid = get_the_ID();
$addone = get_field('like');
$addone++;
update_field('field_5f009fe6d7067' ,$addone, $postsid);
}
echo '</form><p> Like : '; if(get_field('like')) { the_field('like');}else{echo '0';} echo '</p>';
}
?>
I using a Advanced custom field plugin
Where is wrong? How do I solve this problem?
Thanks for any help
i'm sending the section id in my ajax function,but i can't receive this data in my controller function.need your help please.
This is my jQuery:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
},
success: function(){
alert(section);
},
error: function(){
alert("error");
}
});
$.post("{{URL::to('/ajax')}} ",function(data){
$('#groupe').empty().html(data);
});
});
});
Web:
Route::post('ajax' , 'SeanceController#ajaxfct');
My function in the controller:
public function ajaxfct(Request $request){
$id = $request->section;
$groupes = \DB::table('groupes')
->where('section_id','=',$id)
->get();
return view('seance.groupe')->with([
'groupes' => $groupes
]);
}
The code is close to working perfectly, the following setup passes the data correctly:
HTML:
<select id="getGroupe">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
}
}).done(function( msg ) {
console.log('response: ', msg)
});
});
});
</script>
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SeanceController
{
public function ajaxfct(Request $request)
{
return ['received' => $request->section];
}
}
Route:
Route::post('/ajax', 'SeanceController#ajaxfct');
I trying to upload image using ajax in Laravel 5. I am using following code but nothing happends:
image.blade.php
{{Form::open(array('action' => 'ImageController#store','files'=>true,'id'=>'upload_form'))}}
Title: {{Form::text('title')}}
Image: {{Form::file('image')}}
{{Form::submit('submit',['id' => 'btnAddProduct'])}}
{{Form::close()}}
#include('flash::message')
ImageController.php
public function store(Request $request)
{
$destinationpath = public_path() . '/img/';
$image=$request->input('image');
$filename=$request->file('image')->getClientOriginalName();
$request->file('image')->move( $destinationpath,$filename );
return Response::json(['success' => true, 'file' => asset($destinationpath.$filename)]);
}
Ajax code:
<script>
$(document).ready(function() {
$('#submitButtonId').on('click', function() {
$.ajsubmitButtonIdax({
url:'/imgC/store',
data:new FormData($("#upload_form")[0]),
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
});
</script>
Route.php:
Route::resource('imgC', 'ImageController');
What I am doing wrong?