Reload <body> with jQuery and PHP - php

I have an index.php that updates every second user sessions:
[Index.php (before )]
<script type="text/javascript">
$(function($) {
var refresh = setInterval(function() {
$.post('myfolder/reload_info.post.php', {
id: <?php echo $_SESSION['id']; ?>
}, function(data){
clearInterval(this);
});
}, 1000);
});
</script>
[reload_info.post.php]
(sql query... // $row is the result)
$_SESSION['name'] = $row->name;
$_SESSION['mail'] = $row->mail;
$_SESSION['status'] = $row->stat;
$_SESSION['cf'] = $row->cf;
All functions of the site using any session are usually charged if there is any change in the database (MySQL). What I would like is to update the body of index.php () without reloading the page.
That is, if I open the index.php file and have nothing between the and editing the file I put any text after this a second, carrying the text without having to press F5 or take a location.reload ().
Is it possible? Thank you. :)

Perhaps you are after something like joconut: https://github.com/vdemedes/joconut

you want something like this?
<script type="text/javascript">
$(function($) {
var id="<?php echo $_SESSION['id']; ?>";
var refresh = setInterval(function() {
$.post('myfolder/reload_info.post.php', {
id: id;
}, function(data){
clearInterval(this);
$('body .container').html(data);
});
}, 1000);
});
</script>
in reload_info.post.php you should return something...
echo echo $_SESSION['id'];

Related

How to fetch data from database based on user input and display as JSON array using asynchronous POST in php

I have 1 php page which establishes connection to the database and fetches data from the database using JSON array (this code is working fine).
index2.php
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$uid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I created one more HTML page where i am taking one input (userid) from the user. Based on userid, i am fetching more data about that user from the database. Once the user enters userid and clicks on "Get_Logs" button, more data will be fetched from the the database.
<!DOCTYPE html>
<html>
<head>
<title>User_Logs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$uid =$_POST["USERID"];
}
?>
<form method="POST" id="form-add" action="index2.php">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
</body>
</html>
My script:
$(document).ready(function(){
$("#mybtn").click(function(){
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
})
This code is working fine. However it is synchronous POST & it is refreshing my page, However i want to use asynchronous POST. How can i do that? I have never done this asynchronous POST coding. Kindly help.
i tried this & it not throwing error but there is no output. Can someone please check what is wrong in my code.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.post("index2.php", {data :'<?php echo json_encode($json_array);?>'
})
});
})
I assume that index2.php is another php page (not the same) and it is returning the data that you want to update on the page where you run this code on.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.POST("index2.php", {
var myVar = "<?php echo json_encode($json_array); ?>";
});
});
})
you need to add preventDefault in your click handler to prevent the form from being submitted. This will stop the form to be submitted and the page to be reloaded. Inside the POST you can setup the logic to refresh the page with the updated data (without reloading)
Can you try this,
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
});
Also in HTML remove action in form
<form method="POST" id="form-add">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
Edit :
Can you try this please ? Second param for post takes an object .
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
var myVar = <?php echo json_encode($json_array); ?>;
console.log(myVar);
$.post("submit.php", {
'id': myVar
},function(data){
console.log(data);
});
});
});

reading facebook token in url, storing in cookie, echoing in file

I have a multi -part process
step 1:on page.php I evoke a facebook pop-up authentication window with the URI going to page2.php
https://facebook.com/dialog/oauth?client_id=ID&redirect_uri=http://domain.com/page2.php?-Your+Special+Token+1170-&type=user_agent&fbconnect=1&scope=publish_stream
on page2.php I want to process this token by reading it from the url and storing it as a cookie
<?php
session_start();
if ( empty($tkn) ) { ?>
<script>
(function () {
try {
var q = location.href.split('#');
var a = q[1];
var q2 = a.split('=');
var a2 = q2[1];
var q3 = a2.split('&');
var a3 = q3[0];
setTimeout(function () {
top.location.replace('http://domain.com/cookie.php?tkn=' + a3);
}, 200);
} catch (e) {
top.location.replace('http://domain.com/cookie.php?retry=1&tk=broken_' + encodeURI(e.message));
}
})()
</script><? } else {
print $_GET['tkn'];
}
$_SESSION['tkn'] = $tkn;
$tkn = $_POST["tkn"];
if(isset($tkn)) {
setcookie("tkn", $tkn);
echo "success";
}
?>
page.php detects the cookie and echoes out the token $tkn and reloads the page
<?php
session_start();
?>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$.post('page2.php',{tkn: tkn}, function(data){
if(data=='success'){
location.reload(true)
}
});
</script>
<?php echo $tkn; ?>
the problem is I cant get any of this to work. The popup goes into an infinite error loop and nothing is refreshed or echoed.

Strange Ajax/jQuery/PHP login issue

