ajax in wordpress and wp_query - javascript

In my funcitons.php file i have function that response to ajax call and return posts:
functions.php:
function returnPosts(){
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
get_template_part('content', get_post_format());
}
} else {
get_template_part( 'content', 'none' );
}
exit();
}
add_action('wp_ajax_returnPosts', 'returnPosts');
add_action('wp_ajax_nopriv_returnPosts', 'returnPosts');
Javascript (in index.php):
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url("admin-ajax.php"); ?>",
data: {"action": "returnPosts"},
success:function(results){
// Work with results
}
});
But when i call this function via JS i always get content from content-none.php file.

It looks like you're assuming the AJAX call will know what post is being displayed on the page already, since you're checking have_posts() without creating your own WP_Query. But an AJAX call comes in as a separate HTTP request, and the only things it knows about the previous page are the things you tell it.
In additon to passing your "action" name in the AJAX call, try passing the current post's ID. I'm not in front of a real computer to test this, but this should work assuming you're inside a Loop when that jQuery code is output:
data: {"action": "returnPosts", "p": "<?php the_ID(); ?>"},

Quick fix is to:
include("../../../wp-load.php"); <-- guessing at the location of the wordpress file.
at the top of the php file.

Related

Run php script inside JavaScript at regular intervals using ajax or any method

I have a index.php with a javascript function Loaddata()
function loaddata(){
<?php
$data = //connects to database and gives new data
?>
var data = <?php echo json_encode($data); ?>;
}
setInterval(loaddata,3000);
I understand the fact that php scripts can only be run once when the page is loaded and it cannot be run again using set interval method. Can someone please guide me how to run the php script at regular intervals inside my index.php using ajax or some other method. My javascript variable "data" depends upon the php script to gets its value. Thanks a lot
Generally, using ajax to get data from a PHP page on the front page is a good way. The way you write this code is fine, too. I suggest writing like this,
var data = <?php echo json_encode($data);?>;
function loaddata(){
// use data
}
setInterval(loaddata,3000);
I think it is more clear
You could use an ajax call to retrive data from php and call that function in setInterval function something like this.
function demofunc()
{
$.ajax({
url: '<?php echo base_url();?>',
type: 'POST',
data: formdata,
dataType: 'json',
success: function(data) {
// do your thing
}
});
}
setInterval(demofunc,3000);
If anyone wondering how to do it.
Echo the PHP value that you want ajax to get for you.
Do an ajax request to the php page to get the data.
$.ajax({
method: 'get',
url: 'time.php',
data: {
'ajax': true
},
success: function(data) {
console.log(data)
}
});
// Second Method
$.get('time.php',function(data){
console.log(data);
});
PHP file
if ($_GET['ajax']) {
echo "HELOOO";
}
//if using the 2nd method just echo
echo "hi second method";

get specific array keys back in javascript ajax request

