I am making a WordPress template, mytemp.php in wordpress 3.9. In this I can use wordpress functions. For example, below works perfectly.
$(document).ready(function() {
alert(<?php echo get_current_user_id() ?>);
}
However, this template file calls some ajax scripts too depending on user input. Over there it doesn't work. For example, below statement returns fatal error "call to undefined function get_current_user_id"
$sql = 'SELECT x,y FROM table WHERE user_id = ' . get_current_user_id();
I am guessing, I need to tell the ajax script to include some wordpress file or some global variable but I am not sure how.
I solved it. All I needed to do was to have below include statement.
include '../../../../wp-load.php';
By including this, it started recognizing the function get_current_user_id()
Try to include wp-load.php file in ajax file, after including this file wordpress functions are working properly in your ajax file or you need to write a plugin like ajax.php, and then use this plugin file for your ajax file.
After that you can access the wp functions.
Hope it'll helps.
Try this. I just answered a question not too long ago with this style of sql syntax using the function get_current_user_id();
$sql = "SELECT x,y FROM table WHERE user_id = %d", get_current_user_id();
Another solution would be to establish a contract between your ajax script and the javascript that posts to it.
So, in your calling php script, you could set up some JSON in your header:
<script>
<?php echo "wp-data = {current_user_id: " . get_current_user_id() "}"; ?>
</script>
And then put it in your ajax call:
$.ajax({
url: "http://yourdomain.com/process_wp_ajax.php",
method: "post",
data: {
. . . //your post data
current_user_id: wp-data.current_user_id;
})
.success(function(response) {})
.fail(function(response) {} )
.complent(function(response, status) {};
Your receive should expect "current_user_id" to be on the POST (or GET).
This involves more work, but you save yourself from loading the WP framework each time you make an ajax call.
Don't use the php above if you want to set multiple values. Set an object instead and just call json_encode on it:
<?php
wp_object = (object) array('wp-val1' => wp_func1(), 'wp-val2' => wp_func2());
?>
<script>
<?php echo "wp-data =" . json_encode(wp_object) . ";"; ?>
</script>
DRY, just pass the wp-data object directly in your ajax:
$.ajax({
url: "http://yourdomain.com/process_wp_ajax.php",
method: "post",
data: {
. . .
wp-object: wp-data,
}
. . .
So in your calling script, you would eventuall arrive at:
$sql = "SELECT x,y FROM table WHERE user_id = %d", $_POST['current_user_id']
or `$_POST['wp-object']['current_user_id']
(of course you would set the $_POST value in a ternary prior to this right?
Related
NOTE - This is a edited snippet. This is testing at the moment and will be improved after.
I'm aiming to learn oop PHP now I got a good understanding of procedural. I'm stuck on sending this Ajax request to my php file.
Html File
<script>
$("#Question").click(function() {
flag = 1;
uid = "<?php echo $uid ?>";
var dataQuestion = {
uid,
flag,
ImageOne: $("#Image1").val()
};
//Post with AJAX
$.ajax({
type: "POST",
url: "../View/class.user.php",
data: dataQuestion,
perform: "QuestionsFunctions",
success: function(Returned){
$(".NotBoxSmall").text("Updated");
$(".NotBox").text("Updated");
flag = 0;
console.log(Returned);
},
error: function(){
$('.NotBox').text("Issue With Site");
$('.NotBoxSmall').text("Issue With Site");
}
});
});
</script>
Php file
<?php
public function QAsk(){
if($_POST['flag'] == 1){
$Image1 = $_POST['ImageOne'];
$uid = $_POST['uid'];
$insertsqlQ = "UPDATE UsersData
SET Image1 = '$Image1'
WHERE uid = $uid";
$resultquestion = mysqli_query($this->db,$insertsqlQ) or die(mysqli_connect_errno().json_encode("Data cannot inserted"));
return $resultquestion;
echo json_encode("Question Updated");
}else{
echo json_encode("Question NOPE");
return false;
}
}
?>
The id sends and iv'e tested this not within the public function and it appears to be fine. The request send back is blank, outside of the function it's the error log.
The issue is it says questions have been updated but no data has been added to the database.
jQuery must be initialized after the DOM ( document object model ).
How should I initialize jQuery?
I'd suggest some tips:
1 - Make the id names lower case #name_of_element
2 - Grab a OO PHP book and try to practice just this, run tests using curl for instance and make your database rules work before going into the client (html, js, css)
3 - Grab a jQuery book and run tests with mock data just printing a array from PHP. At the beginning is easier study stuff separated.
4 - '$Image1' is a varchar rather than the variable $Image1. Remove the quotes
Complete rewrite of my question
The task I am trying to do is update the display of five variable without reloading the whole page.
I have a php file (check_conf_update.php) which runs a query that produces data and I am scripting it into JSON.
In the PHP file that runs the query I have at the end:
echo json_encode($record);
The JSON result looks like this:
[{"ClientName":"Another","RoomFromDateTime":"2016-02-25 01:00:00","RoomToDateTime":"2016-03-13 23:00:00","ClientImageName":"anothernew.png","DisplayText":"System Testing"}]
I now need to use the data on a page called "template.php). How can I read the data from the Json result and assign each of the result elements in variables I can use on my "template.php" page. I need the Json script to run every x seconds so the display is always shows up todate information.
I have five php variables:
$CientName
$ImageName
$DisplayText
$FromTime
$ToTime
which I use on my web page to display the data on the same page as the script below.
$(document).ready(function() {
function runupdate() {
$.ajax({
url: 'check_conf_update.php',
type: 'GET',
data: 'record',
dataType: 'json',
success: function(data){
// not sure what I need to do here
}
});
};
// run it initially
runupdate();
// run it every 30 seconds
setInterval(runupdate, 30 * 1000);
});
Sorry if have confused anyone, and it looks like I did.
Can anyone help. Many thanks in advance for your time.
Regards
It's not really clear on what happens in your PHP script that produces the data. If you can update the post with the complete code for PHP also, it would be helpful. However, I'm assuming you want to use the data in the produced json string to populate the PHP variables in the destination file (check_conf_update.php)? In this case,
// check_conf_update.php
// $_POST['record'] == '[{"ClientName":"Another","RoomFromDateTime":"2016-02-25 01:00:00","RoomToDateTime":"2016-03-13 23:00:00","ClientImageName":"anothernew.png","DisplayText":"System Testing"}]'
$json = $_POST['record'];
$array = json_decode($json, true)[0];
$ClientName = $array['ClientName'];
$ImageName = $array['ClientImageName'];
$DisplayText = $array['DisplayText'];
$FromTime = $array['RoomFromDateTime'];
$ToTime = $array['RoomToDateTime'];
echo $ClientName . ', ' . $ImageName . ', ' . $DisplayText . ', ' . $FromTime . ', ' . $ToTime;
Edit:
All the PHP code in the template.php file is run on the server side before its rendered in the browser, so it will be too late to assign the updated json data into PHP variables by then. The only way to update information without reloading the page is to replace text or elements with javascript. After each successful ajax request, you can update the values in the page,
$('.clientname').html(data[0].ClientName);
$('.childbox').html(data[0].ClientImageName);
$('.clientndisplaytext').html(data[0].DisplayText);
$('.clientndisplaytime').html(data[0].RoomFromDateTime);
$('.clientndisplaytime').html(data[0].RoomToDateTime);
I am unfamiliar with AJAX and am having a difficult time trying to learn it for what I need.
I need to write ajax calls within a foreach loop.
if i just use PHP calls they will all fire even if i don't use the onclick event.
What im basically doing is writing out a list from the DB and adding a remove button to the row.
when the remove link is clicked, it will fire a query to update a field in the DB for item.
My index.php file
<?php foreach ($items as $item) : ?>
<tr>
<td><?php echo $item['item_name']; ?></td>
<td><a href="#" onclick="ajax call(arguments)" ></a></td>
</tr>
<?php endforeach; ?>
My PHP code: (note: I am using wordpress's $wpdb to query the WP database. query is valid. There is no user input, and its on an admin page so dont worry about prepare() or other injection defenses. )
<?php
$wpdb->query("UPDATE " . $wpdb->prefix."item
SET is_removed =" . $remove_option . "
WHERE item_id =" . $item_id );
?>
($remove_option is populated earlier in the index.php page, and $item_id comes from $items array)
I need to pass 2 variables through the ajax call, populate $remove_option and $item_id.
fire the query, return to index.php page.
How do I use ajax to achieve this? I'm completely unfamiliar with ajax, and i am not using a plugin for WP, only php scripts.
PHP part
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add_action('wp_ajax_update_this', 'update_this_func');
add_action('wp_ajax_nopriv_update_this', 'update_this_func');
function update_this_func(){
$remove_option = $_POST['remove_option'];
$item_id = $_POST['item_id'];
global $wpdb;
$wpdb->query("UPDATE " . $wpdb->prefix."item
SET is_removed =" . $remove_option . "
WHERE item_id =" . $item_id );
return json_encode(['status' => 'Updated!']); // return status as json
}
Ajax call
http://codex.wordpress.org/AJAX_in_Plugins
function onClickingThis(rem_opt,itemid){
$.ajax({
url: ajax_url, // You can get this from admin_url('admin-ajax.php') function
type: 'POST',
data: {action: 'update_this', remove_option: rem_opt, item_id: itemid },
dataType: 'json',
success: function(response){
console.log(response);
}
});
}
can I achieve this with AJAX?
Yes
is there a better approach to what I'm trying to achieve?
If you want to send data from the client to the server then ajax is the best way to do so.
I have found a few articles about using PHP in JS but nothing has helped me so far, so here is my question. I need to call wordpress post content (title, excerpt and thumbnail) into a JS "preview" functionality (essentially calling posts with the ThumbnailGridExpandingPreview). I have been able to make the "expanding preview" open from the post thumbnail and title, however I am having trouble adding the post content to the preview.
I am attempting to add the php calls to the preview function in the "grid.js" file, however I am not sure exactly how to "minify" the php code. See below for my code.
The code as it reads originally:
this.$title = $( '<h3></h3>' );
And here is how I am attempting to call the post title:
this.$title = $( '<h3><?php echo get_the_title(); ?></h3>' );
Any help would be hugely appreciated! Thanks in advance.
Some clarifications: PHP is a server side language; this means that it can be parsed and executed only server-side.
That said, you have two options here, one more elegant, the other a bit crappy (i would use it only in really rare and limited cases):
Elegant solution: Wordpress Ajax. Setup an ajax-callable function in your functions.php file which returns data-populated html:
a. Add an ajax-callable action to your functions.php file:
add_action("wp_ajax_[function_name]", "function_name");
//If the action wants users to be logged in, you can specify a different function to be called in case a user is not:
//add_action("wp_ajax_nopriv_[function_name]", "[function_name_for_non_logged_users]");
b. Specify the function to be called (specify a second one for non logged-in users in case you need it)
function function_name() {
//It is good practice to use nonce verification
if (!wp_verify_nonce( $_REQUEST['nonce'], "function_name_nonce")) {
exit("[Your scary message against bad people]");
}
// Make your query here.
$post_id = $_REQUEST["post_id"];
$post = get_post($id, ARRAY_A);
// Return your data. Here I go with a simple JSON.
$result = json_encode($result);
echo $result;
}
c. Cook the frontend-code, somewhere in the template (obviously make it so that's available to your grid.js calls). You'll need to have $post populated with your post data. I tend to use a global wrapper:
<script type="text/javascript">
<?php
$nonce = wp_create_nonce('function_name_nonce');
$endpoint = admin_url('admin-ajax.php');
?>
var Globals = {
nonce: "<?php echo $nonce; ?>",
postId: "<?php echo $post->ID; ?>",
endpoint: "<?php echo $endpoint; ?>"
}
</script>
d. From now on, it's up to you to make the ajax call (I don't have any references to your code) but it's pretty straightforward:
$.ajax({
type: "post",
dataType: "json",
url: Globals.endpoint,
data: {
action: "function_name",
post_id: Globals.postId,
nonce: Globals.nonce
},
success: function(response) {
//Aaaaand here's your post data
console.log(response);
}
});
See http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action) for this.
This is a good tutorial (found it on the first page of Google): http://wp.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/
Crappy solution: generated data-populated JS code (i would stick to a JS object). In this case, you will need an additional script tag inside your page (template or whatever else has access to PHP) in which you'll output JS valid code:
var title = "<?php the_title(); ?>";
EDIT: Check at the end of this for the solution
I am new to php, ajax and all other things :)
My question is: is there a way for a php file to return a value?
I have:
a file "loadImages.php" containing the script to get the paths to images from the database.
an image gallery where I want to load images via ajax.
a database containing the path to the images (/images/image1.jpg, /images/image2.jpg).
4 categories of images.
What i'm trying to do is :
When clicking on a link (example, first category), I want to call via jquery's ajax(), loadImages.php with the category passed via POST (cat0, cat1, cat2, ...)
I want to return the value from this php file for example : <img src="image/image1.jpg" />, so via javascript, I can retrieve this string. Using only return in my php file returns XMLHttpRequest when i'm putting the ajax() function in a variable instead of the string <img>.
Is there a way to do it? Or maybe a better way, as I don't fully understand ajax.
Thank you! Sorry for my bad grammar.
Below is a more precise map of what i'm trying to do.
JavaScript:
var test = $.ajax({
type: "POST",
url: "loadImages12.php",
data: "category=0",
complete: function() {
alert("COMPLETE");
},
error: function (){
alert("NOT LOADED");
}
});
PHP (loadImages.php)
function createThumb() {
if(isset($_POST['category'])) {
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
return $thumbHtml;
}
else {
$noCategory = "NO CATEGORY TEST";
return $noCategory ;
}
}
createThumb();
SOLVED
Php File
function createThumb(){
//Mysql request
$someVar = //Result of request
return $someVar
}
echo createThumb()
Javascript
$("#someDiv").load("loadImages.php", {category:0});
An AJAX request to PHP is exactly the same as a normal request for a website. You request data from example.com/foo/bar and in return you receive text. The return statement of PHP has nothing to do with what's returned to the client. Only things you echo or otherwise output will be received by the client. That's the same for normal pages and AJAX requests.
So, to "return" <img src="image/image1.jpg" /> to your Javascript AJAX call, echo that string in PHP.
if you want to use the php file that you already have (loadImages.php) just echo the result of the function:
echo createThumb();
Just make the php script to return the path to thumbnail.
and then do something like this in js
somediv.html('<a href="#" class="thumbnail"><img src="">');
and just use the path returned by the php file for the img src ..