How to put PHP script in JS? - javascript

I have a page that allow users to access it. This page have certain things that not allow user to see that particular thing, For my case, user is unable to edit edit() or view this function, so I want to hide it by putting below code in JS because I am using function on this link.
I already enabled Session in PHP page like this <?php session_start(); ?>
And I try this putting this PHP in JS inside Datatables function. The dataTable function is working fine. Just the PHP is not working.
{ data : "project_id",
render: function(data) {
return "<span onclick='view()'></span> "+ // This is allow to user and admin level
"<?php
if ($_SESSION['user_privilege'] == 'Admin') { ?>
<span onclick='edit()'</span>
<?php } ?>"; // This is allow for admin level only
}
}

Check the following
<?php
if(isset($_SESSION["user_user_privilege"])){
echo "<script>
let button = '<span onclick='edit()'></span>';
</script>";
}else{
echo "<script>
let button = '';
</script>";
}
?>
Now check the button is empty or not.
{ data : "project_id",
render: function(data) {
return "<span onclick='view()'></span> "+ ((button!="") ? button : "");
}
}

Related

Prevent Direct access to PHP file using AJAX

I want to prevent direct access to a certain PHP file called prevented.php
My logic is that I have a main file lets call it index.php and it generates a token and stores it in a $_SESSION variable. I also have a another file called def.php which is called using AJAX and it passes the token from the index.php to the def.php and if the $_SESSION['token'] is equal to the $_POST['token'] it defines a _DEFVAR and returns true otherwise it returns false. After I called the def.php and it returns true, I redirect to the prevented.php via javascript using location.href="prevented.php". In the top of the prevented.php file there is a code which checks if the _DEFVAR is defined or not. If not, its die with a message like invalid otherwise it displays the content of the prevented.php file. But somewhy I always get invalid message and I don't know why. Any idea how to reach the prevented.php without directly direct the page?
Here's my code:
index.php
<?php
$_SESSION["token"] = hash_hmac('sha256', "tokenString", "t2o0k0e0n3"); // Creates a hashed token
?>
<script>
$.ajax({
type: "POST",
url: "def.php",
data: {
token: '<?php echo $_SESSION["token"]; ?>'
},
cache: false,
success: function(data) {
console.log (data);
if (data) {
console.log (data + ' valid');
} else {
console.log (data + ' invalid');
}
location.href = "prevented.php";
},
error: function () {
console.log('error');
}
});
</script>
def.php
<?php
session_start();
if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token']) {
echo false;
die('invalid in def');
} else {
define('_DEFVAR', 1);
echo true;
die ('valid in def');
}
?>
prevented.php
<?php
include "def.php";
if (defined('_DEFVAR')) {
die ('valid in prevented'); // instead of this I would show the content of the page
} else {
die ('invalid in prevented');
}
?>
Your code is unnecessarily overcomplicated. If your intent is merely to ensure that visitors to protected.php have first visited index.php then all you need to do is create a session flag in one and check for its existence in the other. There is no need for any AJAX or any form POSTs. The innate behavior of PHP sessions already gives you this functionality.
index.php:
<?php
session_start();
$_SESSION['flag'] = true;
?>
click here for the protected page
protected.php:
<?php
session_start();
if ($_SESSION['flag'] ?? false) {
echo "you have previously visited index.php";
} else {
echo "you have not previously visited index.php";
}
?>

Accessing Through PHP a Posted Javascript Variable

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

wp_enqueue_script not working on AJAX called php file

