Rating specific comments in PHP and MySQL - javascript

So I've got a system in place to post comments to a page, where they are all called from the database and displayed on the page. Each comment has a value called "rating" which is defaulted to 1, and each comment has up and down arrows to the left of it for rating up and rating down which would increase and decrease the rating respectively. Now, I've figured out how to increase and decrease the numbers, but the way I have it, all posts' ratings increase at the same time, regardless of which post I rate.
This is my "rateup" function:
$(function () {
$('#rateup').click(function() {
var request = $.ajax( {
type: "POST",
url: "rateup.php"
});
request.done(function( msg ) {
return;
});
request.fail(function(jqXHR, textStatus) {
});
location.reload();
});
});
This is my rateup.php file:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db_posts";
$tablename = "posts";
// Connection to database
$connection=mysqli_connect("$servername","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno()) {
echo 'NOT_OK';
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Increasing the current value with 1
mysqli_query($connection,"UPDATE $tablename SET rating = (rating + 1)");
mysqli_close($connection);
echo 'OK';
?>
I know that the reason it's incrementing all posts' ratings is because I'm not specifying which post to increment, and that's what I need help with. How do I specify which post is rated when the links to the left of said post are clicked?
The links are echoed like so:
echo " <a class='noStyle' id='rateup' href='index.php'>▼</a>";
It's just a unicode up arrow that's echoed with the post.
Thanks!

You need to specify which link you are clicking and send that through the form.
You can add a data-* tag to your links to do this:
echo " <a class='noStyle' id='rateup' href='index.php' data-id='".$commentID."'>▼</a>";
Then you can get that value when you submit the form and send it as data:
$(function () {
$('.rateup').click(function() {
var id = $(this).data('id');
$.ajax( {
type: "POST",
data: "id=" + id,
url: "rateup.php"
});
location.reload();
});
});
Then you can retrieve this through the form:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db_posts";
$tablename = "posts";
// Connection to database
$connection=mysqli_connect("$servername","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno()) {
echo 'NOT_OK';
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
// Increasing the current value with 1
mysqli_query($connection,"UPDATE $tablename SET rating = (rating + 1) WHERE commentID = '".$id."'");
mysqli_close($connection);
echo 'OK';
?>

Related

Returning an itterable object to Ajax from php

How can I iterate through the object sent back from the php script below in my jquery/ajax call?
I tried result[0] whiche gave me back c. That means that I'm being returned a string.What code should I write to be returned company1 etc. ?
DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
CREATE TABLE company(
name VARCHAR(255),
id INT PRIMARY KEY AUTO_INCREMENT
);
INSERT INTO company(name) VALUES( 'company1');
INSERT INTO company(name) VALUES( 'company2');
INSERT INTO company(name) VALUES( 'company2');
$.ajax({
type: "GET",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
//console.log(response[0]; -> log Company1
//console.log(response[1]; -> log Company2
}
});
<?php
//manager-get-company.php
$hostname = 'localhost';
$username = 'root';
$password = '';
$database_name = 'test';
$con = mysqli_connect($hostname,$username,$password,$database_name);
//Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
echo $row['name'];
}
In ajax add dataType : "json",
$.ajax({
type: "GET",
dataType : "json",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
if(!response.error){
console.log(response[0]);
}
}
});
In php
$result = [];
//Check connection
if (mysqli_connect_errno()) {
$result['error'] = "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
$result[] = $row['name'];
}
}
echo json_encode($result);
Edited : use $result['error'] not result['error']

How to get response.id as string from Facebook Login Java SDK

