what I mainly want to do is to get the div's content and pass it in a variable. To explain what I have done until now :
I have my php file that contains the code :
<?php
$connect = mysql_connect("localhost", "...","...") or die("Could not connect to the database.");
mysql_select_db("...") or die("Could not find database <...>");
$query = mysql_query("SELECT id FROM datainput WHERE id>=ALL(SELECT id FROM datainput)") or die("Query could not be executed");
$row = mysql_fetch_assoc($query);
echo $row['id'];
?>
In my index.php file I have written the following script :
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("document").ready( function(){
//setInterval("checkForNewData()", 1000); //30 Minutes = 1800000 Milliseconds
checkForNewData();
});
function checkForNewData(){
$("#lastid").load("lastData.php");
var mydata = $("#lastid").text();
}
</script>
In my html tag I have a div with id="lastid".
With the code below :
var mydata = $("#lastid").text();
I want to keep the current text of lastid div, so I can later compare it with another.
As I have read here, this should have done mydata="6" (is the current result)?
What am I doing wrong?
Can anyone help? Pleaseee...
You need to wait for the load to have finished. This is done by using a callback function like so:
<script type="text/javascript">
$("document").ready( function(){
//setInterval("checkForNewData()", 1000); //30 Minutes = 1800000 Milliseconds
checkForNewData();
});
function checkForNewData(){
$("#lastid").load("lastData.php", function(){
var mydata = $("#lastid").text();
});
}
</script>
Please see the jQuery API docs for more information: http://api.jquery.com/load/
Essentially, the second argument of the load function can be a function. If it is, then whatever code is in that function will be executed when the load has completed.
Related
I am new to javascript and I've searched this question everywhere but no suitable answer.
I have a "code.php" page as
$query = "SELECT * FROM users WHERE id=1";
$result= mysqli_query($con,$query);
$row=mysqli_fetch_array($result);
echo $row[1];
On the other side in "index.php" i have
<h1>"the value for number is: " <span id="myText"></span></h1>
function myFunction() {
document.getElementById("myText").innerHTML = $row[1];
}
I want to load the value of $row[1] from code.php to index.php.
I know that i have to use ajax but how?
In index php use ajax to get data from code php.
this is example :
<script>
$.ajax({
url: 'code.php',
type:'get',
success:function(data){
$("#myText").html(data);
}
});
</script>
<script>
$(document).ready(function(){
$.ajax({
type:'get',
url:'code.php',
success:function(response){
// ajax will assign the result of code =,php into response
document.getElementById("myText").innerHTML = response; //response;
}
});
});
</script>
Place this at header of your index.php
You can find more tutorials on line to get more understanding of ajax
dont forget to download jquery and embed it your code
https://jquery.com/download/
Or u can copy this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
I tried to show real time visitors visit(ed) the site. Below is my PHP file named getTotalVisitors. In the php file the uniquevisitors are showing well.
include 'common.php'; //get database connection
$query = "SELECT SUM(uniquevisitors) as uniquevisitors FROM " . $DBPrefix . "currentaccesses";
$params = array();
$db->query($query, $params);
while ($new = $db->fetch())
{
$uniquevisitors = $new['uniquevisitors'];
}
echo "visitors until now: " . $uniquevisitors . "<br>";
When i try to get it real time with the update and setInterval function with the below script, I cannot get it working. Anybody gives me the right direction/solution ?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function updategetTotalVisitors()
{
$('#datashow').load('getTotalVisitors.php');
}
updategetTotalVisitors(); //set the datacount as soon as the page is loaded
setInterval( "updategetTotalVisitors()", 10000 ); //update the datashow every 10 seconds
});
</script>
<p>Visitors until now:</p>
<div id = "datashow"></div>
First of all, the function parameter of setInterval must be unquoted and without parenthesis:
setInterval( updategetTotalVisitors, 10000 );
Then, you have to declare updategetTotalVisitors outside $(document).ready scope and to assign the returned value of setInterval to a variable:
<script type="text/javascript">
var repeatFunction;
function updategetTotalVisitors()
{
$('#datashow').load( 'getTotalVisitors.php' );
}
$(document).ready(function()
{
updategetTotalVisitors();
repeatFunction = setInterval( updategetTotalVisitors, 10000 );
});
</script>
The script above works, for me. Obviously I have tested it with fake getTotalVisitors.php, but you say that your php works, so...
I'm working on a notification message i want to load new message from a page call check_new-reply.php in every 10 second using Ajax and Jquery but my code is not showing anything i don't know what the error is please can someone help me out?
<script>
$(document).ready(function(){
$(function(){
var timer = 10;
var test = "";
function inTime(){
setTimeOut(inTime, 1000);
$("#timer-u").html("Time refreshing"+timer);
if(timer == 8){
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
})
timer = 11;
clearTimeout(inTime);
}
timer--;
}
inTime();
});
});
</script>
Here is PHP
<?php include($root . '_inc/Initialization.php');?>
<?php require_once("_inc/dbcontroller.php"); $db_handle = new DBController();?>
<?php
$users = $_SESSION['username'];
$newquery = "SELECT * FROM blog_post
INNER JOIN replys
ON blog_post.UserName = '$users'
WHERE replys.read = 0
ORDER BY rtime";
$newhisory = mysql_query($newquery);
while($newrow = mysql_fetch_array($newhisory)){
echo '<div class="fnot">'.htmlentities($newrow['blog_title']).'';
echo '<span class="ttcredit"><font color="darkgreen">94</font> </span> <a class="reqttag reqttag2" href="#">No</a> ';
echo '</div>';
echo '<input type="hidden" id="unr" name="unr" value="'.$newrow['BID'].'"/>';
}
?>
If you just want to call it every 10 seconds, use 10000 milliseconds in the setTimeOut . Also, it is best to call again the function only when the previous Ajax call is done:
$(document).ready(function(){
$(function(){
var test = "";
function inTime(){
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
setTimeout(inTime, 10000);
});
}
inTime();
});
});
To call any function with some intervals you will have to use
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 10000);
});
function myAjaxCall() {
alert("Hi");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>
window.setInterval will call your function on every 3 seconds with above code, and will generate an alert message,
what you have to do is set your ajax code in a function and use above method, change 3000 to 10000 and your ajax call will defiantly work with every 10 seconds,
This is the code which will call our javascript function on every 10 seconds,
just copy it and check it, you will get an idea, also i have included the jquery as we have discussed.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 3000);
});
function myAjaxCall() {
alert("Call your Ajax here");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>
I want to display the contents of the php file and I tried to include the php file in ajax but it doesn't work.
solution 1 doesn't work
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'><?php include 'word.php' ?></center>";
solution 2 still doesn't work
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'<script type='text/javascript' src='wotd.php'></script>";
Here's the code for ajax if there's no input it will display the word of the day
function showMeaning(word)
{
if(word.length == 0)
{
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'><?php include 'word.php' ?></center>";
//the word of the day must be displayed here but it doesn't work
return false;
}
else{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url = "get_word.php"
url = url + "?word=" + word
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
}
here's my php code for generating the word of the day
<?php
$con=mysql_connect("localhost","root","");
mysql_set_charset("UTF8", $con);
if(!$con)
{
die("Could not connect." .mysql_error());
}
mysql_select_db("dictionary_ajax", $con);
$query = "SELECT eng_word" .
" FROM english".
" ORDER BY RAND(DAY(NOW())) LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows==0)
{
echo "No Results Found. Please try again";
}
while($row=mysql_fetch_array($result))
{
echo "<center><div class='wotd'>Word of the day:</div><div class='word'>".$row['eng_word']."</div></center>";
}
mysql_close($con);
?>
A better approach would be to call the php file via an AJAX request and then append the response to the relevant DOM element.
Overview of AJAX using vanilla Javascript:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
Docs on JQuery Post and Get short cuts.
https://api.jquery.com/jquery.get/
http://api.jquery.com/jquery.post/
There are examples of what you are trying to do in the JQuery .get docs
Using jQuery, you could you use one of their ajax calls to load your html from include.php.
<div id="content"></div>
<script>
$(document).ready(function() {
$("#content").load("/yourpath/include.php");
});
</script>
or, without using jQuery, you may try this,
<div id ="content"></div>
<script>
function loadphpfile() {
var x = document.getElementById("content");
x.innerHTML = '<?php include_once "include.php";?>';
}
loadphpfile();
</script>
Try isolating the html+js files and API call yout .php file
app |-- www/index.html
|-- www/js/main.js
|-- www/api/word.php
Create html for view and include your javascript file and the jQuery library.
Get your data from the php file and return a json file
Call the *.php api file url using $.ajax Read more
Update DOM from the ajax data object
Hope that helps
You should make an AJAX call to get HTML from your server, then put the response to a DOM element with JavaScript.
So, in your case this may look like:
<center>
<img src="images/img_layout/exploro_logo.png">
<div id="wordOfTheDay"></div>
</center>
<script type="text/javascript">
/**
* Gets a word of the day
*/
function getWordOfTheDay() {
//Makes AJAX call
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//Adds the response to the DOM element with ID wordOfTheDay
document.getElementById("wordOfTheDay").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "word.php", true);
xhttp.send();
}
//Invoke the function to get the word of the day
getWordOfTheDay();
</script>
With a popular framework like jQuery, this may look like this:
<center>
<img src="images/img_layout/exploro_logo.png">
<div id="wordOfTheDay"></div>
</center>
<script type="text/javascript">
/**
* Gets a word of the day
*/
function getWordOfTheDay() {
//Makes AJAX call
$.get("word.php", function (response) {
$('#wordOfTheDay').html(response);
});
}
//Invoke the function to get the word of the day
getWordOfTheDay();
</script>
More examples of using AJAX here - http://www.w3schools.com/ajax/ajax_examples.asp
More info about jQuery get method - https://api.jquery.com/jquery.get/
Also there are very good explanations of AJAX on stackoverflow here - How does AJAX work?
I would like to implement comet with records fetch from PHP
My PHP will do the following.. at a page call getlog.php
$sql = "select log_description,log_time from log ORDER by log_time DESC";
$result=mysql_query($sql);
if($result == false)
{ die("unable to fetch records."); }
while ($row = mysql_fetch_assoc($result)) {
$result_output[] = $row;
}
$counter = 1;
foreach($result_output as $row)
{
echo $counter . ". " $row[log_description];
$counter++;
}
If there is new log, I would want to echo it out in viewlog.php
So it would appear like this in viewlog.php
1. Customer 1 logged in at 12:05.
maybe 5 minutes later
1. Customer 2 logged in at 12:10
2. Customer 1 logged in at 12:05
It maintain a maximum of like lets say 15 records.
The data is fetch from PHP, I read the way to do it is something call "comet" but I just want a simple database fetch which auto refresh e.g every 10 seconds to see if there is new record added to the database and append it to the div.
Is there a easy way to achieve this using AJAX and PHP and not using comet.
Thanks for all the help, greatly appreciate !
Did the following code changes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
show_log(){
var lnk = "fetchlog.php";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
window.setInterval(function(){
show_log();
}, 10000);
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>
Whats wrong with my code as it doesn't fetch from fetchlog.php
fetchlog.php echo something like this
1. Acct_1 logged to the system.
2. Acct_3 logged in to the system.
3. Acct_2 logged in to the system.
4. Assign permissions on Acct_1.
5. Delete record on table building with id 80
jsFiddle
Yes you can use ajax for this and simply update a div in your html.
You need to have jquery linked in order to use the below code.
show_log(){
var lnk = "link to the viewlog.php file";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
Run the show_log() function every x number of mins.
Have your viewlog.php show the last x number of records in the descending order of time.
You can update your sql to look like
$sql = "select log_description,log_time from log ORDER by log_time DESC LIMIT 5 ";
You can use the below inside your javascript to run the function every x number of seconds. In this every 10 seconds.
window.setInterval(function(){
show_log();
}, 10000);
the 10,000 is in miliseconds
----- Try the below
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
http = getHTTPObject();
function getHTTPObject(){
var xmlhttp;
if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = false;
}
}
return xmlhttp;
}
function show_log(){
var url = "viewlog.php";
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse(){
if(http.readyState == 4){
document.getElementById('log_div').innerHTML = http.responseText;
}
}
setInterval ( "show_log()", 5000 );
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>