how to fetch the current user data in phpfox - javascript

Topic: Fetch current user(some particular fields) data from the DB and display it on the Welcome Screen.
Explaination of UI : On the Registration Page, A dropdown would appear. As the user selects an option, it would trigger an event to fetch user image to show on the welcome page.
I have put following code in (pages.process) module
function getUserId($iUserId)
{
$aRows = $this->database()->select('p.image_path')->from($this->_sTable, 'p')
->Join(Phpfox::getT('user') , 'u', ' p.page_id = u.college_name') ->
where('u.college_name = p.page_id AND u.user_id = ' .
(int)$iUserId)->execute('getRows');
return $aRows;
}
The data will selected from User & Pages Table, and will be used to show the user image. Please suggest.

There is a service to get user details by is
$user_id = Phpfox::getUserId();
$aRow = Phpfox::getService('user')->getUser($user_id);
This will give you user details

For performance, check if the page you are altering already has the information you need, maybe you dont need to query the database in ajax if the page, when being created, already has that info and you can store it in javascript.
Since you mentioned an ajax situation (trigger an event on drop down to query the database), then you need to include a JS file (my suggestion since you can do this from a plugin), there are other ways but this is the best in my opinion.
Please read my article about plugins if you need help with writing one. My suggestion is to write a plugin to include your JS file in the page.
In the JS file you can call a "controller function" like this:
$.ajaxCall('mymodule.myfunction', 'param1=value1&param2=value2');
this would run the function "myfunction" in the file /module/mymodule/include/component/ajax/ajax.class.php
From this ajax file you can call "service functions" and send code to the browser, for example:
$value = Phpfox::getService('mmodule')->someOtherFunction();
$this->call('alert("' . $value . '");');
Hope it helps

Related

How to implement custom logic in WordPress?

