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.
Related
I am trying to work implement ajax due to maximum site load which PHP causes. But I am not aware of where I am making a mistake here. it is an anchor tag, when it is clicked the status of the particular row should be changed to a string which is hard coded.
PHP WAY
USERDETAIL.PHP
Next
Then it triggers This (IGNORE SQL INJECTION)
if(isset($_GET['changeStatus'])){
$id = $_GET['changeStatus'];
$user=$_SESSION['user'];
$sql = "select * from productOrder where id = ".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
$sql = "update productOrder set prodStatus = 'Ready', By='".$user."' where id=".$id;
if(mysqli_query($conn, $sql)){
header("Location:USERDETAIL.php");
}
}
}
According to this way, it works neat, but the userdetail.php would refresh anyways which is a lot time consuming. Then tried AJAX way is below.
Next
and that hits to
$(document).ready(function() {
$(".changeStatus").click(function(event){
event.preventDefault();
var status = "Ready";
var id = $(this).attr('data-id');
$.ajax({
url : 'action.php',
method : 'POST',
data : {status : status , id : id},
dataType: 'html',
success : function(response){
console.log(response);
}
});
});
});
and in the action.php it is (IGNORE SQL INJECTION AGAIN)
if(isset($POST['prodStatus'])){
$status = $_POST['prodStatus'];
$id = $_POST['id'];
$sql = "update productOrder set prodStatus= '$status' where id=".$id;
$result = mysqli_query($conn, $sql);
if($result){
return 'Updated';
}
}
The output is nothing happens. in the console it is just adding int values. I know I am making a mistake, or understood AJAX in a wrong way. it is just one button click and the string in SQL should be updated without an input text / modal. Please suggest what should be improved?
Also instead of having a seperate action php for these actions, can I do all these in userdetail.php itself with Ajax? is it possible?
Thanks in advance.
As B_CooperA pointed out, $POST should be $_POST.
Also, in $.ajax script data object your property name is status and in action.php you are checking it by prodStatus.
Furthermore, you should check the errors PHP is throwing in your script by enabling error reporting: error_reporting(E_ALL);
It's better to separate ajax calls from your view files. You can create a Class to handle all of your ajax calls (You should also consider authenticating your calls as per your use cases).
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');
}
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);
});
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.
EDIT - got the transfer to happen
.. now I need to figure out how to get the successful transfers to delete each row after it is stored on the host. The function that grabs the data from the browsers SQL database is :
function grabLocal(){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM entries', [], function(tx, results){
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
var qID = (results.rows.item(i).ID);
var qEmail = (results.rows.item(i).email);
var qPhone = (results.rows.item(i).phone);
var qMonth = (results.rows.item(i).birth_month);
var qDay = (results.rows.item(i).birth_day);
var qYear = (results.rows.item(i).birth_year);
var qMonth = (results.rows.item(i).birth_month);
var qGender = (results.rows.item(i).gender);
var qContest = (results.rows.item(i).contest);
var qStore = (results.rows.item(i).storeNo);
var qDate = (results.rows.item(i).added_on);
var localData = new Array((qEmail),(qPhone),(qMonth),(qDay),(qYear),(qGender),(qContest),(qStore),(qDate));
$.ajax({
type: "POST",
url: "sendIt.php",
data: "email=" + qEmail + "&phone=" + qPhone + "&month=" + qMonth + "&day=" + qDay + "&year=" + qYear + "&gender=" + qGender + "&contest=" + qContest + "&store=" + qStore + "&date=" + qDate,
success: function(){
// delete each row as passed to host
db.transaction(function(tx)
{
tx.executeSql('DELETE FROM entries WHERE ID = ?', [qID]);
});
// alert ("Success");
}
});
}
});
});
}
the php is simple like :
<?php
$link = mysql_connect('host', 'user', 'password');
if (!$link) {
die('Could not connect: ' .mysql_error());
}
echo 'Connected successfully';
$email = htmlspecialchars(trim($_POST['email']));
$phone = htmlspecialchars(trim($_POST['phone']));
$month = htmlspecialchars(trim($_POST['month']));
$day = htmlspecialchars(trim($_POST['day']));
$year = htmlspecialchars(trim($_POST['year']));
$gender = htmlspecialchars(trim($_POST['gender']));
$contest = htmlspecialchars(trim($_POST['contest']));
$store = htmlspecialchars(trim($_POST['store']));
$datestamp = htmlspecialchars(trim($_POST['date']));
mysql_select_db("sandbox_info") or die (mysql_error());
mysql_query("INSERT INTO `infoData` (email, phone, birth_month, birth_day, birth_year, gender, storeNo, contest, added_on) VALUES ('$email','$phone','$month','$day','$year','$gender','$store','$contest','$datestamp')");
echo 'Data uploaded';
mysql_close($link);
?>
Can someone please help explain what is wrong with the delete transaction? It does delete one row each time I run the process but I would like it to delete all of them. I guess I could drop the whole table but I would rather it runs a check after each transfer to the remote host and then deletes the local data. I would also appreciate any tips on how this code could just be improved in general. Thanks in advance for any advice!
REVELATION
OK i echoed back the qID in the success and found out since it is deleting out each row it is then giving a new id to the next available row and keeps echoing out the same id over and over. So... I know the problem but still need some help to find the fix.
You seem to have described it well enough: if you already have HTTP POST support in your app (using java.net.URL or HttpClient) and a PHP script that works on the server, you'll need to:
Detect when someone is online (look at their IP address or try and connect to your server).
Generate a list of all unsaved transactions: you've got the basic code for that above, maybe you need some flag.
For each row, generate a POST to the server: if the POST succeeds (returns a 200 success code) then delete the row from the local database (or mark it as synchronized in some other way).
That should do it?
I'm not 100% clear on what you are trying to do but...
You could have one side generate a list of INSERT statements from the data that would be executed on the other side.