Display woocommerce notice through Ajax callback on product page - php

I'm trying to display a woocommerce notice in a product page. The notice should by displayed by an ajax callback function, triggered by a button.
The callback is working correctly, but no notice is being displayed.
Here is my code:
jQuery/AJAX
$(document).ready(function() {
$('#return-button').on('click', function (event) {
event.preventDefault();
var id = $(this).val();
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'my_custom_function',
product_id: id
},
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
});
PHP Callback
function my_custom_function() {
error_log('Function called');
wc_add_notice("Success!", "notice");
wc_print_notices();
wp_die();
}
What is the correct way to do this?

Solution
wc_print_notices() default effect is to echo the HTML code of the notices. The content echoed by my_custom_function corresponds to the response param in the AJAX success function. So it just has to be displayed/inserted in the DOM.
Note: wc_print_notices() can also return the value instead of echoing. This can be done by setting the $return param as true 1.
Here is the working code:
jQuery/AJAX
$(document).ready(function() {
$('#return-button').on('click', function (event) {
event.preventDefault();
var id = $(this).val();
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'my_custom_function',
product_id: id
},
success: function(response) {
$('woocommerce-notices-wrapper').append(response);
},
error: function(error) {
console.log(error);
}
});
});
});
PHP Callback:
function my_custom_function() {
error_log('Function called');
wc_add_notice("Success!", "notice");
wc_print_notices();
wp_die();
}

Related

POST mywebsite/wp-admin/admin-ajax.php 400 (Bad Request)

I am using ajax for handling filters in my custom post type but getting a Bad request on both POST & GET methods don't know why. Here is my Ajax code,
(function($) {
$(document).ready(function(){
$(document).on('submit', '[data-js-form=filter]', function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data);
var ajaxscript = { ajax_url : '//localhost/experiencecamping/rv-sales/wp-admin/admin-ajax.php' }
$.ajax({
url: ajaxscript.ajax_url,
type: "POST",
data: data,
success: function(result) {
console.log(result);
},
error: function(result) {
console.warn(result);
},
});
});
});
})(jQuery);
add_action('wp_ajax_nopriv_filter', 'filter_ajax');
add_action('wp_ajax_filter', 'filter_ajax');
For this wp_ajax request to work we need to specify action = filter in the data array we send via POST
Also we need filter_ajax() function
Maybe you have it here but you haven't copy it to your question.
Try this version of the code
(function($) {
$(document).ready(function(){
$(document).on('submit', '[data-js-form=filter]', function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data);
var ajaxscript = { ajax_url : '//localhost/experiencecamping/rv-sales/wp-admin/admin-ajax.php' }
$.ajax({
url: ajaxscript.ajax_url,
type: "POST",
data: {
query: 'test',
action: 'filter'
},
success: function(result) {
console.log(result);
},
error: function(result) {
console.warn(result);
},
});
});
});
})(jQuery);
add_action('wp_ajax_nopriv_filter', 'filter_ajax');
add_action('wp_ajax_filter', 'filter_ajax');
function filter_ajax(){
echo 321;
wp_die();
}

Can't display ajax result WordPress