I've got a complicated little problem here.
I'm building a WordPress plugin where I select a "parent" post (of a custom type that I made called 'step') and then an AJAX function shows a new select bar with all of the children of that parent. I do this by outputting the new and elements in the PHP file that's called in the AJAX function. This works, but now I want to repeat the process to run a function from the same JQuery file when this new outputted element is added to the page. (See Javascript code)
Main php plugin file (in a folder within the plugin directory):
<?php
/*
Plugin Name: n8jadams Step by Step Plugin (WIP)
Plugin URI:
Description:
Author: Nathan James Adams
Author URI: http://nathanjamesadams.com
Version: 0.0.1a
*/
//Exit if accessed directly
if(!defined('ABSPATH')) {
exit;
}
//My custom post type, it works fine
require_once(plugin_dir_path(__FILE__).'n8jadams-step-funnel-cpt.php');
require_once(plugin_dir_path(__FILE__).'n8jadams-ajax.php');
//Add my javascript
function n8jadams_init_javascript() {
wp_register_script('n8jadams_javascript', plugin_dir_url(__FILE__).'n8jadams-scripts.js', array('jquery'),'1.1', false);
wp_enqueue_script('n8jadams_javascript');
}
add_action('wp_enqueue_scripts', 'n8jadams_init_javascript');
//Adds a plugin menu to the wordpress sidebar
function n8jadams_add_plugin_menu() {
add_menu_page('', 'Steps Settings', 4, 'steps-settings', 'n8jadams_steps_settings', '');
}
add_action('admin_menu', 'n8jadams_add_plugin_menu');
//The actual function for the menu page
function n8jadams_steps_settings() {
//Access the database and the tables we want
global $wpdb;
$posts = $wpdb->prefix.'posts';
//Get the user id
$user = wp_get_current_user();
$userid = $user->ID;
//Initialize javascript (it works here!)
n8jadams_init_javascript();
/* Get all the parents */
$parentsquery = "
SELECT `ID`, `post_title`
FROM $posts
WHERE `post_author` = $userid
AND `post_parent` = 0
AND `post_status` = 'publish'
AND `post_type` = 'step'
";
$parentsarray = $wpdb->get_results($parentsquery);
?>
<h4>My Forms:</h4>
<select id="parentselect">
<option id="-1"> - Select Your Step Form - </option>
<?php
//output the parents
for($i=0;$i<sizeof($parentsarray);$i++) {
echo '<option id="'.$parentsarray[$i]->ID.'">'.$parentsarray[$i]->post_title.'</option>';
}
?>
</select>
<div id="displayChildren"></div>
<?php
}
?>
Javascript (n8jadams-scripts.js):
(function($){
$('#parentselect').change(function(s) {
var thisID = s.target[s.target.selectedIndex].id;
var outputDisplay = document.getElementById('displayChildren');
if(thisID != '-1') {
$.ajax({
type: 'POST',
url: 'admin-ajax.php',
data: {
action: 'n8jadams_get_children',
id: thisID
},
success: function(response){
if(response == "") {
outputDisplay.textContent = "This form has no children. Add them in the sidebar menu of this step form.";
} else {
outputDisplay.innerHTML = response;
}
},
error: function(errorThrown) {
alert(errorThrown);
}
});
} else {
outputDisplay.textContent = '';
}
});
// I want this function to work
/*
$('#childselect').change(function(t) {
console.log("test");
});
*/
})(jQuery);
PHP file called by AJAX (n8jadams-ajax.php):
<?php
function n8jadams_get_children() {
//Get the id of the parent
$parent_post_id = $_POST['id'];
//Sanitize the input (Added after question was answered)
$parent_post_id = preg_replace("/[^0-9]/","",$parent_post_id);
//Access database
global $wpdb;
$posts = $wpdb->prefix.'posts';
$user = wp_get_current_user();
$userid = $user->ID;
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
//Retrieve the children associated with this parent
$childrenarray = $wpdb->get_results($childrenquery);
//Initialize Javascript (it doesn't work here!)
n8jadams_init_javascript();
if(!empty($childrenarray)) { ?>
<h4>My Steps:</h4>
<select id="childselect">
<option id="-1"> - Select Your Step - </option>
<?php
//output the children of the parent
for($i=0;$i<sizeof($childrenarray);$i++) {
echo '<option id="'.$childrenarray[$i]->ID.'">'.$childrenarray[$i]->post_title.'</option>';
} ?>
</select>
<?php wp_die();
}
}
add_action('wp_ajax_n8jadams_get_children', 'n8jadams_get_children');
add_action('wp_ajax_nopriv_n8jadams_get_children', 'n8jadams_get_children');
?>
Screenshot of Plugin Menu
I cannot figure out why my javascript file isn't working in the PHP file that's called by AJAX. Maybe the vast wisdom of the StackOverflow can help me. Thanks for the help in advance. :)
You are hooking into wp_enqueue_scripts, which is only run for the frontend of Wordpress (the part the average visitor sees). If you want to load a script into wp-admin, the backend of Wordpress, use the admin_enqueue_scripts action.
Since this code does not work in /wp-admin/, you don't need to use admin_enqueue_scripts. I guess the whole problem would be that you are attaching a handler to $('#childselect'), while no such element exists on the page at that time. Use deferring with $(..).on(..):
$(document).on('change', '#childselect', function(e) {
//Black magic
});
Side note: As already mentioned in the comments, the following part contains an unsanitised variable which will allow an attacker to perform sql injections.
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
Use WP_Query if at all possible. If this is only used from the backend of Wordpress, don't use wp_ajax_nopriv_*, because users that are not logged in into your site have no right to use that anyway.

