Need a few pointers on AJAX in Wordpress - php

Alright, so I'm trying to learn how to work with AJAX in Wordpress the "right way", via admin-ajax, etc. but I'm kinda going around in circles. I want to load a portfolio item (custom post type) via Ajax - when I do it via jQuery .load() it works fine, but as soon as I try to do it the Wordpress way, it doesn't. Tutorials and StackOverflow questions have only been helpful up to a certain point... I don't know, I just feel kinda dense :-(
This is how far I've gotten, with a little (ahem) tutorial help here and there. Forgive me if there are stupid errors, for I am terrible with this kind of code. It's new to me and all. Also, thanks in advance for any help you can offer :-D
The jQuery:
jQuery(document).ready(function ($) {
$(".getworks").click(function (event) {
event.preventDefault();
if (getpost !== '') {
$.ajax({
type: "POST",
url: MyAjax.ajaxurl,
data: {
'action': MyAjaxRequest,
'getpost': $(this).attr('href'),
},
success: function (data) {
// This outputs the result of the ajax request
$('#portfolio-back').html(data);
console.log(data);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
}
});
});
The PHP:
add_action( 'wp_ajax_MyAjaxRequest', 'MyAjaxFunction' );
add_action( 'wp_ajax_nopriv_MyAjaxRequest', 'MyAjaxFunction' );
function MyAjaxFunction() {
if ( isset($_POST['getpost']) ) {
$getpost = $_POST['getpost'];
if ( $getpost !== '' ) {
echo $getpost;
}
}
die();
}
UPDATE: So I added a preventDefault to the click and I $(this).attr('href') into the ajax call, and now the URL is loaded into the DIV on success, instead of the actual contents.

Related

Ajax call to PHP action/function with array as data (in wordpress)

I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );

Passing JSON data from a PHP page as a Javascript variable

In the middle of a PayPal Checkout Express (client-side) javascript, I need to use AJAX to call the output of a PHP page, but I'm a bit stuck.
The PHP page:
$data = array('retid' => $username);
header('Content-Type: application/json');
echo json_encode($data);
Now inside the other javascript page I simply want to capture the PHP variable $username, via AJAX, as a javascript variable.
<?php
$IDToPassPlus = ($id.'&retid=');
?>
<script>
//It's the inclusion of this part, which tries to get the "retid" js variable, that stops the script from rendering the Paypal button:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
},
});
paypal.Button.render({
env: 'sandbox',
client: {
sandbox: 'xxxxx',
production: 'xxxxx'
},
commit: true,
style: {
layout: 'vertical',
size: 'responsive',
shape: 'rect',
color: 'gold'
},
payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount: { total: '0.99', currency: 'GBP' }
}
],
redirect_urls: {
'cancel_url': 'pay-return-cancel.php?id=<?php echo $IDToPassPlus; ?>'+retid
}
}
});
},
onAuthorize: function(data, actions, error) {
return actions.payment.execute().then(function() {
window.alert('Payment Complete!');
window.location.replace('test-return.php?id=<?php echo $IDToPassPlus; ?>'+retid);
if (error === 'INSTRUMENT_DECLINED') {
actions.restart();
}
});
},
onCancel: function(data, actions) {
return actions.redirect();
},
onError: function(err) {
window.location.replace('pay-return-error.php?id=<?php echo $id; ?>'+retid);
}
}, '#paypal-button');
</script>
Without the contributor's AJAX suggestion, the button works perfectly. But I'm trying to pass a variable from a PHP page by way of AJAX, to add it onto the redirects.
it's possible to use on in-page javascript as
<script>
var js_var = "<?php echo $php_var;?>";
//now you have php var value in javascript to use on .php page
If it's not what you are seeking, then please elaborate your question.
ok so as far I understood you want to retrieve the PHP response via ajax and you don't know how to make ajax call. Here is an example you may use on your js file:
$.ajax({
type: 'POST',
url: 'YOUR PHP SCRIPT URL',
dataType: 'json',//this will make it understand what datatype to expect in response
success: function(response) {
var retid = response.data.retid; //here you get on successfull response
},
});
First, read this entire page; it will really help you throughout your career as a developer, it has helped me tremendously: https://stackoverflow.com/help/mcve
Then, lets use the knowledge gained from that page to make an MCVE. Put this on a new page:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
console.log(retid);
},
});
This should print the value of retid to your console. Take a look at your console. Notice any errors, or does the value of retid print as expected?
So why have we taken time to create a new page and put this on it? We are narrowing down our issue, we're trying to find the exact cause of the problem by creating an MCVE. If we don't know what is causing the problem, and if we can't create a very basic example to illustrate the problem, we will have a hard time solving the problem and/or asking for help.
(Note 1, make your code "pretty" when you post it here. Indent it as it should be indented; this makes it easier for others to read. You are asking people to take time out of their day to help you, for free; make it as easy as possible for them to read and understand your code)
(Note 2, here is an example of where I had some very, very complicated MySQL interactions that I had a question about. Rather than post all of the complicated code, I followed the MCVE concept: DRY - how to extract repeated code to...a stored function maybe? and made some fake, very very simplified examples of my problem. Since I did that, I was able to get quick, concise answers from experts, notice the answer I accepted was from one of the top-scored users on all of Stackoverflow)