I stuck in the following process:
Here is the well known "Facebook Login for the Web with the JavaScript SDK example":
https://developers.facebook.com/docs/facebook-login/web
I want to get the Facebook USERID as a simple string to pass it to a PHP variable. Altough the USERID is shown when I print the $fbID, but it's not a string.
How can I get the USERID as a simple string (or a number)...?
Here is my code:
<?php
$fbID = "<script>
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = response.id;
});
}
</script>";
?>
</script>
<div id="status">
</div>
<?php
echo $fbID;
$sql = "select id from customer where fbid = '$fbID' and status = '1'";
$table = mysqli_query($conn,$sql);
list($realid) = mysqli_fetch_array($table,MYSQLI_BOTH);
echo $realid;
?>
Thank you in advance for your answers!
Use ajax to persist the ID in your database. Add the following code to your FB.api('/me', function(response) { } function:
$.ajax({
url: 'persistID.php',
type: "POST",
dataType:'json',
data: ({id: response.id}),
success: function(data){
console.log(data);
}
});
And create a seperate persistID.php file where you persist the FacebookID:
<?php
$ID = $_POST['id'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (fbid) VALUES ($ID)";
// Persist userid
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Ajax form submission loading result page in another div

I am attempting to send data from a form to another page(on the same server) and have that page load within a div on the main index page. When I submit the data it is being processed but the div is not updating to reflect a new page has been loaded in it.
form-page.php
<script>
$(document).ready(function() {//start document ready
$('#review-submit-button').click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'pages/firstdeploy/deploy-sequence-finalize1.php',
data: $("#masteraccountsetup").serialize(),
success: function(response){
$("#primary-display").html(response);
}
});
});
});//end document ready
</script>
processing-form-page.php
<?php
$con=mysqli_connect("localhost","***","***","***");
if (!$con){
die("Database Connection Failed" . mysqli_error());
};
// escape variables for security
$companyname = mysqli_real_escape_string($con, $_POST['review-
companyname']);
$jobtitle = mysqli_real_escape_string($con, $_POST['review-jobtitle']);
$masteraccount = mysqli_real_escape_string($con, $_POST['review-username']);
$masteremail = mysqli_real_escape_string($con, $_POST['review-email']);
$masterpassword = mysqli_real_escape_string($con, $_POST['review-
masterpassword']);
$sql = "INSERT INTO accounts (username, password, company, position, email)
VALUES ('$masteraccount','$masterpassword',
'$companyname','$jobtitle','$masteremail')";
mysqli_query($con,$sql);
echo $companyname;
echo "<br>";
echo $masteraccount;
echo "<br>";
echo $jobtitle;
echo "<br>";
echo $masteremail;
echo "<br> test";
echo $masterpassword;
$con->close();
?>
Now the processing page works when I independantly go to it and it also works when submitted through the form page. The issue is, that it is not updating in to #primary-display from the index page. The form-page.php is loaded into the #primary-display div at the start of the form sequence.
edit: added index page
<div id="primary-holder" class="prima-hold">
<div id="primary-display">
<?php
// Start the Session
session_start();
$con=mysqli_connect();
if (!$con){
die("Database Connection Failed" . mysqli_error());
};
$query = "SELECT * FROM accounts";
$result = mysqli_query($con,$query) or die(mysqli_error());
$count = mysqli_num_rows($result);
if($count > 0){
//Display if there is already a restaurant placed in the system
echo "
<script>
$(\"#primary-display\").load(\"pages/security/mainentrance.php\");
</script>
";
}else{
// Display if no restaurants have been placed in the system
echo "
<script>
$(\"#primary-display\").load(\"pages/firstdeploy/intro.php\");
</script>
";
};
?>
</div>
</div>
you can try:
$.ajax({
type: 'POST',
url: 'pages/firstdeploy/deploy-sequence-finalize1.php',
data: $("#masteraccountsetup").serialize(),
dataType: 'html',
success: function(response){
$("#primary-display").html(response);
}
If ajax dataType is set as text or html, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.
from here

Save data from dataTable to database

how can I save all my datatable data to my database?, im using jquery and php to do this dynamic.
$('#bot_guar').click( function () {
//var rows = $("#tabla1").dataTable().fnGetNodes();
var oTable = $('#tabla1').DataTable();
var data1 = oTable.rows().data();
//alert(data1.length);
$.ajax({
type:"POST",
dataType:'json',
url: "<?= Router::Url(['controller' => 'cab_facturas', 'action' => 'addDetFac'], TRUE); ?>/",//teacher//getdata/3
data:data1,
success: function(data){
alert(data);
}//success
});
});
this is what I had to POST the data from datatable, but I dunno why is the function to send to my php function that will insert.
You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings. Consider you want to access firstname, lastname and email from your server side script. It can be done using:
$firstname = _POST['firstname'];
$lastname = _POST['lastname'];
$email = _POST['email'];
Now, Connect to your database and insert this data through your php script:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Its good practice to send a response to your call back functions so you can do this:
echo json_encode(array('status'=>"Success", message=""));
Your call back function will contain the data sent back from the php file. Since we are sending back a json string, we can make an object of it like this:
var myCallbackFunction = function(data){
var d = $.parseJSON(data)[0];
if(d.Status=="Success"){
//reload your datatable ajax
}else{
alert(d.message);
}
}
I hope that helped!

Jquery $.post returns object

I am attempting to have the user enter their un/pw, click a button, have a javascript function take the un/pw entered, send it to a php script which will return a 1 or 0 based on whether the un/pw was valid.
In the javascript page I have:
function handleLogin() {
var username = document.getElementById('un').value;
var password = document.getElementById('pw').value;
var valid = $.post("getLogin.php", {"un": username, "pw": password}, "json");
alert(valid);
}
In the php file I have:
$username = $_POST['un'];
$password = $_['pw'];
$valid = 0;
# This section will open a connection to the existing backup server and get the last ith_rid used.
# It will then store that ith_rid to be used later and then close the database connection
$mysqlconn = new mysqli('localhost','username','password','database');
if ($mysqlconn->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqlconn->connect_errno . ") " . $mysqlconn->connect_error;
}
###################################################
## Get username and password
##################################################
$res = $mysqlconn->query("SELECT username, password FROM table WHERE username = '" .$username . "'");
if (!$res) { ##If there is an error running query, display it to the screen.
echo "Error: $mysqlconn->error \n";
}
while($row = $res->fetch_assoc()) {
$un = trim($row["username"]);
$pw = trim($row["password"]);
}
if ($un == $username && $pw == $password){
$valid = 1;
}
echo json_encode($valid);
The php does return something, but it is in an object. Not sure how to access the variable from the javascript in order to determine if it is 1 or 0.
Edit:
So I changed things up a bit and it is working correctly now.
carrierchange.js
jQuery(document).ready(function () {
$("#content").append("<form name='loginForm' autocomplete='off'>");
$("#content").append("<table align=center>");
$("#content").append("<tr><td colspan=2 bgcolor=#87C9FF><center><h2>Login</h2></center></td></tr>");
$("#content").append("<tr><td><label for='un'>Username:</label></td><td><input id='un' name='un'></td></tr>");
$("#content").append("<tr><td><label for='pw'>Password:</label></td><td><input id='pw' name='pw' type='password'></td></tr>");
$("#content").append("<tr><td colspan=2><center><input type='submit' class='btn' value='Login' onClick='handleLogin()'></center></td></tr>");
$("#content").append("</table>");
$("#content").append("</form>");
document.getElementById('un').focus().focus();
});
function handleLogin() {
var username = document.getElementById('un').value;
var password = document.getElementById('pw').value;
var valid;
$.get("getLogin.php", {un: username, pw: password}, "json", function(data) {
console.log(data);
});
}
getLogin.php
<?php
$username = $_GET['un'];
$password = $_GET['pw'];
$valid = 0;
# This section will open a connection to the existing backup server and get the last ith_rid used.
# It will then store that ith_rid to be used later and then close the database connection
$mysqlconn = new mysqli('localhost','username','password','datebase');
if ($mysqlconn->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqlconn->connect_errno . ") " . $mysqlconn->connect_error;
}
###################################################
## Get username and password
##################################################
$res = $mysqlconn->query("SELECT username, password FROM cc_user WHERE username = '" .$username . "'");
if (!$res) { ##If there is an error running query, display it to the screen.
echo "Error: $mysqlconn->error \n";
}
while($row = $res->fetch_assoc()) {
$dbusername = trim($row["username"]);
$dbpassword = trim($row["password"]);
}
if ($dbusername == $username){
$valid = 1;
}
echo json_encode($valid);
?>
Since $.post is an asynchronous request, you should handle the received data in the callback function:
$.post("getLogin.php", {"un": username, "pw": password}, "json", function(data) {
console.log(data); //received data
});

Categories

Resources