Can't display ajax result WordPress - php

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>

Related

Display woocommerce notice through Ajax callback on product page

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();
}

Access php variables of a template with ajax

I know that this question has already been answered in other topics but for some reason it doesn't work for me and I don't understand why.
I call a template with ajax and inside it there are set some php variables and i need to get those values.
first-template.php
<?php
$advert = array(
'ajax' => 'Hello world!',
'advert' => 'Bye',
);
echo json_encode($advert);
?>
second-template.php
?>
<script>
jQuery(document).ready(function($){
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
alert(result['advert']) // "Bye" alerted
},
error : function(xhr, status, error) {
alert(error);
}
});
});
</script>
This is how it is shown here but the function returns error.
First, maybe, you can change the request type to GET, because you don't post anything, but tried to get the information.
<script>
jQuery(document).ready(function($){
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
alert(result['advert']) // "Bye" alerted
},
error : function () {
alert("error");
}
});
});
</script>
EDIT:
Here is a functional script:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function(xhr, status, error) {
alert(error);
}
});
});
</script>
See the modifications:
GET instead of POST
console.log(result) to see the result
In my browser console:
Object { ajax: "Hello world!", advert: "Bye" }
Just to be sure, do you load your JQuery properly and do you work on a WAMP/LAMP server?
Can you post the entire files code?
EDIT2:
Check error in console and post it here, this is more easy to find the problem in the future with it.

how i can send a confirmation response to my API , when user click on activation link

I am trying to send a confirmation message to my API after click on activation link , I am trying lot but failed ,
http://polestarllp.com/users/useractive.php?contranumberid=23215
<script type="text/javascript">
$(document).ready(function () {
var person = "<?php $data; ?> ";
$.ajax({
url: 'http://192.168.1.102:1512/qlikapi/RegisterUser',
//type: 'Post',
data:person,
success: function (data, xhr) {
alert(data.ErrorMessage);
if(data.Success)
{
document.location.reload();
}
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
});
</script>
<style>
So far from what you said I have understood that you're trying to send a POST request whenever a user accesses your URL. Is that correct?
In that case try something like this:
<script type="text/javascript">
$(window).ready(function(){
$.ajax({
type: 'post',
url: 'http://192.168.1.102:1512/qlikapi/RegisterUser',
data: {'id' : 23215},
success:(function(data){
alert('Success ' + data);
}),
error:(function(data){
console.error('Error ' + data);
alert('Error has occurred');
})
});
});
</script>
This will send a POST request to http://192.168.1.102:1512/qlikapi/RegisterUser straight after when the page loads, with id parameter and its value being 23215
If you want to get the contranumberid from the URL, you can embed the PHP into your JS script like so:
<script type="text/javascript">
var contranumberid = <?php echo intval($_GET['contranumberid']);?>;
$(window).ready(function(){
$.ajax({
type: 'post',
url: 'http://192.168.1.102:1512/qlikapi/RegisterUser',
data: {'id' : contranumberid },
success:(function(data){
alert('Success ' + data);
}),
error:(function(data){
console.error('Error ' + data);
alert('Error has occurred');
})
});
});
</script>
Note that I've added a new line:
var contranumberid = <?php echo intval($_GET['contranumberid']);?>;
This will assign a JS variable to the value of the GET contranumberid parameter and the POST that value to http://192.168.1.102:1512/qlikapi/RegisterUser.
Hope this helps :)
The script you have given in the question and the actual script in the page linked in question is slightly different. The success callback function was missing closing braces. Here's a better version of your JS code:
<script type="text/javascript">
function myfunc(id) {
id = 23215;
$.ajax({
url: 'http://192.168.1.102:1512/qlikapi/RegisterUser',
type: 'post',
data: {'id' : 23215},
success: function (data, textStatus, xhr) {
alert(data.ErrorMessage);
}
});
}
</script>
Also, I didn't see any code invoking myfunc() anywhere?

PHP Echo doesn't display in html

I post data to sa.php via AJAX and on it I use $_POST['data'] to grab the post and echo it. Now when I hit F12 to see the transfer it shows success. The $_POST['data'] shows up on the sa.php but when you look at the screen no text shows.
retrieve code:
Now here is my AJAX code:
$.ajax({
type: "POST",
data: {"data": data},
dataType: "text",
success: function(data){
console.log(data);
},
statusCode: {
404: function() {
alert( "page not found" );
}
},
complete: function (data) {
console.info(data);
}
});
});
I'm trying to echo the $_POST['data'] but it won't display in html.
As most comments point out you are not updating the HTML but rather just logging to the console....try this... create a div with an id "status"
In your page
<div id="status"></div>
and update your javascript
$.ajax({
type: "POST",
data: {"data": data},
dataType: "text",
success: function(data){
$('#status').html(data); //puts the response in a div with id status
console.log(data);
},
statusCode: {
404: function() {
alert( "page not found" );
}
},
complete: function (data) {
console.info(data);
}
});
});
I presume that you would have a container div for where you want to echo your $_POST['data']? If you do, you can use that div as a selector using jQuery, where you can insert your AJAX data into it. To do that you add to your AJAX success function, something like the following:
success: function(data) {
$('#containerDiv').html(data);
}
Note: .html overwrites whatever is in your selector
Have a look at the first answer of this question, i think this might help achieve what you need:
https://stackoverflow.com/a/2972645/5525510

How to run PHP script in the back by a jquery button

I need to run some PHP code from a file when I click a button from jQuery. This is the code I have:
$(document).ready(function(){
$("#btnSubmit").button().click(function(){
alert("button 1");
$.ajax({
url: 'releaseBackEnd.php',
type: 'POST',
async: false,
data: {},
dataType: 'xml',
error: function(){
alert('Error');
},
success: function(data){
//check error
alert("success!");
}
});
});
});
It shows the alert of "error". I have the releaseBackEnd.php file in the same directory of the javascript file.
check the response in firebug console .. if u don't have firebug add it to your firefox using this link
https://addons.mozilla.org/en-US/firefox/addon/1843/
Change
$("#btnSubmit").button().click(
to
$("#btnSubmit").click(
and check whether the php page is sending the response or not.
Try getting the error in the error callback function using the XMLHttpRequest.
error(XMLHttpRequest, textStatus) {
}
Try this code...
$(document).ready(function(){
$("#btnSubmit").bind('click',function() {
alert("button 1");
$.ajax({
url: 'releaseBackEnd.php',
type: 'POST',
async: false,
data: {},
dataType: 'xml',
error: function(){
alert('Error');
},
success: function(data){
//check error
alert("success!");
}
});
});
});

Categories