Wordpress admin plugin AJAX call (ajaxurl) keeps returning 0

I have been busting my balls for the last week on the issue below. Ofcourse I did search and come across posts of people describing similar issues but none of the answers and solutions discussed seem to solve my problem.
I want my Wordpress plugin to make use of the build-in Wordpress functionalities but my functions keep returning value: 0 in the console. The JS get 'loaded' on the admin_footer add_action and executes when someone hits 'add-row' button. That all seems to be working fine. However the console message keeps returning:
Successful AJAX Call! /// Return Data: 0
So it seems to me that the woosea_ajax function never even gets called? Who can help me out here? Greatly appreciated.
function woosea_ajax() {
$data = "hello world";
echo json_encode($data);
wp_die(); // just to be safe
}
add_action( 'wp_ajax_woosea_ajax', 'woosea_ajax' );
function ajax_js_script() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
jQuery(".add-row").click(function(){
jQuery.ajax({
method: "POST",
url: ajaxurl,
data: {
action: 'woosea_ajax'
}
})
.done(function( data ) {
console.log('Successful AJAX Call! /// Return Data: ' + data);
})
.fail(function( data ) {
console.log('Failed AJAX Call :( /// Return Data: ' + data);
});
});
});
</script>
<?php
}
add_action( 'admin_footer', 'ajax_js_script' );
To give access on the front-end side (anonymous users), you'll need to add the nopriv action too, like:
add_action( 'wp_ajax_nopriv_woosea_ajax', 'woosea_ajax' );

how to get exact answer from ajax?

I have some ajax requests in my jquery code. and my php server should decide what to do. but I'm beginner in web programming I don't know how to return the exact response .
<script>
$(document).ready(function () {
$('#subButton').click(function () {
var query = "query";
$.ajax({
type: 'POST',
url: 'info.php',
datatype: 'text',
data: {query: query},
complete: function (data) {
alert(data);// it returns the whole php page!
}
})
.done(function (data) {
alert("done");
})
.fail(function () {
alert("Posting failed.");
});
});
});
</script>
and there is my php code
<?php
if ( isset( $_POST[ 'music' ] ) ) {
echo "music";
}
if ( isset( $_POST[ 'query' ] ) ) {
echo "query";
}
if ( isset( $_POST[ 'url' ] ) ) {
echo "url";
}
?>
in this jquery I want just the word "query" not whole page. and also I want to know how to set it in html through some tags.
so we've found out why your php page is returning the whole script. It had a .html extension, not a .php one. Without the php extension the server would just send back the whole lot.
how to put it into a tag? Quite easy.
suppose you have a tag on your page like this (note the id):
<h2 id="main_heading">some heading</h2>
all you need to do is ask jquery to place the response inside it like this.
complete: function (data) {
// select the object with the right ID and change its innerHTML
$('#main_heading').html(data);
}
this will replace the contents of the <h2> with whatever comes back.
update
if youre having trouble, try putting a console.log call in and check it with the browsers javascript console, this should show you whats being sent back from the server.
like this:
complete: function (data) {
console.log(data);
// select the object with the right ID and change its innerHTML
$('#main_heading').html(data);
}

