I need to get data (image_url, names, etc) from mysql when the page is open.
I'm thinking to do this on oninit() event. However I'm not sure if this is the best approach.
The code I got so far is taking more time than I was expecting so maybe I'll need to add a "loading" message while this operation is going. Am I in the right way?
Thanks in advance
Okay, there are scenarios here -- and I'm not too sure about what you need. The first is pulling the data once on page load. You present your data through a view using a controller to access your data model. Everything is processed on page load and is static.
// Use simple PHP
<?php
$con = mysql_connect("localhost","peter","abc123");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($result))
{
echo $row['image'];
echo $row['names'];
// etc.
}
?>
The second is more dynamic, using AJAX to pull data from your server continuously. You can use JavaScript's setInterval to load data over a regular period:
// Load MySQL data every 15 seconds with jQuery
$(function () {
setInterval(function() {
$.ajax({
url: '/path/to/controller',
data: 'var1=hey&var2=bro',
dataType: 'html',
type: 'POST',
success: function(data) {
$('.div_of_your_choice').html(data);
})
});
},15000);
});
Related
This little project of mine involves registering actions associated with buttons pressed on a gamepad (PS3 style for the record). Because html5 supports gamepads I decided to use it as a fast and simple way for development.
The thing is, when running the ajax and the call of the php script, after pressing a button, the insert statement is duplicated. This not happens when I set async: false and use Firefox, but this goes against the purpose of ajax, and from what I've read, not an elegant thing to do.
This is what I have in my index.html (borrowed from here https://gamedevelopment.tutsplus.com/tutorials/using-the-html5-gamepad-api-to-add-controller-support-to-browser-games--cms-21345)
function reportOnGamepad() {
var gp = navigator.getGamepads()[0];
var html = "";
html += "id: "+gp.id+"<br/>";
html += "timestamp: "+gp.timestamp+"<br/>";
html += "<br/>move<br/>"
if (gp.buttons[0].pressed) { var moves=" B1"; $.ajax({
url:'my.php',
method:'POST',
data:{
moves: moves
},
}); html+= " <br/>";
};
and my my.php
$conn = new mysqli($servername, $username, $password, $dbname);
$moves = $_POST['moves'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test (moves) VALUES ('$moves')";
$conn->query($sql);
$conn->close();
Simple stuff as you can see. My knowledge of jquery/javascript is very basic so, if someone with more experience could point me what I'm doing wrong, I would really appreciate it. Thank you.
The tuts+ tutorial you linked has some code to set up a polling interval for Chrome as a workaround for unreliability in the gamepadconnected event:
//setup an interval for Chrome
var checkGP = window.setInterval(function() {
console.log('checkGP');
if(navigator.getGamepads()[0]) {
if(!hasGP) $(window).trigger("gamepadconnected");
window.clearInterval(checkGP);
}
}, 500);
This bug is fixed in the latest version of Chrome and the workaround could be causing your issue. For instance, if checkGP fires before the gamepadconnected event is received, you may register the reportOnGamepad interval twice.
For example I am a user and I want to post a comment and after submitting it and saved to my database. The other page of the admin updates and automatically the data that I inserted displays without refreshing the page of the admin. Help please..
any code can help. Thanks. I'm using php for server-side language. Any language can help javascript or ajax.
Javascript (jQuery):
$.post('path_to_your_php_script.php', function(data) {
$('the_dom_element_you_want_to_show_the_comment_in').html(data);
});
Somewhere in path_to_your_php_script.php:
// some code to save the data
echo '<div>New comment</div>';
exit;
For more information, please refer to jQuery's post and ajax methods. You can do the same thing without jQuery, but you shouldn't reinvent the wheel.
yourphpfile.php is the php file where you need to do all your database operations (in your case its insert into database).
So,basically you want to show the recently insert data in a webpage without refreshing the page, to do that, we need Ajax.
So, do your insert operation in yourphpfile.php, and if the insert operation is successful, just return the result (inserted data into DB) using echo $output;exit;
where $output = 'recently inserted data';
That's what you need to do in the php side.
Your yourphpfile.php:
<?php
//your database insert operation
echo $output;// $output should have the inserted data
exit;
?>
Now in ajax function:
You could use jquery.ajax
$.ajax({
type: "GET",
url: "yourphpfile.php",
success: function(response){
if(response != '') {
//data that I inserted displays without refreshing the page of the admin
$('yourDivContent').html(response);
} else {
// response error
}
}
});
In the reponse variable you would get what you have echoed in the yourphpfile.php.
That is $output. Then you could use the reponse varible inside ajax function and use it to insert into your HTML.
Suppose you have a form and you can use Ajax for sending the data to the backend. The ajax call would look in the following way:
var id = $(this).attr('id');
$.ajax({
type:"POST",
url:"ajax.php",
data:{id:id},
success:function(data){
// do something if insertion into database has succeeded
}
});
...and in php you write something as:
// Connecting to Database
mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die ('Can not connect to MySQL database');
// Selecting Database
mysql_select_db(DBNAME) or die ('Cant select Database');
$action = mysql_real_escape_string($_POST['action']);
if ($action == "insert")
{
foreach ($recordArray as $key=>$value) {
$query = "INSERT INTO `TABLE`
SET name = `".$_POST['name']."`
SET age = `".$_POST['age']."`
.
.
mysql_query($query) or die('Error, insert query failed');
}
guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead
I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.
I'm trying to get some values off a DB and then putting those values into javascript variables. I managed to do just that, the problem I'm having is when the values in the DB change the values of the variables don't. I figured the problem lies within my PHP, but I cant find it. Can you guys help me?
here's my code:
PHP
<?php
session_start();
if(!isset($_SESSION['u_name'])){
$_SESSION['u_name'] = '';
}
mysql_connect ("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db('raffleiz_Main')or die ("cannot select DB :(");
$signups = mysql_query("SELECT * FROM `Rafflez_info`") or die ('Error: ' . mysql_error());
$row = mysql_num_rows($signups);
//pull all of the data and store it
for($p = 0; $p < $row; $p++){
$participants[$p] = mysql_result($signups, $p, "#_participants");
};
for($a = 0; $a < $row; $a++){
$max_participants[$a] = mysql_result($signups, $a, "max_participants");
};
?>
and my javascript function:
function progress(){
var signups = "<?php echo $participants[0]; ?>";
var maxP = "<?php echo $max_participants[0]; ?>";
alert (signups);
alert (maxP);
var pSignup = signups / maxP;
alert (pSignup);
var total = 550 * pSignup;
var theImg = document.getElementById('progress');
theImg.width = total;
alert (total);
};
I put the "alert" command there so that I could see the change in the values. right now the values don't change no matter what I change them to in the DB.
PHP is a server-side language, meaning that when it served the script from the server to the client, there is no going back.
JavaScript is a client-side language, thus can receive values from a server-side language such as PHP. The values received are then client-side only, a copy if you will.
You can use the XMLHttpRequest API to request a script from a server, updating the local client-side values.
I recommend using the jQuery $.ajax function to easily achieve that.
Here's a nice tutorial from Nettuts to get your started.
You need to call your php page and ask it if values are changes. You can easily use jQuery AJAX to achieve that. Use JSON for easier data transfer. If you want to check if values are changes every 3 seconds for example you can do this:
var interval = window.setInterval(function(){
jQuery.ajax({
url: 'your php file address',
success: function(data){
progress(data)
}
});
}, 3000);
You will need to change you proccess and php code. This is just to give you the idea.