I've got the following ajax request that I want to run every 5 seconds. To test it, I just set up a couple alerts. I set up an alert('hello'); inside the success and it fired every 5 seconds. So that works.
What isnt working is the if(response.update==true){ section.
I am setting
<?php $data['update'] = "true"; return $data; ?> inside the ajax url file.
Am I doing something wrong? Is this an incorrect approach? Am I missing something?
I even tried setting datatype: json, inside ajax and returning return json_encode($data); inside ajax url as well with no success.
CODE
<script type="text/javascript">
$(document).ready(function(){
/* AJAX request to checker */
setInterval(
function (){
$.ajax({
type: 'POST',
url: '<?php echo http() . $websitedomain .'/Manage/order_management/search_orders_checker.php'; ?>',
datatype: html,
data: { counter:10 },
success: function(response){
if(response.update==true){
alert('yes');
}
}
})
},5000);
});
</script>
EDIT
console log is now reporting the json response. But the if (response.update == "true") { alert('yes'); } still isnt working.
The console.log response: {"update":"true"} and its updating every 5 seconds like its supposed to.
Here are all the things you need to get it working:
1) PHP:
you need to
encode your data as JSON
echo your data to your script's output, rather then returning it somewhere within PHP
return a boolean true instead of a string "true" in the "update" field
Here's the new code for that:
<?php
$data['update'] = true;
echo json_encode($data);
?>
2) JavaScript:
You need to change datatype: html to dataType: "json"
This is because
JS variables are case-sensitive, so jQuery doesn't recognise an
option called 'datatype'
the value "json" must be string (before you used html which was actually a reference to a non-existent variable
specifying "json" tells jQuery to automatically parse the response as JSON, meaning you don't have to do you own call to JSON.parse()
in the callback.
Couple things look incorrect here. First off...
<?php $data['update'] = "true"; return $data; ?>
If this is how you are returning your data, then this is not returning json. You need to encode the associative array into json and echo that to the standard out.
<?php $data['update'] = "true"; echo json_encode($data); ?>
Once you have that, then you can make your ajax request expect the response to be json.
$.ajax({
type: 'POST',
url: '<?php echo http() . $websitedomain .'/Manage/order_management/search_orders_checker.php'; ?>',
//dataType tells ajax to auto-parse the json response into an object
dataType: 'json',
data: { counter:10 },
success: function(response){
if(response.update==true){
alert('yes');
}
}
})

Send array with Ajax to PHP script in wordpress

I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps

Call do_action using JavaScript/jQuery

I have an AJAX function that sends information to the userpro_ajax_url after successfully logging in through Facebook.
I am trying to get the success block to run a do_action function using
<?php
ob_start();
do_action('userpro_social_login', <email needs to go here>);
ob_clean();
?>
Right now if I pass the email address manually it works fine, however the only way I can get the email dynamically is through the current response which is in JavaScript.
The full function is:
FB.api('/me?fields=name,email,first_name,last_name,gender', function(response) {
jQuery.ajax({
url: userpro_ajax_url,
data: "action=userpro_fbconnect&id="+response.id+"&username="+response.username+"&first_name="+response.first_name+"&last_name="+response.last_name+"&gender="+response.gender+"&email="+response.email+"&name="+response.name+"&link="+response.link+"&profilepicture="+encodeURIComponent(profilepicture)+"&redirect="+redirect,
dataType: 'JSON',
type: 'POST',
success:function(data){
userpro_end_load( form );
<?php
ob_start();
do_action('userpro_social_login', );
ob_clean();
?>
/* custom message */
if (data.custom_message){
form.parents('.userpro').find('.userpro-body').prepend( data.custom_message );
}
/* redirect after form */
if (data.redirect_uri){
if (data.redirect_uri =='refresh') {
//document.location.href=jQuery(location).attr('href');
} else {
//document.location.href=data.redirect_uri;
}
}
},
error: function(){
alert('Something wrong happened.');
}
});
});
I tried running the php action using:
jQuery(document).trigger('userpro_social_login', response.email);
Neither of these work... what am I doing wrong?
Modify your php function userpro_fbconnect trigger the code there or create another ajax request after this one is done
You can't execute PHP code from your JS and vise versa. But the following may help you:
<?php
// Some php code goes here...
?>
<script>
// JS code...
ob_start();
do_action('userpro_social_login', <?php <email needs to go here> ?>);
ob_clean();
</script>
And if you want to execute a method from your JS, and that method in defined using PHP, and it to the global scope, then simply call it from JS my_global_method()
I hope that helps fixing your problem.

PHP request through AJAX fails

This is probably something very simple, and I've seen that there are/have been more people with the same issue. But the solutions provided there did not seem to work.
So, I want to execute a .php file through AJAX. For the sake of testing the php file (consolefunctions) is very small.
<?php
if(isset($_POST['action'])) {
<script>console.log('consolefunctions.php called.');</script>
}
?>
And now for the javascript/ajax part.
$(".startConsole").click(function(){
var consoleID = $(this).attr("value");
$.ajax({ url: 'include/consolefunctions.php',
type: 'post',
data: {action: 'dosomething'},
success: function(output) {
//alert("meeh");
}
});
});
Somewhere, somehow there's an issue because the message from the PHP file never shows. I've tested the location from the php file, which is valid.
First the php code is not correct, you should add an echo
<?php
if(isset($_POST['action'])) {
echo"<script>console.log('consolefunctions.php called.');</script>";
}
?>
but the problem is, when you send this code to js, you'll get it as a string on your variable output, not as a code that will be executed after making the ajax call, so the best way to do this is to echo only the message to display on your console and then once you receive this message you can call console.log function
<?php
if(isset($_POST['action'])) {
echo"consolefunctions.php called";
}
?>
in the success function :
console.log(output);

Categories