Reload a function without reloading the page - php

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'));
}

Related

AJAX Success function never true

I don't know why my success function isn't working. I mean although it passes the JSON data to the PHP file and changes the password.
// this is the id of the form
$("#password_form").submit(function(e) {
e.preventDefault();
$(".verify-user-loader").addClass("force-display-block");
password = $("input#password-reset").val();
url = 'reset-pass.php';
$.ajax({
type : 'POST',
url : url,
dataType : 'json',
data : {
cardnumber: <?php echo '\''.$cardnumber.'\''; ?>,
act_token: <?php echo '\''.$activationToken.'\''; ?>,
password: password
},
success : function(success){
alert("success");
},
error : function(request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
});
This file works as expected, it changes the password using the POST data
reset-pass.php
include_once '/../login/user.class.php';
$activationToken = $_POST['act_token'];
$cardnumber = $_POST['cardnumber'];
$password = $_POST['password'];
$user = new User();
$verifyToken = $user->verifyToken( $activationToken, $cardnumber );
if ($verifyToken['status'] === true) {
$tokenStatus = "inactive";
$user->signUp( $cardnumber, $password );
$user->changeTokenStatus( $cardnumber, $tokenStatus );
$success = true;
return $success;
}else{
print_r($verifyToken);
}
You should use echo instead of return, because when you work without function you should need to use echo.
So the code will be
echo true; // or you can write echo $success = true;
exit(); // exit is use to stop further processing of code.
1 ) you need to echo $success; instead of return $success;
Ajax response should be any browser out put (i.e like html or echo or print_r these are browser output ) . instead of return .
2) simple add data like this
........
data : {
cardnumber: '<?php echo $cardnumber; ?>',
act_token: '<?php echo $activationToken; ?>',
password: password
},
........

AJAX Unique ID div color change per post if user logs in

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);

update image profile with jquery

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
});

Div onClick With JSON Call Doesn't Work

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/

Using ajax to grab information from database

I m using codeigniter and would like to grab some user info with ajax. This is what I have but it s not working
In the view I have a defined variable:
<script type="text/javascript">
var end_user = "<? echo $user_id; ?>";
</script>
<div id="tabs6"></div>
js file:
function get_experience()
{
$.post(base_url + "index.php/home/get_experience", { user : end_user }, function(data) {
if (data.status == 'ok')
{
$("div#tabs6").html(data);
}
else
{ //nothing }
}, "json");
}
get_experience();
controller:
public function get_experience()
{
$this->load->model('experience_model');
$end_user = $this->input->post('user');
$one_exp = $this->experience_model->one_exp($end_user);
if ($one_exp->num_rows() > 0)
{
$one_exp_html = '<ul>';
foreach($one_exp->result() as $exp)
{
$one_exp_html .= '<li>';
$one_exp_html .= $exp->experience;
$one_exp_html .= '</li>';
}
$one_exp_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $one_exp_html);
return json_encode($result);
exit();
}
else
{
$result = array('status' => 'ok', 'content' => 'nothing here');
return json_encode($result);
exit();
}
}
model:
function one_exp($end_user)
{
$query_str = "SELECT experience FROM exp WHERE user_id = ?";
$query = $this->db->query($query_str, $end_user);
}
You need to add return $query to your one_exp method.
EDIT
You're setting user_id in your view, but then using end_user in your javascript function get_experience().
Also, since it's json you'll need to change the html fill to
$("div#tabs6").html(data.content);
For more debugging add an alert to your callback (right before if (data.status == 'ok') add alert(data);)
You've got to echo the result out I think, not return it.
I am not sure but problem occurs in end_user value in js.Try this oneView File:
<script type="text/javascript">
var end_user = "<? echo $user_id; ?>";
get_experience(end_user);
</script>
<div id="tabs6"></div>
The js file:
function get_experience(foo)
{
$.post(base_url + "index.php/home/get_experience", { user : foo }, function(data) {
if (data.status == 'ok')
{
$("div#tabs6").html(data);
}
else
{ //nothing }
}, "json");
}

Categories