I have a dynamic login header. 2 links, login / register and profile / logout.
I have a php class function that was being used to check if logged in and displaying relevant links, it worked fine.
I then moved to an ajax login as I didn't want a page refresh and the login box drops down and rolls back up. Again, it works fine.
I've noticed a slight issue, by slight I mean very irritating :)
Once logged in, Every single page refresh on new page shows a flicker where 'profile' becomes 'login' and then flickers back again. It only happens when the page is loading and doesn't last long but it's not very nice.
Could someone help me solve it please? I'm pretty new to Ajax/jQuery and spent ages wiht the help of some guys in here getting the ajax/jquery part functional in the first place.
this is script that toggles the login divs
<script>
window.onload = function(){
$(function() {
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
$("#loggedIn").toggle(loggedIn);
$("#loggedOut").toggle(!loggedIn);
});
}
</script>
Thanks
EDIT: Ajax
function validLogin(){
$('#error').hide();
var username = $('#username').val();
var password = $('#password').val();
if(username == ""){
$('input#username').focus();
return false;
}
if(password == ""){
$('input#password').focus();
return false;
}
var params = {username: username, password: password};
var url = "../loginProcessAjax.php";
$("#statusLogin").show();
$.ajax({
type: 'POST',
url: url,
data: params,
dataType: 'json',
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= '<img src="../images/loginLoading.gif" /> checking...' ;
},
success: function(data) {
$("#statusLogin").hide();
if(data.success == true){
$('#loggedIn').show();
$('#loginContent').slideToggle();
$('#loggedOut').hide();
}else{
// alert("data.message... " + data.message);//undefined
$("#error").show().html(data.message);
}
},
error: function( error ) {
console.log(error);
}
});
}
Use PHP to hide the unwanted element by doing the following
<?php
$loggedIn = $general->loggedIn();
?>
... Some HTML
<div>
<div id="loggedIn" <?php echo ( $loggedIn ? '' : 'style="display: none;"' ); ?>>
.... Logged in stuff
</div>
<div id="loggedOut" <?php echo ( !$loggedIn ? '' : 'style="display: none;"' ); ?>>
.... Logged Out Stuff
</div>
</div>
<script>
var loggedIn = <?php echo json_encode($loggedIn); ?>;
$('#loginForm').submit(function() {
... Handle form submit
... When ajax returns true or false we can set loggedIn and then toggle the containers
});
</script>
// CSS-Stylesheet
#loggedIn,
#loggedOut {display: none}
<script>
$(document).ready(function() {
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
if (loggedIn == true) { // i can just guess here...
$("#loggedIn").show();
}
else {
$("#loggedOut").show();
}
});
</script>
Three possible solutions:
If the script element is placed inside the body, move
it to head element.
Use the following script instead:
$(document).ready(function () {
'use strict';
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
$('#loggedIn').toggle(loggedIn);
$('#loggedOut').toggle(!loggedIn);
});
Hide both links in the "logged in" div using $('#loggedIn
a).hide(); and then, show them on the window.onload event using
$('#loggedIn a).show();. A bit dirty, bit it may work.

Ajax not working in chrome. Can anyone save me?

I have this code on my page...
the jQuery
window.setInterval( function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});},10);
This is the get_posts.php
<?php
include('dbconnect.php');
session_start();
$uid= $_SESSION['uid'];
$get_ids=mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($get_ids)){
$id=$row['id'];
$sm=$row['message'];
}
$get_lpid=mysql_query("SELECT * FROM users WHERE uid='$uid'");
while($row_o = mysql_fetch_array($get_lpid)){
$l_pid=$row_o['lastviewed'];
}
if($id!=$l_pid){
$insert=mysql_query("UPDATE users SET lastviewed='$id' WHERE uid='$uid' ");
if($insert){?>
<div class='media'><img src='img/profile_pictures/thumbs/thumb_13718921232_119055628287843_1500172795_n.jpg' class='img-circle post-circle pull-left'><div class='media-heading'><a href='#'>Pratik Sonar</a><div class='pull-right'><small>12.00PM</small></div></strong></div><div class='media-body'><?php echo $sm ?></div></div>
<?php } else{
}
}
else{
}?>
This technique seems to work on every browser except chrome. I have tested ie, safari, firefox and opera all are working. Can anyone enlighten me on this thing? Is there something I don't know or am I missing?
Try to wrap your code into this function:
$(document).ready(function() { ... });
Like:
$(document).ready(function() {
window.setInterval( function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});},10);
});
You're probably better off using setTimeout() too.
Now the code runs when the DOM is fully loaded.
Why are you using window.setInterval?
It's simply setInterval(), without any parent.
Try
$(document).ready(function() {
setInterval(function(){
$.get("php/get_posts.php", function(data) {
$('.post-container').prepend(data);
});
},10);
});
Thank You guys for all your concerns. Well at last the bug got fixed by this chunk of code. I guess setTimeout gain gains victory over setInterval
$(document).ready(function() {
window.setTimeout(function(){
$.ajax({
type: "GET",
url: "php/get_posts.php",
}).done(function( data ) {
$('.post-container').prepend(data);
});
},10);
});

How to merge php-mysql data with jquery to fade data

I'm having a simple select statement using php-mysql and I have this script to change text with another.
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("text2");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<div id=deletesuccess > text1 </div>
Trying to display data from table using php-mysql and jquery above script but it's displaying only the last row the loop is not working
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("<?php echo $row['desc']; ?>");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<?php
}
But couldn't use it with the above PHP code to display data one by one.
You can do this easily by using jQuery ajax.
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
url: 'getData.php',
dataType: 'json',
type: 'POST',
success: function(data) {
$('#deletesuccess').delay(500).fadeOut(function(){
$.each(data,function(key, value){
$('#deletesuccess').html(value);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
}
});
});
</script>
Now in getData.php page you need to do query and echo json_encode data. That means the getData.php file should contain the following code:
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
$json = '';
while($row = mysql_fetch_array($getTextR)){
$json .= $row['desc'];
}
echo json_encode($json);
?>
Attention, you have not a clear difference between php and javascript code execution. The php code will make an echo of that javascript code, and after php has finish execution(on document ready) the javascript code will be executed at istant, so the last echo of javascript will have effect in the execution. try to separate the codes.
The problem is that you overwrite your JavaScript each time the loop runs. Instead you should make it like this:
<script type="text/javascript">
var php_results = '';
</script>
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
php_results += "<?php echo $row['desc']; ?> | ";
</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html(php_results);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
Of course this would have to be cleaned up to make it pretty, but it should work. I added the pipe as a separator between the different descriptions from the database.

Categories