I have a separate PHP file containing a valid mysql query returning # of Rows representing my criteria (No. of active Notifications), and I have a JQUERY code to display notifications counter, but I only can use it statically with .text('5') for example. I want to be able to link the PHP MYSQL query result to the JQUERY output on browser.
notfcounter.php:
<?php
function getNotCount() {
require_once $_SERVER['DOCUMENT_ROOT'] . 'info.php';
$conn = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
$count = $_POST['action'];
$sqlquery = "SELECT did FROM users WHERE users.uid=".$_SESSION['id'];
$result = $dbc->query($sqlquery);
while ($row = $result->fetch_assoc()) {
$rows = $row['did'];
}
$countquery = "SELECT noname, noaction FROM notfs WHERE notfs.did=".$rows." AND notfstatus = 0";
$result2 = $dbc->query($countquery);
if (mysqli_num_rows($result2)!=0)
{
$count = mysqli_num_rows($result2);
echo ''.$count.'';
}
else
{
$count = 0;
echo ''.$count.'';
}
echo $count;
}
?>
JQUERY external file:
$(document).ready(function () {
// ANIMATEDLY DISPLAY THE NOTF COUNTER.
$('#notfs_Counter')
.css({ opacity: 0 })
//.text('5') this is what I use to display a counter statically
$.ajax({
type: 'post',
url: 'notfcounter.php',
data: {action: 'getNotCount'},
success: function(data) {
alert(data);
}
})
.css({ top: '0px' })
.animate({ top: '0px', opacity: 1 }, 500);
});
after researching more about AJAX, I got to understand it better and knew where I was wrong.
I had to adjust my code to reposition the $(selector). commands inside the AJAX success function call to properly display my data. Also, I didn't need a function on my PHP code, I removed the function and echo'd the needed variable for display $count, and modified AJAX action to count, code is below:
AJAX & JQUERY:
$.ajax({
type: 'post',
url: 'notfscounter.php',
data: {action: 'count'},
success: function(data) {
//alert(data)
$('#notfs_Counter').css({opacity: 0})
$('#notfs_Counter').text(data)
$('#notfs_Counter').css({ top: '0px'})
$('#notfs_Counter').animate({ top: '0px', opacity: 1 }, 500);
}
});
PHP:
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . 'info.php';
$conn = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
$sqlquery = "SELECT did FROM users WHERE users.uid=".$_SESSION['id'];
$result = $dbc->query($sqlquery);
while ($row = $result->fetch_assoc()) {
$rows = $row['did'];
}
$countquery = "SELECT noname, noaction FROM notfs WHERE notfs.did=".$rows." AND notfstatus = 0";
$result2 = $dbc->query($countquery);
if (mysqli_num_rows($result2)!=0)
{
$count = mysqli_num_rows($result2);
echo ''.$count.'';
}
else
{
$count = 0;
echo ''.$count.'';
}
echo $count;
?>
special thanks to #ADyson for his encouraging & helpful guide.
Related
I am creating a simple comment program. i want to use ajax to refresh the comments and total number of comments. Keeping both functions in a single file is not working for me.
here is my code:
HTML:
<h3></h3>
<ul>
</ul>
PHP: include.php
//for comments
function main(){
try {
$query = connect()->prepare("SELECT * FROM comments WHERE article_id = 1627359589");
$query->execute();
echo json_encode($query->fetchAll());
} catch (PDOException $e) {
die("database connection failed");
}
}
// for total comment
function totalComment(){
$sql ="SELECT * FROM comments WHERE article_id = 1627359589";
$stmt = connect()->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
echo json_encode($num);
}
main();
totalComment();
AJAX:
// for comment
setInterval(displayComments, 2000);
function displayComments(){
$.ajax({
url: "include.php",
type: "POST",
dataType: "JSON",
success: function(data){
for (var i = 0; i < data.length; i++) {
$("ul").append("<li>"+data[i] + "</li>")
}
}
})
}
// for total comments
setInterval(total, 2000);
function total(){
$.ajax({
url: "include.php",
success: function(data){
$("h3").html(data);
}
})
}
Set the PHP to process a named POST item and use switch to determine which function to use:
<?php
if( $SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cmd'] )){
function main(){
try {
$query = connect()->prepare("SELECT * FROM comments WHERE article_id = 1627359589");
$query->execute();
echo json_encode($query->fetchAll());
} catch (PDOException $e) {
die("database connection failed");
}
}
function totalComment(){
$sql ="SELECT * FROM comments WHERE article_id = 1627359589";
$stmt = connect()->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
echo json_encode($num);
}
switch( $_POST['cmd'] ){
case 'comments':
main();
break;
case 'total':
totalComment();
break;
case 'banana':
banana();
break;
}
}
?>
In your javascript set the same parameter in each request but with a different value: data:{cmd:'banana'}, etc
function displayComments(){
$.ajax({
url: "include.php",
type: "POST",
data:{cmd:'comments'},
dataType: "JSON",
success: function(data){
for (var i = 0; i < data.length; i++) {
$("ul").append("<li>"+data[i] + "</li>")
}
}
})
}
function total(){
$.ajax({
url: "include.php",
data:{cmd:'total'},
success: function(data){
$("h3").html(data);
}
})
}
setInterval(displayComments, 2000);
setInterval(total, 2000);
Currently, I made script, which after onclick event,sending question to the database and showing data in console.log( from array ). This all works correctly, but.. I want to show data from array in the different position in my code. When I try to use DataType 'json' and then show some data, then it display in my console.log nothing. So, my question is: How to fix problem with displaying data? Is it a good idea as you see?
Below you see my current code:
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
//console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "text",
data: {id:id},
success: function(data){
console.log(data);
}
});
});
});
:
public function GetPlayer($id){
$id = $_GET['id'];
$query = "SELECT name,surname FROM zawodnik WHERE id='".$id."'";
$result = $this->db->query($query);
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
$this->PlayerInfo[] = $row;
}
return $this->PlayerInfo;
}else {
return false;
}
}
:
$info = array();
$id = $_GET['id'];
$vv = new AddService();
foreach($vv->GetPlayer($id) as $data){
$info[0] = $data['name'];
$info[1] = $data['surname'];
}
echo json_encode($info);
I think it would be better to change the line fetch_all in mysqli to rm -rf. That information in the DB is all obsolete, or completely not true.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="profile" data-id="1">Click</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "json",
data: {id:id},
success: function(data){
console.log(data);
$.each(data, function(idx, item) {
console.log(item.surname);
});
}
});
});
});
</script>
</body>
</html>
PHP side:
<?php
class AddService {
public function GetPlayer($id) {
if (filter_var($id, FILTER_VALIDATE_INT) === false) {
return false;
}
$query = "SELECT name, surname FROM zawodnik WHERE id={$id}";
$result = $this->db->query($query);
if ($result->num_rows <= 0) {
return false;
}
// assumming you are using mysqli
// return json_encode($result->fetch_all(MYSQLI_ASSOC));
// or
WHILE ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$vv = new AddService();
// you don't need foreach loop to call the method
// otherwise, you are duplicating your results
echo $vv->GetPlayer($id);
}
When you load the page, I have two separate divs that get images randomly from a database then echo them as the background-image. I also get other data that comes along with the image.
I need to get data from a new PHP file and change the background-image of a div on click of a button (so that you don't need to refresh the page).
In getnew.php:
$select = mysqli_select_db($conn, "database");
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row = $result->fetch_assoc();
$img1link = $row['link'];
$rating1 = $row['rating'];
$s1 = $row['sigma'];
$result2 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
$rating2 = $row2['rating'];
$s2 = $row2['sigma'];
In main.php:
$("#button").on("click",function(){
//
})
As I understand it you use jQuery's $.get to fetch the data from getnew.php but how exactly can I then use the data to change the background-image without having to refresh the page?
For example: style="background-image: url('<?php echo $img1link ?>')">
You'll need to use ajax, send data from the server and parse it at the client
Here is a code sample based on your snippet
In getnew.php:
$select = mysqli_select_db($conn, "database");
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
$row = $result->fetch_assoc();
$img1link = $row['link'];
$rating1 = $row['rating'];
$s1 = $row['sigma'];
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
$rating2 = $row2['rating'];
$s2 = $row2['sigma'];
echo json_encode(array('img1'=>$img1link,'img2'=>$img2link));
In main.php:
$("#button").on("click",function(){
$.getJSON("getnew.php",function(data){
//use data.img2 and data.img1 and set the background
// for example: $('#someDiv').css('background-image',"url('"+data.img1+"')");
});
})
use JQuery CSS codes..as you are able to fetch the data from a page, pass the image path in jquery.css code, it will do as per your desire.
Try to analyze the code
Place it in a finction which will be called on click of the function:
on success you may use css like code:
This is just an example in ajax/jquery
$.ajax("signin.php", {
data: {
login: login,
pass: pass
},
success: function(data)
{
//alert(data);
if (data==1)
{
s$("#login").animate({ opacity: 1,top: '49%' }, 200,function(){
$('.userbox').show().animate({ opacity: 1 }, 500);
$("#login").animate({ opacity: 0,top: '60%' }, 500,function(){
$(this).fadeOut(200,function(){
$(".text_success").slideDown();
$("#successLogin").animate({opacity: 1,height: "200px"},500);
});
})
})
}
else
{
alert(data);
setTimeout( "unloading()", 1000 );
showError('OOPS..please check the credentials..');
}
},
error: function()
{
//alert(data);
showError('OOPS..Error in Connection..');
},
type: "POST"
});
Just a quick script, but hope it helps:
in getnew.php
$select = mysqli_select_db($conn, "database");
function get_random_image(){
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row = $result->fetch_assoc();
$result=[
'link' => $row['link'],
'rating' => $row['rating'],
'sigma' => $row['sigma']
];
return $result;
}
if($_POST['request']=='get_random_image'){
$r = array();
array_push($r, get_random_image());
array_push($r, get_random_image());
echo json_encode($r);
}
in javascript file:
$("#button").on("click",function(){
show_image();
})
function show_image(){
var response = get_data("get_random_image");
response = jQuery.parseJSON(response);
$.each( response, function( key, value ) {
// do something with the data like this:
$('.image').append('<img src="'+value.link+'">');
}
}
function get_data(requested_action)
{
var data=$.ajax({
type: "POST",
url: '../getnew.php', // relative path to the php file
data: {
request:requested_action
},
async: false,
dataType: 'json'
});
var msg= data.responseText;
return msg;
}
If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...
<script type="text/javascript">
function dispMsg() {
$("#displayMessage").load('load.php');
var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
$("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage"></div>
and here is the load.php:
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$id = $result['id'];
$from = $result['user_01'];
$to = $result['to_usr'];
$message = $result['message_01'];
$date = $result['date_send'];
echo "<span class='from'> $from </span>"
. "<span class='message'> $message </span> <br/>";
}
use the parameters and call back of $.load()
$.load(url, {param1:value, param2:value}, function(result){
if(result >5){
//do something
}
)
Example:
<?php
if($_REQUEST['action'] == 'check'){
if($_REQUEST['lastId'] < 5 ){
echo $_REQUEST['lastId']+1;
die;
}
}
if($_REQUEST['action'] == 'load'){
echo 'some conntent!';
die;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var lastId = 0;
function dispMsg() {
$.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
if(responce !== 0){
alert(responce);
$('#displayMessage').load('tmp.php', {action:'load'});
}
});
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage">1</div>
You can send the last message id with each request. If the last message of your query is greater than the id sent, send the response. Otherwise send nothing.
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "load.php",
type: "POST",
data: {
last: last
},
cache: false,
success: function(html){
//insert message
}
});
}
You can send the id as the id attribute in your HTML. Each message in the chat window is sent as a paragraph with some message id such as id="133".
Expanding on #Pé de Leão's solution, here's something more simple:
<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
$msg = $result->fetch_assoc();
if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
}
}
And on the client side:
function dispMsg() {
var last = $('#displayMessages span.from').attr('id');
$.get(baseUrl + '/load.php', { last: last }, function(result) {
if (result) {
$('#displayMessages').html(result);
}
});
}
Note that this replaces everything in displayMessages.
I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.