A href load database items onClick

i'm developing a simple Content Management System that allow users to create categories and subcategories. This is the code.
$categories = mysql_query("SELECT * FROM categories");
while($row = mysql_fetch_array($categories)) {
$text = $row['text'];
$id = $row['id'];
echo "<li><a href='?category=$id'>$text</a></li>";
}
Now, all works fine as expected but i would like that when a user click on <li> items the system loads subcategories related to the selected category. In PHP i can't do this so i need to use JavaScript but i don't understand why. I wrote this code.
<script type="text/javascript">
function loadSubCategories() {
<?php
if(isset($_REQUEST['category'])) {
echo "Hello";
}
?>
}
</script>
and obviously
echo "<li><a href='?category=$id' onClick='javascript:loadSubCategories()'>$text</a></li>";
This not works because nothing appear when i click on a link. How can i solve?
Pass id attribute in function call like this:
echo "<li><a id="$id" onClick='javascript:loadSubCategories(this.id)'>$text</a></li>";
Then you can use jQuery/Ajax, try something like this:
$( document ).ready(function() {
function loadSubCategories(id){
$.ajax({
url : Class/Method-Name,
type : 'POST',
data : form_data,
success : function(msg){
// Action
}
}),
}
});

$.post data success returning data unsuccessfully, but successfully?

I'm working on a "like" function in php and jquery and I'm at the last part of it. When I click on the:
like
<span id="post_<?php echo $post_id ?>_likes">
<?php echo $post_likes; ?>
</span>
the function in add_like.php:
<?php add_like() ?>
submits the user data and increments the like count by one in the database.
The problem I'm having is I'm getting an alert that say success in it when it shouldn't be and it doesn't update the like count until I refresh the page. I should be getting a alert that says 'works!' and getting the like count back.
edit**
Right now it is returning the echoed "success" from the like_add.php in the alert when I click on the like button. This to be exact:
'
success'
like.js
function like_add(post_id){
$.post('../public/like_add.php', {post_id:post_id}, function(data){
if (data == 'success') {
like_get(post_id);
alert("works!");
}else{
alert("'" + data + "'");
}
});
}
function like_get(post_id){
$.post('../public/like_get.php', {post_id:post_id}, function(data){
$('#post_'+post_id+'_likes').text(data);
});
}
add_like.php
<?php
if(isset($_POST['post_id'], $_SESSION['user_id'])
&& post_exists($_POST['post_id'])){
$post_id = $_POST['post_id'];
$user_id = $_SESSION['user_id'];
if (previously_liked($post_id, $user_id) === true) {
echo "You've already liked this";
} else{
add_like($post_id, $user_id);
echo 'success';
}
}?>
If you have whitespace (like a hard return) before your <?php or after your closing ?> tag, you will return more than "success" as you saw when you alerted ' success'. Find this whitespace and remove it. Make sure your opening PHP tag is flush against the top left of your script page.
As commenters have mentioned, an easy fix is to trim the data variable so ' success' becomes 'success';

Categories

Resources