I'm working on my website and I want to add two things.
A link when a user clicks on it then his/her user id and the current post id get and inserted in the database and the counter increases.
Let's suppose user logs in and opens the post and the link is like this: I am Interested (0) here 0 is the count value of the total number of unique logged in people who have clicked on this link. The second link will be like: I want to work (0) same logic applies here.**
And finally need to show the no of interested and working people for a specific post(custom post type: job).
There is a table in which each row has the title of the post (job) I can get the value of the post by WordPress native functions and then compare that with the post id in the database and then retrieving it status (noofinterested and noofworking) and then inject via AJAX using jQuery.
I have created the table for this purpose but I'm having difficulty:
Getting POST ID and USER ID via jquery as for some reasons I cant modify the current custom post template as I'm using wp job manager for custom job posts.
All I need is to find a way to get unique people to count on the specific posts
So far I thought of a way to append the two links via jQuery and the add click function to the link via jQuery and in that add ajax to get data and input to the PHP file which I have coded and in that PHP file it will insert into the table via the post values and then return response. And in the second page where I want to insert the status in the table row, I will use jQuery for this.
This is currently I'm having on hand.
PHP
<?php
global wpdb;
if(isset($_POST['if_intested'])&&isset($_POST['if_working'])&&isset($_POST['user_id'])&&isset($_POST['post_id'])){
if($wpdb->insert('wp_custom_jobmanager', array ( "post_id" => $_POST['post_id'], "user_id" => $_POST['user_id'], "if_interested" => $_POST['if_interested'] , "if_working" => $_POST['if_working']))){
return "Thanks your feedback has been saved";
}else {
return "Sorry something went wrong Please Try Logging in again and try again.";
}
}
?>
jQuery
jQuery("#link").click(function(){
if(jQuery("body").hasClass("single")){
jQuery('<p id="stauts-interested">interested 24</p><br><p id="status-work">Working 43</p>').appendTo(".job-manager-single-alert-link");
}
});
Now the number of interested and working should be fetch from database and also get incremented for unique logged in users on click.
Why don't you just add a custom field to your Custom Post Type instead of using a custom table? This is almost a prime example of when it's appropriate to use it. Just add the current user id to an array using get_post_meta and update_post_meta on the WP Ajax hooks.
add_action( 'wp_ajax_increment_cpt_interests' );
add_action( 'wp_ajax_nopriv_increment_cpt_interests' );
function increment_cpt_interests(){
extract( $_POST );
// Get current interested people
$interested_people = get_post_meta( $post_id, 'interested', true );
$interested_user = get_current_user_id();
// If current user isn't already "interested"
if( !in_array( $interested_user, $interested_people ){
// Add them to the array of interested people
update_post_meta( $post_id, 'interested_people', $interested_people[$interested_user] );
}
}
Just pass the post ID, Ajax URL (and current user id if you want) using wp_localize_script (Read more here) to the button you want clicked on.

Check if a $_SESSION variable is set from Javascript

I'm building a message system to learn how it works, and I've already got
pretty much everything. I can log in and make a post on a board, but now I would like to be able to edit it. The back-end is ready, it receives a POST request
Basically what I need to do is check if the currently logged in user is the author of a certain post from Javascript to show or hide the edit button. I know how to tell if the user is logged in from PHP so that it blocks requests if you aren't the author, but I can't hide or show the buttons as the posts are dinamically generated from a <template> using JS.
Login snippet:
$_SESSION["userid"] = $userid;
Edit check PHP snippet (kinda pseudo-code):
if ($_POST["action"] == "modifypost" && isset($_POST["postid"]) && isset($_POST["content"]))
{
$post = get_post($_POST["postid"]);
if ($post.userid != $_SESSION["userid"])
{
die("you are not allowed");
}
//MySQL queries
}
Post dynamic generation (abbreviated):
function add_post(post) {
var t = document.querySelector('#historypost');
t.content.querySelector(".content").innerHTML = post.content;
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
}
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>, but then the user would be able to manually set that variable from the console and show the buttons.
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>
Yes, this is one correct approach. Basically, use PHP to tell JavaScript which posts actually belong to the current user.
but then the user would be able to manually set that variable from the console and show the buttons
True. There is no way to secure information from user-meddling once you've sent it to the browser. This is because the user is in control of what gets executed in the browser. Instead of thinking of the button visibility as a security feature, think of it as a convenience -- something to make the user experience more pleasing.
Application security is really enforced on the server. Just make sure that one user is not allowed to edit another user's posts, and do not trust what comes from the browser. Verify inputs.
Ideally, I would prefer to put the post rendering logic inside the server-side.
But as your solution is focused in javascript, an option makes PHP render a javascript variable that tells if the user is the post author.
Example:
Inside your PHP file, in the HTML render part you can do this:
<script>var isAuthor = '<?php echo ($post.userid == $_SESSION["userid"])'; ?></script>
Doing this you will have javascript script variable called isAuthor, that will have value "1" is the user is the author.
-
But as I said, this doesn't look like a good approach to solve the problem. It's something that PHP can handle better, without expose your logic to the client.

Change URL data on page load

Hello I have a small website where data is passed between pages over URL.
My question is can someone break into it and make it pass the same data always?
For example let say, when you click button one, page below is loaded.
example.com?clicked=5
Then at that page I take value 5 and get some more data from user through a form. Then pass all the data to a third page. In this page data is entered to a database. While I observe collected data I saw some unusual combinations of records. How can I verify this?
yes. as javascript is open on the website, everyone can hack it.
you will need to write some code on you backend to validade it.
always think that you user/costumer will try to hack you sytem.
so take precautions like, check if user is the user of the session, if he is logged, if he can do what he is trying to do. check if the record that he is trying get exists.
if u are using a stand alone site, that u made the entire code from the ashes, you will need to implement this things by yourself.
like using the standard php session, making the data validation etc.
or you can find some classes that other people have made, you can find a lot o this on google. as it is a common problem of web programing.
if u are using a backed framework that isnt from another world, probably already has one. sp, go check its documentation.
html:
<a id = 'button-one' name = '5'> Button One </a>
javascript:
window.onload = function() {
document.getElementById('button-one').onclick = function() {
changeURL(this.attributes.name.value);
};
};
function changeURL(data) {
location.hash = data;
}

creating a configuration page and passing variables to a simply.js app

i developed a simply.js app that fetches bus arrival time from a webservice, problem is that as of now it work only for one stop.
i want to create a configuration page with a multiselect where i could choose multiple stops , sending them to the pebble as an array and at the press of up/down buttons i want to cycle the array to show different bus stops.
Im not good in C, i prefere javascript thats because i used simply.js.
id like to know and learn how to do it, because i think online there isnt much documentation and examples.
Found a similar question/ issue at simply.js github page https://github.com/Meiguro/simplyjs/issues/11. The code example below comes from Meiguros first answer. The code sends the user to your configuration website, which you should configure to send json back.
You can probably copy the code example for enabling the configuration window and paste it in the begining of your main pebble app.js file. Do not forget to add "capabilities": [ "configurable" ], in your appinfo.json file. If you are using cloudpebble you should go to the settings page of your app and make sure the configurable box is checked.
var initialized = false;
Pebble.addEventListener("ready", function() {
console.log("ready called!");
initialized = true;
});
Pebble.addEventListener("showConfiguration", function() {
console.log("showing configuration");
//change this url to yours
Pebble.openURL('http://assets.getpebble.com.s3-website-us-east-1.amazonaws.com/pebble-js/configurable.html');
});
Pebble.addEventListener("webviewclosed", function(e) {
console.log("configuration closed");
// webview closed
var options = JSON.parse(decodeURIComponent(e.response));
console.log("Options = " + JSON.stringify(options));
});
(https:// github.com/pebble-hacks/js-configure-demo/blob/master/src/js/pebble-js-app.js - remove space after https://)
To then push the settings back to the pebble i think you need to add
Pebble.sendAppMessage(options);
just before
console.log("configuration closed");
// webview closed
I found this out at the last post on this pebble forum thread http://forums.getpebble.com/discussion/12854/appmessage-inbox-handlers-not-getting-triggered-by-javascript-configuration-data
You can aslo find a configuration website example named configurable.html in the same git as the code example at https:// github.com/pebble-hacks/js-configure-demo remove space after https://
Hope this helps a bit on the way to achieving your goal
So the configuration page is a web page, and you can host it and provide your URL as mentioned by Ankan above.
Like this:
Pebble.openURL('http://assets.getpebble.com.s3-website-us-east-1.amazonaws.com/pebble-js/configurable.html');
Lets say you decide to take the name and age of the user in the configuration page, you would have two text fields for them to enter their information, then you would have a submit button. For the submit button write a javascript function which uses jQuery to take the values of the text fields onclick, then save those values to a variable, and use JSON to send them to the phone. Here is an example of a fully created configuration web page: https://github.com/pebble-hacks/js-configure-demo
Enjoy.

Not able to copy data from one table to another

I have two tables: trade and user_pokemon_db
I want to copy a specific rows from user_pokemon_db, when an event occurs.
Html code:
echo "<a href='tradecenter.php' onClick='document.write(".trade($db_id).")' >Put in Trade</a>";
When the user clicks on the link, the php function is called which consists on sql query to copy the row.
$sql = " INSERT INTO trade (trade_id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
SELECT (id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
FROM user_pokemon_db WHERE user_id = '".$id."' AND id = '".$db_id."' ";
Problem maybe due to improper writting of the query.. or maybe due to improper formatting of the href!??
What should I do?
I don't know the content of your php function trade() but it seems that you are confusing javascript and PHP.
Keep in mind that in most of case, once the web page is sent to the user browser, the PHP execution is finished. If you want to do a SQL request after a link click, you need to load a new page or to use something like Ajax to run some PHP code again.
The simplest way to do what you want is to pass the pokemon id as a GET variable (= in the URL)
and check this variable on another page and generate the good SQL query :
echo '<a href="trade.php?pokemon_id='.$id.'" >Trade </a>' ;
And the trade.php would do something like that :
$id = $_GET['pokemon_id'] ; // Be Aware of SQL Injections !!
trade($id);
Have a look at this page for more information about forms : http://www.w3schools.com/php/php_forms.asp
( And if you are using GET or POST variables in your SQL query, be aware of SQL Injections )
If you want to run your PHP function without reloading the page, you should use AJAX. Check this page to understand how it works. A very easy way to use it is to use jQuery

Categories

Resources