I'm currently in the process of relaying the data from a column called "followers_count", in a table called "tbl_users". The site has several users each with their own page. On those pages a person can click a follow button and the follow count is displayed, using JSON. The code works so far except it only shows/updates the data of "followers_count" for the first "userID" in the table. My question is, how would I alter the code so that it knows for each user's page to display their followers_count?
In changes.php:
<?php
require_once 'class.channel.php';
$user_change = new USER();
$seqFollows = $user_change->runQuery("SELECT followers_count FROM tbl_users");
$seqFollows->execute();
$row = $seqFollows->fetch(PDO::FETCH_ASSOC);
$follow_count = $row['followers_count'];
header('Content-type: application/json');
$array = array('followers_count'=>$follow_count);
echo json_encode($array);
?>
In index.php?id= (the user page template):
<div>
Channel Adds: <div id="follow_count" style="display:inline;"></div>
</div>
<script type="text/javascript">
var timer;
timer = setInterval(function() {
$(document).ready(function(){
$.getJSON('changes.php', function(data) {
$('#follow_count').html(data.followers_count);
});
});
}, 1 * 1000);
</script>
Also in index.php?id=, this is the code that determines whose page I'm currently viewing:
$currentID = ( isset( $_GET['id']) && !empty( $_GET['id'] ) ) ? trim($_GET['id']) : '' ;
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$currentID));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
You need to tell changes.php what the user ID value is. You will need to modify your index.php file to supply that value. One option is to modify the AJAX call similarly to:
$(document).ready(function(){
$.getJSON('changes.php?id=<?php echo $_GET["id"]; ?>', function(data) {
$('#follow_count').html(data.followers_count);
});
});
Then your changes.php file will need to get the value of $_GET['id'] just like index.php.
Related
I have a problem with updating the data I display from my db. Initially, when the page opens I display the date corresponding to the current date but then the user can change the date by entering it in a text box and when he clicks update all the data displayed should be deleted and the data corresponding to the new date should be displayed. Right now I have a javascript function which deleted all the data in the div when the button is clicked. The div holds the data I want to change. But I don't know how to add new data into the div. I tried to add php code to look up the database for the data in the javascript function but I don't know how to add it to the text box.
function changedate()
{
document.getElementById("label1").innerText=document.getElementById("datepicker").valu e;
document.getElementById("selecteddate").innerText=document.getElementById("datepicker" ).value;
document.getElementById("teammembers").innerHTML = "";//empties the div(teammembers)
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
}
}
?>
}
You can use a combination of jQuery and AJAX to do this. Much simpler than it sounds. To see that this is the right answer for you, just view this example.
In the below example, there are two .PHP files: test86a.php and test86b.php.
The first file, 86A, has a simple selection (dropdown) box and some jQuery code that watches for that selection box to change. To trigger the jQuery code, you could use the jQuery .blur() function to watch for the user to leave the date field, or you could use the jQueryUI API:
$('#date_start').datepicker({
onSelect: function(dateText, instance) {
// Split date_finish into 3 input fields
var arrSplit = dateText.split("-");
$('#date_start-y').val(arrSplit[0]);
$('#date_start-m').val(arrSplit[1]);
$('#date_start-d').val(arrSplit[2]);
// Populate date_start field (adds 14 days and plunks result in date_finish field)
var nextDayDate = $('#date_start').datepicker('getDate', '+14d');
nextDayDate.setDate(nextDayDate.getDate() + 14);
$('#date_finish').datepicker('setDate', nextDayDate);
splitDateStart($("#date_finish").val());
},
onClose: function() {
//$("#date_finish").datepicker("show");
}
});
At any rate, when the jQuery is triggered, an AJAX request is sent to the second file, 86B. This file automatically looks stuff up from the database, gets the answers, creates some formatted HTML content, and echo's it back to the first file. This is all happening through Javascript, initiated on the browser - just like you want.
These two files are an independent, fully working example. Just replace the MYSQL logins and content with your own fieldnames, etc and watch the magic happen.
TEST86A.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "test86b.php", // "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
TEST86B.PHP
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'abcd1234';
$pword = 'verySecret';
$dbname = 'abcd1234_mydb';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
$result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<ul style="list-style-type:disc;">
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</ul><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
Here is a more simple AJAX example and yet another example for you to check out.
In all examples, note how the user supplies the HTML content (whether by typing something or selecting a new date value or choosing a dropdown selection). The user-supplied data is:
1) GRABBED via jQuery: var sel_stud = $('#stSelect').val();
2) then SENT via AJAX to the second script. (The $.ajax({}) stuff)
The second script uses the values it receives to look up the answer, then ECHOES that answer back to the first script: echo $r;
The first script RECEIVES the answer in the AJAX success function, and then (still inside the success function) INJECTS the answer onto the page: $('#LaDIV').html(whatigot);
Please experiment with these simple examples -- the first (simpler) linked example doesn't require a database lookup, so it should run with no changes.
You want to output a literal JS statement with whatever you get back from php, basically:
document.getElementById("teammembers").innerHTML = // notice no erasing, we just
// overwrite it directly with the result
"<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
// so just show it!
echo $email_users; // think about this for a second though
// what are you trying to achieve?
}
}
?>"
This is a vast question, not very specific. Checkout more about AJAX requests - basically from javascript you will have a call to the server that retrieves your data.
This is a snippet from the javascript library jQuery :
$.ajax({
type: "POST",
url: "emails.php",
data: { user: "John" }
}).done(function( msg ) {
$('teammembers').html(msg);
});
hope this will give you a starting point
I have a comics website, Hitting Trees with Sticks, that allows a user to get next, previous, or random comic id by pressing next or simply pressing arrow keys.
Since images are stored in a database, the only way for me cycle through these images on the client side was to store them in a javascript array, and store the php $imgid in a javascript variable as imgIndex. Then I could alter that index on the client side when they press keyboard keys.
When the user presses a key, I'm using pushstate to alter the imgid in the URL, but that's not actually updating the server side $imgid. I need to update the server side $imgid because I'm associating a liking function with each specific ID... but currently, the total likes associated with an img ID won't refresh/update when I press a key to get a new image.
My solution was to not only use the PushState to update the URL, but when a key is pressed, I use a $.post, and send the updated imgIndex to the php script.
Here are snippets:
KeyInput.php: This is the client-side javascript:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($site)) ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
$(document).keydown(function (e) {
var key = e.which;
var rightarrow = 39;
var leftarrow = 37;
var random = 82;
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
window.history.pushState(null, null, '.?action=viewimage&site=comics&id=' + imgIndex);
$.post('./templates/viewimage.php', { _newImgId : imgIndex },
function(data) {
//alert(data);
}
);
}
viewimage.php This is the file that originally gets the $imgid, then it calls the keyInput.php script to accept key input... that alters the javascript imgid. For testing purposes, I've tried using $.post and $.get AJAX to send the updated imgid, as you can see below, that's $newID = $_POST['_newImgId];. When I echo out $newID, it says it's not defined.
<?php
/*
Controls display of comic on the viewComic template
*/
include 'include/header.php';
global $site, $imgid;
$cat = (isset($_GET['cat']) ? ($_GET['cat']) : null);
$site = (isset($_GET['site']) ? ($_GET['site']) : null);
$title = (isset($_GET['title']) ? ($_GET['title']) : null);
$imgid = $_GET['id'];
include './scripts/keyinput.php';
$newID = $_POST['_newImgId];
echo $newID; //THIS SHOULD ECHO THE UPDATED ID, but it says it is not defined
Any thoughts?
Thanks!
I think the problem with your code is that you are using your Ajax code after the page has already loaded, while trying to change the $_get variables for the initial page load. AFAIK, you need to update the entire page for the "Facebook like" button to change it's ID. Another option would be to use an Iframe. From what I can see, the button's data-href attributes always leads to http://hittingtreeswithsticks.com/ - and that can only be changed by reloading the page using a different attribute.
If you don't mind loading a page for each picture, this can work out for you:
<!-- This is the Like button code -->
<div [...] data-href="http://www.hittingtreeswithsticks.com/<?php echo $_get['id']; ?>"></div>
and the address for this page would be: http://www.hittingtreeswithsticks.com/?id=PAGE_ID
EDIT
Using AJAX, you are calling for data from the backend to be used in the client side, without having to reload the entire page. This data can then be used to alter the code in the client side. In your code, the data is being sent back to you but you are not using it at all, that's why it doesn't work:
$.get('./templates/viewimage.php', { _newImgId : imgIndex },
function(data) {
// This is where you should make use of the data received
}
);
EDIT #2
If you want to dynamically change the Like button's url, take a look at this answer.
Here is a fiddle of the working example:
http://jsfiddle.net/TkFma/4/
I am echoing data into a table with values from my database. It looks like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point
echo "<tr><td>".$somedata."</td></tr>";
?>
So the value of this table row will be displayed based on how much data is in the database. I want to asynchronously update the page, for example the user wants to delete this from the DB. How can I pass this value to javascript with an onClick function? Or is there another way? If I have a link to delete in the table like:
<td><a onClick="delete(ThisValueOfThisTableRow)">Delete</a></td>
And in javascript or jQuery I want to find this value and set it to a variable, then pass it as:
var some_value = //get this value
.ajax{
url: "somephpfile.php"
data:{some_value:value}
}
I think this would be helpful to anyone if they a responsive member page. Please help out!
maybe something like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array) {
?>
<tr>
<td><?=$somedata;?></td>
<td><a href='#' class='delete-btn' id='row-<?=$someID;?>'>Delete</a></td>
</tr>
<?
}//end while
?>
and then for the js event
$('.delete-btn').click(function() {
var id = $(this).attr("id");
id = id.split("-");
data = { "id" : id[1] }
//your ajax here, pass in your data obj
});
best of luck-
PHP
while ( $row = mysql_fetch_array( $result ) ) {
echo '<tr><td><a onclick="delete_row(' . $row['id'] . ')">delete row</a></td></tr>';
}
Javascript
function delete_row( id ) {
alert( id ); //To show you are getting the id remove this for production
//ajax goes here
}
The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston"
success: function(data){
alert('done');
});
<? foreach ($waiting_users as $waiting_user): ?>
<? echo $waiting_user->user_id; ?>
<? endforeach; ?>
I need to define the user id in a javascript variable. What is the best way of doing something like this?
<script type="text/javascript">
var user_id = "<? echo $waiting_user->user_id; ?>"; <-------------???
var post_id = "<? echo $post_id; ?>";
</script>
EDIT
The foreach returns just one user id. It's used to display a user that has signed up for a chat. Then I use the code below which is in end.js to delete the user from a table.
DELETE FROM table WHERE user_id = ? AND post_id = ?;
<a class="end" href="#" title="End">End</a>
$(document).ready(function() {
$("a.end").click(function() {
$.post(base_url + "index.php/home/end", { user_id : user_id, post_id : $(this).attr('id') }, function(data)
{
alert(data);
}, "json");
});
});
I would recommend getting the desired data through a service which you could call from javascript using ajax, but your version works too, although it is a bit messy.
If you really want to write php code that generates javascript code, I recommend you pass the whole object to the client side. Just make it a JSON and javascript will interpret it as a native javascript object.
<script type="text/javascript">
var users = <?php echo json_encode($waiting_user);?>;
// do whatever you want to do with the users
// ex : iterate over all users
for(var key in users)
{
var id = users[key].id;
// ...
}
</script>
UPDATE
If you only want to pass to the client side only the ids of the users, you should loop the users collection (in php) and store them in an array (or object). Then use the mechanism described above :
<?php
$user_ids = [];
foreach ($waiting_users as $waiting_user)
$user_ids[] = $waiting_user->user_id;
?>
// ....
<script type="text/javascript">
var user_ids = <?php echo json_encode($user_ids);?>;
</script>
Collect the user ids in an array and then output that array as JS.
<script type="text/javascript">
<?php
$user_ids = array();
foreach($waiting_users as $u) {
$user_ids[] = $u->user_id;
}
?>
var array_of_user_ids = <?=json_encode($user_ids)?>;
</script>