Apologies for the NOOB question but I’m still learning.
Firstly I’m not asking for someone to program the following problem for me or to give me the code. I’m merely looking for a bit of help with the logic and a bit of advice.
What I am trying to do
This is just an example, what I am trying to do is different but will use the same logic: I am trying to display a movie poster on my website, the user can than rate that movie between 0 - 5 stars, his/her rating will be recorded in a database, along with other users’ ratings. When he/she has finished his/her rating, a new movie poster needs to be displayed where he/she can again rate the poster and so it goes on until he/she is tired of rating movies.
The Logic
I AM ASSUMING I will need to use PHP here to store and retrieve the data
A Table will be created which contains different images and ratings corresponding to that movie’s rating, along with the number of users who rated the movie to calculate the average for the total rating
The Problem
How do I get the image to change once the user rated the image?
Is it possible to change an image src onclick with PHP like it is with Javascript?
If so how do I do it? Is it possible that I will need to use a combination of PHP and Javascript here?
Any help or advice will be greatly appreciated. Thank you in advance.
You definitely need to use both javascript and PHP to accomplish this.
I would approach it like this:
a) Use jQuery javascript library to make the javascript easier.
b) Write some javascript which responds to the user selecting a rating. You'd probably need to bind to the onClick event of your rating buttons.
c) When a rating button is clicked, the javascript functions should use jQuery.ajax to send the selected rating to the server via an HTTP POST. The data sent to the server would probably need to contain an ID to identify the movie, an ID to represent the user (so you can stop people voting more than once for the same movie), and the rating they chose.
d) On the server-side, you can write a PHP script to handle the vote submissions. It would check for the movie, and user ids, (stored in PHP's $_POST variable), and then save the rating to some database. It could then also send a response back to the client which would contain the next movie id, and the next poster. I would recommend you use json_encode to store this info in a way that's easy for the javascript to interpret.
e) Finally, back on the client side, your javascript code can react to the data sent back by PHP, by putting up a message like 'thank you for your vote', then changing the movie details on screen to replace them with the new one.
Your client-side code would look something a bit like this:
<img id="movie-poster" src="movie poster src" />
<ul>
<li class="rating-button">1</li>
<li class="rating-button">2</li>
<li class="rating-button">3</li>
<li class="rating-button">4</li>
<li class="rating-button">5</li>
</ul>
<script>
var currentUserId;
var currentMovieId;
$('.rating-button').on('click',function() {
$.ajax({
url: "URL of PHP script here",
type: 'post',
data: {'movieId':currentMovieId, 'userId':currentUserId, 'rating':$(this).text()},
dataType: 'json',
success: function(response) {
// this runs after your PHP script has responded
// update your page with the new movie here
alert('thanks for voting');
currentMovieId = response.newMovieId;
$('#movie-poster').attr('src',response.newMoviePosterSrc);
}
});
}
</script>
Your PHP script would look something a bit like this (you'll have to figure out all the database and user authentication bits yourself)
<?php
$user_id = $_POST['userId'];
$movie_id = $_POST['movieId'];
$rating = $_POST['rating'];
// check that the user is allowed to vote - possibly examine cookie for this
// check that rating is between 0 and 5
// check that the movie exists
// store results of vote in database
// load up another random movie from the database and send it back (in JSON format)
// assume details of new movie are in $new_movie =
header('Content-type: application/json');
echo json_encode(array('newMovieId'=> new movie id here, 'newMoviePosterSrc' => URL of new poster here));
exit;
You should also add some error handling to that code. EG, messages to display if there's a connection problem, or the movie ID isn't recognised or something.
This page has more info on how to select a random row from your database - IE to select at random the next poster to show:
How to randomly select rows in SQL?
Hopefully that should be enough to get you started.
Related
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.
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.
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;
}
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
I have an Instant Message feature on my site which uses a popup window. When a user makes an IM post, their picture is added to the post. I am able to save on a database query for each IM post (so the popup does not have to query the database to retrieve the user's picture for each post) by retrieving the stored user pic file name from a form (UserPicStorage...a separate query is not required to grab $sql['picture']...it's already present on each of the main pages when these pages load) on each of 5 non-popup, main pages (one page is an exception, see below) of my site as follows:
<form id="UserPicStorage"><input type="hidden" name="UserPic" value="<?=
$sql['picture'] ?>"></form>
I have an About Us page which does not need a database query to load. So to save a query if a user posts an Instant Message while on the About Us, I pass $sql['picture'] to the a href as follows:
About Us
so the popup can retrieve the userpic if there is an IM post while the user is on About Us.
However, the user can use AJAX on one of the 6 main pages to change his/her user picture.
So I can't use this:
About Us
because if the user changes his/her photo, $sql['picture'] (which was valid on page load)
is no longer the current photo. I did a lot of searching, but could find nothing to support
something like the following method:
About Us
I tried this and simply passed the literal string document.forms.UserPicStorage.UserPic.value. So did the following:
About Us
Is there any way to append the input value of a form directly to the a href?
You should just use
About Us
(well, probably you should encode $sql['picture'])
And when you make the AJAX request, update it as a success callback:
ajax.onreadystatechange = function() {
if (ajax.readyState===4 && ajax.status >= 200 && ajax.status < 300) {
/* AJAX successful */
myAnchor.src = "about.php?userpic=" + encodeURIComponent(
document.forms.UserPicStorage.elements.UserPic.value
);
}
};