Well what I want to do is to update image profile picture of the user with jquery from database but it does not pull out the source of image from db.please tell me where I'm wrong.
here is my code
include('../inc/config.inc.php');
$userSession = #$_SESSION["utente"];
$verificaPic = mysqli_query($db,"SELECT pic_profilo FROM users WHERE username='$userSession'");
$row_pic = mysqli_fetch_array($verificaPic, MYSQLI_ASSOC);
$pic = $row_pic["pic_profilo"];
if($row_pic["pic_profilo"] !== ""){
echo "<img src='$pic' class='img-polaroid'>";
}else{
echo '<img src="img/defaultuser.png" class="img-polaroid">';
}
and this is my jquery call
JQ(function($) {
setInterval(function() {
$.get("/ajax/DataProfilo.php",
function(data) {
$("#picprofilo").html(data); // 2pm
});
}, 100);//1000-1 sec
});
If I understand you correctly, then the code below is the DataProfilo.php script, correct? Please make the few minor changes in this code and show me what the result of the AJAX call is from the console. I also need to see the original HTML markup showing what #picprofilo is.
PHP
include('../inc/config.inc.php');
$userSession = #$_SESSION["utente"];
$q = "SELECT pic_profilo FROM users WHERE username='" . $userSession . "'"; // **add this line of code**
echo $q."\n";
$verificaPic = mysqli_query($db,$q); // **change this line of code!!**
$row_pic = mysqli_fetch_assoc($verificaPic);
$pic = $row_pic["pic_profilo"];
if (!empty($row_pic["pic_profilo"])) {
echo "<img src='$pic' class='img-polaroid'>";
} else {
echo "<img src='img/defaultuser.png' class='img-polaroid'>";
}
jQuery
JQ(function($) {
setInterval(function() {
$.get("/ajax/DataProfilo.php",
function(data) {
$("#picprofilo").html(data);
console.log(data);
});
}, 100);//1000-1 sec
});
Related
I want to callout a function without the page is reloading.
I know that this is possible with AJAX but i don't know how it works with calling a function.
I want to put a timer so it will reload the function every 3 seconds, so the users doesnt need to reload the page everytime to see if there is a new message.
$object = new Messages();
$object->ShowMessage($nick);
ShowMessage(); is the function that i want to call out every 3 seconds.
Full code :
public function ShowMessage() {
$st = $this->db->prepare("SELECT * FROM bericht");
$st->execute();
if($st->rowCount() == 0){
echo 'There is no message jet!';
}
foreach ($st as $bericht){
$uid = $bericht['uid'];
$nick = $this->db->prepare("SELECT * FROM users WHERE id=?");
$nick->bindParam(1, $uid);
$nick->execute();
foreach($nick as $name) {
$image = $name['foto'];
if($image == 'nophoto.jpg'){
echo '<img src="image/nophoto.jpg" width="60px" height="30px">';
} else {
echo '<img src="image/'; echo $image.'"'; echo ' width="60px" height="30px">';
}
echo json_encode($name['name']) .': ';
echo json_encode($bericht['message']).' <br> ';
}
}
}
You can do that with ajax. In order to do that, you need to implement ajax client function on frontend and a handler for processing ajax request. In frontend you can use jquery for ajax operations;
setInterval(function() {
$.get( "handler.php", function( data ) {
// You can use data. It is in json format.
// Ex: alert(data.message) . "message" is one of the
// fields of returned array in php handler file
});
}, 3000);
handler.php
<?php
$object = new Messages();
$result = $object->ShowMessage($nick);
// I assume this returns array.
// Ex: array("type" => "error", "message" => "Error occured on feed");
echo json_encode($result);
?>
Update: If you do not want to use json data
Update your code like below. Only use echo, you do not need to return json data.
public function ShowMessage() {
$st = $this->db->prepare("SELECT * FROM bericht");
$st->execute();
if($st->rowCount() == 0){
echo 'There is no message jet!';
}
foreach ($st as $bericht){
$uid = $bericht['uid'];
$nick = $this->db->prepare("SELECT * FROM users WHERE id=?");
$nick->bindParam(1, $uid);
$nick->execute();
foreach($nick as $name) {
$image = $name['foto'];
if($image == 'nophoto.jpg'){
echo '<img src="image/nophoto.jpg" width="60px" height="30px">';
} else {
echo '<img src="image/'; echo $image.'"'; echo ' width="60px" height="30px">';
}
echo $name['name'] .': ';
echo $bericht['message'].' <br> ';
}
}
}
and in js;
setInterval(function() {
$.get( "handler.php", function( data ) {
// alert(data);
});
}, 3000);
You need to do that integrating javascript to your php code.
Using jquery, you can take a look at $.post function. You can rise the event with the javascript function window.setInterval(yourFunction(),3000)
You also need to create a php page that will reply to the Ajax request, that will be passed as a parameter to the $.post
Just call that script via ajax:
.html:
setInterval(function(){
$.ajax({
url: "showMessageScript.php",
type: "post",
data: {nick: $("#nick").val(), token: <?php echo $_SESSION['token']; ?>},
success: function(jsonData){
$('#display').text(jsonData['message']);
}
});
},
3000);
showMessageScript.php:
function showMessage($nick) {
$object = new Messages();
$object->ShowMessage($nick);
echo json_encode(array('message': 'Your message is here'));
}
// check if authorized to do some action
if (!empty($_SESSION['token']) && $_SESSION['token'] == $_POST['token'] && !empty($_POST['nick'])) {
showMessage($nick);
} else {
echo json_encode(array('message': 'not authorized'));
}
There are many posts that are made by users, I want each post (or div in this case) to display the background color green or grey depending on the user status (logged in or not).
What I am trying to achieve is while idling on the page, you should see a user going online without refreshing the page
status.php
if (logged_in() === true){
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
echo "online";
}
}
}
}else {
echo "offline";
}
Main page
$res8 = mysql_query("SELECT * FROM `users` WHERE user_id='".$user_id."' LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
datatype:"application/json",
type: 'GET',
success: function(data) {
if (data === "online") {
$('.status').css({background: '#40A547'});
} else {
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 5000);
});
</script>
<?php
}
}
}
echo '<div class="status">TEST</div></a></div>';
This code changes the background color of all the divs but I want it to only target the divs that correspond to the user that logged in (the creator of the post).
Not sure how to make the div have the dynamic styling using ajax.
Any help is much appreciated!
You can use the id user from the database to achieve this. Then add an id to the div corresponding to the user id. For instance :
Ajax Request in success :
$('.status #user'+ dataId).css({background: '#7f8c8d'});
In your HTML :
echo '<div class="status" id="user1">TEST</div></a></div>';
Edit
Your Main page (your AJAX request)
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.message === "online")
{
$('.status #user'+ data.userId).css({background: '#40A547'});
} else // data.message === "offline"
{
$('.status #user'+ data.userId).css({background: '#7f8c8d'});
}
}
});
//...
// HTML looks like...
echo '<div class="status" id="user1">TEST</div></a></div>';
echo '<div class="status" id="user2">TEST2</div></a></div>';
status.php
You set the dataType of your ajax request that you want return Json but it's unclea, your your status.php add the header content-type to json.
<?php
header('Content-Type: application/json'); // So add this
//...
$array = array(); // New variable which would be return as json
if (logged_in() === true) // Your online part
{
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
$array['message'] = 'online';
$array['userId'] = $row8['user_id']; // Here is the userId (adapt following your code)
}
}
}
}// Your offline part
else {
$array['message'] = 'offline';
}
echo json_encode($array);
I have a script that loads sample images from DB on page load from relevant category in the DB.
<?php
$category = 'granite';
$samples = 'SELECT * FROM material WHERE material_type = :cat';
$res = $db->prepare($samples);
$res->execute(array(':cat' => $category));
$count = $res->rowCount();
if($count > 0)
while ($row = $res -> fetch()){
$postimggranite = $row[mat_image];
$postidgranite = $row[id];
?>
<?php
echo "<div class='sample'>";
echo "<h3 class='sample_h'>$row[name]</h3>";
echo "<a href='/images/granite-worktops/samples/$postimggranite'><img src='/images/granite-worktops/thumbs/$postimggranite' alt='$row[name]' width='100' height='100' class='aligncenter size-full' title='$row[name]'></a>";
echo "<br /><a class=\"button\" href=\" \" rel=\"nofollow\" onClick=\"user_notice(this,''); return false;\">More Details</a>";
echo "</div>";
}
?>
As you can see from the script above in the last echo before closing a div I have a "More Details button, by clicking on which the dialog appears on the screen where I need to display additional information from the same DB. Method I am planning to use is
function user_dialog(a,b){
"undefined"!=typeof jQuery.ui?($("#dialog").attr("title","Detailed Information").html(a),
$("#dialog").dialog({
modal:true,
width:400,
buttons: {
Cancel: function() {
$(this).dialog("close");
},
Download: function(){
$(this).dialog("close");
window.location=b
}
}
}
))
:window.location=b}
function user_notice(a){
download_link=$(a).attr("href");
$.ajax({
type:"POST",
url:"/includes/json.php",
data:"action=reminder&thepath="+download_link,
dataType:"json",
error:function(){
window.location=download_link
},
success:function(a){
1==a.status&&user_dialog(a.html,download_link);
}
})
};
Here also the script of my json.php file
<?php
header('X-Robots-Tag: noindex, noarchive');
$a = session_id();
if(empty($a)) session_start();
if($_SERVER['HTTP_REFERER']){
$resp_dialog = array(
'status' => 1,
'html' => '<p>Here is you sample and rest of staff</p>'
);
echo json_encode($resp_dialog);
}else{
header('HTTP/1.1 403 Forbidden');
exit;
}
?>
clearly it all works and the line <p>Here is you sample and rest of staff</p> is appearing in the dialog, but what I actually need is to create a json object that brings additional info from DB and have no idea where, inside the json.php file or create some sort of additional file and place in href with urlid="something to get fromdb" than $_GET['urlid'] in the json.php to send it do DB. Basically have no idea of what and where to do it.
Please go easy on me since I am still learning this all and most of it is still pretty new for me, so forgive me if I have not explained something correctly.
You need to pass in your $.ajax the id of the category you want to detail.
$.ajax({
type:"POST",
url:"/includes/json.php",
data:['cat_id': cat_id], // passing var cat_id from the link...
Then your json.php file should be like:
<?php
header('X-Robots-Tag: noindex, noarchive');
$a = session_id();
if(empty($a)) session_start();
if($_SERVER['HTTP_REFERER']){
$cat_id = $_POST['cat_id']; // Grab the Id of the category you want to detail...
// Here you have to fetch the info from the DB...
$samples = '... WHERE cat_id = :cat'; // Create the sql here!
$res = $db->prepare($samples);
$res->execute(array(':cat' => $cat_id));
$count = $res->rowCount();
$htmlToDisplay = '';
if($count > 0)
while ($row = $res -> fetch()){
$htmlToDisplay += $row['...']; // format yout output...
}
$resp_dialog = array(
'status' => 1,
'html' => $htmlToDisplay,
);
echo json_encode($resp_dialog);
}else{
header('HTTP/1.1 403 Forbidden');
exit;
}
?>
Edit:
To create the "more details" link, try to do this:
echo "<div class='sample'>";
/* ... */
// Passing $row[id] to user_notice() function!
echo "<br /><a class=\"button\" onClick=\"user_notice(this,". $row[id] ."); return false;\">More Details</a>";
echo "</div>";
And then, change the user_notice() function to this:
function user_notice(a,cat_id){ // New parameter cat_id!
download_link=$(a).attr("href");
$.ajax({
type:"POST",
url:"/includes/json.php",
data:{ cat_id: cat_id }, // Passing cat_id to json.php... don't forget to pass your other variables
/* ... */
Look how to pass variables through $.ajax here
In $.Ajax() function change your passing Data from
data:"action=reminder&thepath="+download_link,
to
data: "{'action':'reminder','thepath':'"+download_link+"'}"
I have a search function that calls a php file onkeyup. Now in JQuery i have a onClick function that when you click a div from that same JSON call it alerts something, maybe it will be easier to understand from my code below:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];
if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);
foreach($Term as $Key)
{
$I = 0;
$I++;
if($I == 1)
{
$Search .= 'Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
else
{
$Search .= 'OR Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
}
if($Result = $Connect->query($Search))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$USearch['S'][] = '<div class="Result"><label class="TText" style="cursor:pointer;">' . $User . '</label></div>';
}
}
}
echo json_encode($USearch);
?>
Now, as you can see, once the user types into a box a div shows up showing all LIKE records of Users, once the div is clicked on nothing happens.
$('.Result').click(function()
{
alert('Hi');
});
When the ajax call return a state of success you can use for example the jquery bind method. (see here for more info http://api.jquery.com/bind/ )
function myAjaxFunct(val){
$.ajax(
{
type: "POST",
url: myPhpFile.php,
datatype: "jsonp",
data: {val: val},
success: function (result) {
$("#jsonResultDisplay").text(result);
$('.Result').bind('click', function() {
alert('hi');
});
}
});
}
You are dynamically creating element that is why it doesn't work.
Use on()method.
Check an example:
http://jsfiddle.net/pZQ8T/
jQuery:
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast")
.load("home.php div#update").fadeIn("fast")
});
});
PHP:
function statusUpdate() {
$service_query = mysql_query("SELECT * FROM service ORDER BY status");
$service_num = mysql_num_rows($service_query);
for ($x=1;$x<=$service_num;$x++) {
$service_row = mysql_fetch_row($service_query);
$second_query = mysql_query("SELECT * FROM service WHERE sid='$service_row[0]'");
$row = mysql_fetch_row($second_query);
$socket = #fsockopen($row[3], $row[4], $errnum, $errstr, 0.01);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
mysql_query("UPDATE service SET status='$status' WHERE sid='$row[0]'")
or die(mysql_error());
?>
<ul><li style="min-width:190px;"><?php echo $row[1]; ?></li>
<li style="min-width: 190px;" title="DNS: <?php echo $row[2]; ?>">
<?php echo $row[3] . ':' . $row[4]; ?></li>
<li class="<?php echo $status; ?>" style="min-width:80px;"><div id="update">
<?php echo $status; ?></div></li></ul>
<?php
}
}
?>
<?php statusUpdate(); ?>
I have a button which I press (refresh) and that will then refresh the #update id to hopefully fadeOut all the results, and then fade in the new results... issue is it fades them out okay, but when it brings them back, it's just div on div and div and looks really messy - does not do what it's meant to do (would have to upload a picture to give further information).
In the short, what I want to happen is when you hit the update, they will all fade and then fade in with updated values from the php... I made the php/mysql into a function so then I could call it when i hit that refresh button, thinking that would work, but I don't know how to do that...
Thank-you in advance,
Phillip.
Javascript
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast");
$.ajax({
url:'home.php',
data:{type:'getStatus'},
type;'post',
success:function(data){
$('div#update').html(data).fadeIn('fast');
}
});
});
});
php page format
<?php
$type= $_POST['type'];
if($type=="getStatus")
{
//get statuses from data base and return only formatted statuses in html
}
else
{
//your page codes here
//like tags <html>,<body> etc, all regular tags
//<script> tags etc
}
?>
.load("home.php div#update").fadeIn("fast")
That's wrong. You need to use,
$('div#update').load('home.php', function(data) {
$('div#update').html(data).fadeIn("fast");
});
Make sure your PHP file works properly by calling it directly and confirming that it returns the results properly.
Reference : http://api.jquery.com/load
Try this
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('home.php div#update', function() {
$data.fadeIn('slow');
});
});
Just for the reference, it will be better to add an additional page in the same directory (eg: phpcode.php) and then put your php code also in there! then try this:
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('phpcode.php div#update', function() {
$data.fadeIn('slow');
});
});