page AUTO-UPDATE when database changes - php

At the moment, everything is working fine with the script, I insert data in my database, I refresh and I get the username with the new message. However I'm trying to figure out how to have the message added onto the page as soon as the database is updated without having to refresh.
Simple HTML, Here's where the messages load up
<div id="msg">
</div>
Whenever the page is done loading, I'm calling AJAX to get the data
<script type="text/javascript">
$(function(){
//AJAX
var hr = new XMLHttpRequest();
var url = "exampleclass.php";
var msg = document.getElementById("msg");
hr.onreadystatechange=function()
{
if (hr.readyState==4 && hr.status==200)
{
document.getElementById("msg").innerHTML=hr.responseText;
}
}
hr.open("GET", url, true);
hr.send();
});
</script>
Here is my PHP form that retrieves data
<?php
include('inc/connect.php');
$query = "SELECT message, user_name "
. "FROM chat "
. "WHERE (user_name='bryan' or user_name='derek') "
. "AND (user_to='derek' or user_to='bryan')";
while ($retrievedata = mysql_fetch_assoc($sql)){
echo $retrievedata['user_name'].": ".$retrievedata['message']."<br/>";
}
?>

Related

Unable to execute statement in php only when user selects yes in dialog box

Hi am trying to insert data into mysql only when user enters yes in confirm dialog but the data always inserted into mysql even if the user enters no.Here is my code..
<?php if (mysqli_num_rows($data_query) >= 1) { ?>
<script>
var txt;
var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it')
if (r == true) {
<?php
$query="INSERT INTO video_data(date) " ;
$query .= "VALUES('{$date}')";
$create_video_query=mysqli_query($connection,$query);
if (!$create_video_query) {
die("failed".mysqli_error());
} else {
$success = "Video added succesfully";
}
?>
}
</script>
<?php } ?>
Test your code without the php.
you are missing a semicolon after "Click OK to Add & Cancel to Cancel it')"
Make sure you really have "if(r==true)" and not "if(r=true)"
I tested the following code (php is removed) and it works:
<html>
<body>
<script>
var txt;
var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it');
if(r==true){
alert('Clicked OK: Run insert sql');
} else {
alert('Clicked Cancel: Do nothing');
}
</script>
</body>
</html>
You can not mix server-side (PHP) and client-side (JavaScript) together to interact in real time together. You have to use AJAX or you have to submit a form (either one built in the html or built by javascript). Here is just a basic example:
<?php
# Checks to see if the form has been submitted
if(isset($_POST['add'])) {
$query="INSERT INTO video_data(date) " ;
$query .= "VALUES('{$date}')";
$create_video_query=mysqli_query($connection,$query);
if(!$create_video_query) {
die("failed".mysqli_error());
}
else {
$success = "Video added succesfully";
}
}
?>
<?php
# I don't know what this is based on (the query) so I don't know if it's required.
# I just left it
if(mysqli_num_rows($data_query) >= 1) { ?>
<script>
var txt;
var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it');
if(r !== false){
// Assumes there is a form to submit and submits it
form.submit();
}
</script>
<?php } ?>

Loading content on tab click

I recently found a cool tabbed content page, where when you click on the tabs they show content http://codepen.io/unasAquila/pen/nDjgI What I discovered was, that these tabs were preloaded once you enter the page, rather than being loaded as the tabs are clicked on. I was wondering if it is possible to make it to where the content loads as you click on the tab. For example, If I have a PHP Query statement where I want to load information such as this:
$query3 = $db->query("SELECT * FROM mybb_game WHERE id='" . $id . "'");
while($row = mysqli_fetch_array($query3))
{
echo "$row[name]
}
How would I make it to where the content is only loaded once the tab is clicked on?
It can be done using AJAX. Simply put, AJAX is a technology that allows sending requests to the back-end when an event triggers on the front-end.
You could make the following:
In your HTML:
<!-- Change myTabId to whatever id you want to send to the server side -->
<element onclick="loadTab(myTabId)">my tab</element>
In your JS:
// Will be executed on tab click
function loadTab(tabId) {
var xmlhttp = new XMLHttpRequest();
// Define a handler for what to do when a reply arrives from the server
// This function will not be executed on tab click
xmlhttp.onreadystatechange = function() {
// What to do with server response goes inside this if block
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Change the content of the element with id "myTabContent" to the server reply
document.getElementById("myTabContent").innerHTML = xmlhttp.responseText;
}
}
// Opens a connection to "myServerSideScript.php" on the server
xmlhttp.open("GET", "myServerSideScript.php?id=" + tabId, true);
xmlhttp.send();
}
Now you need to create myServerSideScript.php on the server root with a content similar to the following:
$id = $GET[id]; //The GET parameter we sent with AJAX
$query3 = $db->query("SELECT * FROM mybb_game WHERE id='" . $id . "'");
$response = "";
while ($row = mysqli_fetch_array($query3)){
$response .= $row[name];
}
// To return a reply you just need to print it
// And it will be assigned to xmlhttp.responseText on the client side
echo $response;
You can learn more about AJAX here

Want to perform php using OnClick function without clearing the current web page

This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'>&nbsp</div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?

Ajax auto update not updating

Hello I'm working on a shoutbox and I need help with auto updating them via ajax.
Here is my shoutbox with ?getShouts=true at the end:
Here is my shoutbox without that:
My goal here is to run a web request and get the contents of the shoutbox in ?getShouts and update on the page I'm in.
This PHP code is run on the top of the page:
if(!empty($_GET['getShouts']))
{
$sbinfo = "";
$rows = $db->query("SELECT * FROM shouts order by shoutid DESC limit 20");
while($row = $rows->fetch_array(MYSQL_ASSOC))
$sbinfo .= $row['username'] . ": " . $row['shout'] . "<br />";
}
That stores the markup for the text into one string.
later in php file it displays the markup by: if(!empty($_GET['getShouts'])) echo $markup;
Here is my ajax I'm currently running:
<script>
$(document).ready(function() {
getMessages();
});
function getMessages()
{
//make request
var req = new XMLHttpRequest();
req.open("GET", location.href+"?getShouts=true", true);
req.send(null);
document.getElementById("shouts-box").innerHTML = req.responseXML.getElementsById("shouts-box")[0].innerHTML;
//loop
window.setInterval(getMessages,3000);
}
</script>
any ideas?
I have found a solution for this using:
$('#div').load('index.php?getShouts=true #div');

PHP In ajax responseText take all the html cose instead of ONLY the echo passed trought PHP

Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>

Categories