I have the following simple HTML structure
<button class="aardappel" value="im a value">HENK!</button>
<p class="leeg" value="niks"></p>
What's supposed to happen is once I click the button the p tag gets replaced with the result from my php function
I have the following jQuery
jQuery(".aardappel").on("click", function(){
jQuery.ajax({
url : ajax_testing.ajaxurl,
data: {
action : "test_printer",
buttonvalue : jQuery(this).val()
},
type: "POST",
//dataType: "html",
succes: function(data){
console.log(data);
//jQuery(".leeg").html(data);
},
error: function(){
console.log("foutje");
},
completed: function(){
console.log("doe ik iets?");
}
})
and this is the function ajax is calling
add_action( 'wp_ajax_test_printer', 'test_printer' );
add_action( 'wp_ajax_nopriv_test_printer', 'test_printer' );
function test_printer()
{
$result = <<<HTML
<p>{$_POST["buttonvalue"]}</p>
HTML;
echo $result;
exit();
}
When I press the button I recieve the admin-ajax.php file with the following content
But also when I press the button nothing get logged in the console, in other words, error, succes and completed are not triggering and thus I can't display the result on my page. What am I doing wrong?
Try this script. typo error. it is success function not succes;
<script>
jQuery(".aardappel").on("click", function(){
jQuery.ajax({
url : ajax_testing.ajaxurl,
data: {
action : "test_printer",
buttonvalue : jQuery(this).val()
},
type: "POST",
//dataType: "html",
success: function(data){
console.log(data);
//jQuery(".leeg").html(data);
},
error: function(){
console.log("foutje");
},
completed: function(){
console.log("doe ik iets?");
}
});
});
</script>

Ajax Pagination Laravel 5.1

I'm trying to make a pagination with ajax and laravel 5, but I can not do the ajax works even with simple tests:
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
$.ajax({
type: "GET",
url: 'testeserver.php',
//url:"raphael.dev/testeserver.php",
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success:function(json){
alert("Success"+json);
},
error:function(){
alert("Error");
}
});
});
});
In this example I try one have a return on json ,
<?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>
but only with the error alert , in fact I'm trying with these following cases :
BlogController:
public function index(Request $request){
$artigos = Artigo::where('publicado_em', '<=', Carbon::now())
->orderBy('publicado_em', 'desc')
->paginate(config('blog.artigos_por_pagina'));
if ($request->ajax()) {
return Response::json(view('Blog.artigos', compact('artigos'))->render());
}
return view('Blog.index', compact('artigos'));
}
routes.php
post('/', 'BlogController#index');
get('/', 'BlogController#index');
get('/{slug}', 'BlogController#show');
jquery
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
$.ajax({
type: "POST",
url: 'page=' + page,
dataType: 'json',
success:function(json){
alert("Success"+json);
},
error:function(){
alert("Error");
}
});
});
});
Just found the solution, changed my jquery code to :
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
var url = '?page=' + page;
$.post( url, function(data) {
alert( "success"+data );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
And found a error in my BlogController :
in
if ($request->ajax()) {
return Response::json(view('Blog.artigos', compact('artigos'))->render());
}
the Facade Response was not declared, so just added
Use Request;
at the top,
but i still dont understand why the $ajax() dosent work, just the $get and $post
Laravel protects your application with CSRF tokens. When utilising Ajax you need to be sure to send across the CSRF token, otherwise Laravel will not process the request to protect your app.
$.ajax({
url: 'test',
type: "post",
data: {'_token': $('input[name=_token]').val()},
success: function (data) {
alert('the joys');
},
complete: function (data) {
}
});
Notice the $('input[name=_token]').val() - that will send your CSRF token. You will of course need to create a hidden input with the CSRF token in your view.
More information can be found here!

ajax url won't call php file

I am trying to update the user input ratings through ajax call. This one alert(performance_rating) returned the user input ratings properly. But, I have a problem with my url. it won't call user_ratings.php. I don't know why? I have tried alert function in user_ratings.php page. But, it won't alert.
I have the user_ratings.php file in siteurl.com/include/pages/user_ratings.php
How do I call my php file properly?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});
If you are sending your ajax request from localhost to your domain, then you have to use full site url in your ajax call as follows
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://domain.com/include/pages/user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});
first its better you do this
define("URL", "http://siteurl.com/");
Then in the ajax url section write
url: '<?php echo URL ;?>includes/pages/user_ratings.php',
Put your FQDN (e.g. www.yoururl.com) before the user_ratings.php in your jQuery Ajax call. So change to this:
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://www.yoururl.com/user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});

Ajax submit with Spry Validate

I am trying to have my form validate before the ajax runs but can't seem to get the coding right for this to happen.
if i seperate them i can post using ajax with no validation or validation but it posts the default way
here is my current code i am trying
$(document).ready(function(){
// ajax code start
$('#form').on('submit', function (e){
e.preventDefault();
if (spry.widget.form.validate('#form') == true)
{
$.ajax({
type: "POST",
url: "localProxy.php",
data: $('#form').serialize(),
success: function (response) {
document.location = '/thank-you';
// do something!
},
error: function () {
alert('There was a problem!'); // handle error
}
});
};
});
});
figured it out
$(document).ready(function(){
// ajax code start
$('#form').on('submit', function (e){
e.preventDefault();
Spry.Widget.Form.onSubmit = function(e, form)
{
if (Spry.Widget.Form.validate(form) == false) {
return false;
}
{
$.ajax({
type: "POST",
url: "localProxy2.php",
data: $('#consult').serialize(),
success: function (response) {
document.location = '/thank-you';
// do something!
},
error: function () {
alert('There was a problem!'); // handle error
}
});
};
};
});
});

Categories