Load PHP function with jQuery Ajax

I have a file which is loaded at the top of my document, which is called Videos.php. Inside that file are several functions, such as getYoutubeVideos. On some pages, I need to call upon that function several times (up to 50), and it of course creates major lag on load times. So I have been trying to figure out how to call that function in, only when it is need (when someone clicks the show videos button). I have very little experience with jQuery's ajax abilities. I would like the ajax call to be made inside of something like this:
jQuery('a[rel=VideoPreview1).click(function(){
jQuery ("a[rel=VideoPreview1]").hide();
jQuery ("a[rel=HideVideoPreview1]").show();
jQuery ("#VideoPreview1").show();
//AJAX STUFF HERE
preventDefault();
});
Ok I have created this based on the responses, but it is still not working:
jQuery Code:
jQuery(document).ready(function(){
jQuery("a[rel=VideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").hide();
jQuery("a[rel=HideVideoPreview5]").show();
jQuery.post("/Classes/Video.php", {action: "getYoutubeVideos",
artist: "Train", track: "Hey, Soul Sister"},
function(data){
jQuery("#VideoPreview5").html(data);
}, 'json');
jQuery("#VideoPreview5").show();
preventDefault();
});
jQuery("a[rel=HideVideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").show();
jQuery("a[rel=HideVideoPreview5]").hide();
jQuery("#VideoPreview5").hide();
preventDefault();
});
});
And the PHP code:
$Action = isset($_POST['action']);
$Artist = isset($_POST['artist']);
$Track = isset($_POST['track']);
if($Action == 'getYoutubeVideos')
{
echo 'where are the videos';
echo json_encode(getYoutubeVideos($Artist.' '.$Track, 1, 5, 'relevance'));
}
$.post('Videos.php', {
'action': 'getYoutubeVideos'
}, function(data) {
// do your stuff
}, 'json');
In your php code, do something like this:
$action = isset($_POST['action'])? $_POST['action'] : '';
if($action == 'getYoutubeVideos')
{
echo json_encode(getYoutubeVideos());
}
Then data in your JavaScript function will be the array/object/value returned by getYoutubeVideos().
I would do the JS part like ThiefMaster describes, but the php part would i handle a little bit different.
I would do something like this:
if(isset($_POST['action'], $_POST['par1'], $_POST['par2'])
{
$action = $_POST['action'];
$result = $this->$action($_POST['par1'], $_POST['par2]);
echo json_encode(result);
}
But be careful, if you have some methods in the class which shouldn't be called by the user, trough manipulating POST data, then you need some way to whitelist the methods the JavaScript may call. You can do it by prefixing the methods i.e:
$this->jsMethod.$action(....);
or by simple if/switch condition.
Ok here is what ended up working:
PHP CODE
$Action = isset($_POST['action']);
if($Action == 'getYoutubeVideos')
{
getYoutubeVideos($_POST['artist'].' '.$_POST['track'], 1, 5, 'relevance');
}
JQUERY
jQuery.ajax({
type: "POST",
url: "/Classes/Video.php",
data: "action=getYoutubeVideos&artist=artist&track=track",
success: function(data){
jQuery("#VideoPreview1").html(data);
}
});
json encoding was annoying, not sure if json is hte better way of doing it, I could actually use the jQuery.post function as well, because the real problem was with the PHP. If anyone knows about any security problems with the method I am doing, please let me know. Seems fine though.

Categories