I try to use server side event with updating or adding data in database. In this case, why the onmessage event in index.html doesn't work after I add data to database by dataAdd.php?
index.html :
<body>
<div id="result"></div>
</body>
<script>
var result = document.getElementById("result")l
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("sse.php");
source.onmessage = function(event) {
result.innerHTML += event.data + "<br>";
};
} else {
result.innerHTML = "Sorry, your browser does not support sse";
}
</script>
sse.php :
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
mysql_connect("localhost","username","password");
mysql_select_db("database");
mysql_query("set names utf8");
$result = mysql_query("select * from table order by id desc limit 1;");
$row = mysql_fetch_array($result);
echo "data: $row[message]";
flush();
?>
dataAdd.php :
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
mysql_query("set names utf8");
if(isset($_GET['text'])) {
mysql_query("insert into chat (message) values ('$_GET[text]')");
}
?>
Related
After sending the country name "US" in JavaScript to PHP code, I will try to receive the results of PHP's work back to JavaScript and use them.
To do this I used the below code.
$ctryNm_php_temp = "document.write(ctryNm);";
As a result, it seemed that the value 'US' of the ctryNm variable was well transfered to php code.
The cryNm value and $SQL value printed on the screen contain 'US'.
However, the results of the SQL query were returned to an empty value, so we checked.
The IF statement shows that ctryNm and 'US' are different values.
(The output on the screen shows the same value and data type as string.)
I printed $result_obj and found no value.
echo and console.log command result for checking:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var ctryNm = "US";
</script>
<?php
$ctryNm_php_temp = "<script language='javascript'>document.write(ctryNm);</script>";
$ctryNm_php = $ctryNm_php_temp;
echo $ctryNm_php . "<br><br>";
echo "--------------" . "<br>";
echo gettype($ctryNm_php) . "<br>";
if ($ctryNm_php == 'US') {
echo "Same" . "<br>";
} elseif ($ctryNm_php != 'US') {
echo "Different" . "<br>";
}
$conn = new mysqli("...", "...", "...");
mysqli_select_db($conn, '...');
mysqli_query($conn, "set names utf8");
$sql = "SELECT * FROM acst_covid_who WHERE country_code = '$ctryNm_php'";
echo $sql . "<br>";
$result_obj = mysqli_query($conn, $sql);
echo "result_obj :" . $result_obj . "<br>";
$date_adjust = 0;
$latestDate_trend = '';
while ($row = mysqli_fetch_array($result_obj)) {
if ((int)$row['confirmed_new'] !== 0) {
$latestDate_trend = $row['date'];
$date_adjust = 1;
} elseif ((int)$row['confirmed_new'] === 0) {
$latestDate_yester_trend = strtotime($row['date'] . "-1 days");
$latestDate_trend = date("Y-m-d", $latestDate_yester_trend);
$date_adjust = 0;
};
};
$result_obj = mysqli_query($conn, $sql);
$total_rows_trend = mysqli_num_rows($result_obj) - $date_adjust;
$arr_trend = array();
while ($row = mysqli_fetch_array($result_obj)) {
array_push($arr_trend, $row);
}
echo $total_rows_trend;
echo json_encode($latestDate_trend);
?>
<script>
var latestDate_js_trend = <?php echo json_encode($latestDate_trend) ?>;
var arr_js_trend = <?php echo json_encode($arr_trend) ?>;
var arr_length_trend = <?php echo $total_rows_trend ?>;
console.log(latestDate_js_trend);
console.log(arr_js_trend);
console.log(arr_length_trend);
</script>
</body>
</html>
this sadly does not work like this.
PHP code is executed first on the server, so before the website is even shown in the browser. The order you write it does not matter.
The process is like this:
You type the address in the browser and it asks the server for the page.
The server literally runs an app called php, that reads what you wrote in the code, reads only what is between <?php and ?>, nothing else (technically the first one can be <?=)
When it is done, the server sends the page to browser
The browser reads html and fires JavaScript, long after PHP was already changed.
This is simplified but show why your code will not work.
I have the PHP code where I get echo as my postgres database table fields I want to display these fields in my html and JavaScript based web application.for now I can load them in my webpage but I have to reload the webpage to get newly updated values. I want to get them automatically in a textbox without reloading application.i read that an ajax request would be helpful
given is the php code i am using with html to show case records but i have to reload page every time to get it updated
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
while($row = pg_fetch_row($ret)) {
// echo "e = ". $row[1] . "\n";
echo "<input type='text' value='$row[14] '/>";
echo "<input type='text' value='$row[13] '/>";
}
echo "Operation done successfully\n";
pg_close($db);
?>
The problem is that after your browser renders the output of your php script, it is not connected to your php anymore. This is how HTTP works.
To be able to show the output without refreshing the whole page, you need to use javascript to make another HTTP request to your PHP script.
Something like this:
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
?>
<div id='content'>
<?php while($row = pg_fetch_row($ret)) { ?>
<input type='text' value='<?= $row[14] ?>'/>
<input type='text' value='<?= $row[13] ?>'/>
<?php } ?>
Operation done successfully
<script>
(function() {
const secondsToRefresh = 5;
const Http = new XMLHttpRequest();
const url='#YOUR_PHP_SCRIPT_URL#';
setTimeout(function() {
Http.open("GET", url);
Http.send();
}, secondsToRefresh * 1000);
Http.onreadystatechange=(e)=>{
document.getElementById('data').innerHTML = Http.responseText;
}
})()
</script>
</div>";
I'm new at php. I get the last id from database. For each id I want the state and the link. I'll check if state == 1, then get the content of the link (there's JavaScript variable that I need that is in the content of link). I'll send that variable with location.href.
Then I get that variable with $_GET in the second page. I want to store that var into database, then come back to first page and get the second link from the database and again do the same works.
How can I send the $j into second page for saving the x_cor and y_cor, and how to increase the $j when it comes to first page again?
<html>
<head>
<title>firstpage</title>
</head>
<body>
<?php
include_once ('simple_html_dom.php');
include_once ('split_unicode_function.php');
// getting the last id from db
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$sql = "SELECT id FROM netbarg ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql, $connection);
$rows = mysql_fetch_array($result);
$last_id = $rows['id'];
// getting id and link for each column
for ($j = 1; $j <= 2; $j++)
{
$select_db = mysql_select_db("kk", $connection);
$id = "SELECT state FROM `table` WHERE id='$j' ";
$result = mysql_query($id, $connection);
$row = mysql_fetch_array($result);
echo $state = $row[0] . '<br />';
// getting link
$link = "SELECT link FROM `table` WHERE id='$j' ";
$result = mysql_query($link, $connection);
$rows = mysql_fetch_array($result);
$link = $rows[0];
// (state is just 1 or 2)check if the state is 2 or not...
if ($state == 1)
{
$f = file_get_contents($link);
echo "<div>$f</div>";
}
}
?>
<script>
$("body").hide();
location.href ='secondpage.php?val='+point0+;
</script>
</body>
</html>
second page
<html>
<head>
<title>second page</title>
</head>
<body>
<?php
if (isset($_GET['val']))
{
$hat = $_GET['val'];
echo $hat;
$coords = trim($hat, '()');
// echo $coords.'<br />';
$a = array();
$a = explode(",", $coords);
var_dump($a);
echo $long = $a[0];
echo '<br />';
if ($long == "undefined") $lat = "undefined";
else echo $lat = $a[1];
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$update = "UPDATE `table` SET `x_cor`='$long',`y_cor`='$lat' , `state`='2' WHERE `id`='$j' ";
$insert_todb = mysql_query($update, $connection);
if ($insert_todb) echo "coordinates has been updated", '<br />';
}
}
?>
<script>
location.href ='firstpage.php';
</script>
</body>
</html>
if get the last insert id use mysqli_insert_id($con);
it return last insert id from database using this geted id you can
I have a column in phpMyAdmin id call that gets integer values 1 or 0. When 1, the user enter the site an alert is displayed ('Welcome!'); how to do so that when the user clicks OK to be updated msg to 0?
index.html
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
var msg = event.data;
if (msg>0){
alert('Welcome');
};
};
};
</script>
</body>
</html>
demo_sse.php
<?php
$dominio = "127.0.0.1";
$host = "localhost";
$user = "root";
$pass = "";
$banco = "teste";
$codificacao = 'utf8';
$conexao = mysqli_connect($host, $user, $pass, $banco) or die(mysqli_connect_error());
$sql= "select * from `msg`";
$resultado = mysqli_query($conexao,$sql);
$tabela = mysqli_fetch_array($resultado);
$id=$tabela['id'];
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data:{$id}\n\n";
flush();
?>
You'll have to create a php script that switches that record to 0 then use the event of clicking the ok button to fire an Ajax request to that script. The Ajax will run your php and give the effect you want. If you need more instruction I can do a detailed example when I get to a computer.
function create(x) {
var field=document.createElement('fieldset');
var t=document.createElement('table');
t.setAttribute("id","myTable");
document.body.appendChild(t);
field.appendChild(t);
document.body.appendChild(field);
var row=document.createElement('th');
newHeader = document.createElement("th");
newHeader.innerText = x;
row.appendChild(newHeader);
var row1=document.createElement('tr');
var col1=document.createElement('td');
var col2=document.createElement('td');
var row2=document.createElement('tr');
var col3=document.createElement('td');
var col4=document.createElement('td');
var row3=document.createElement('tr');
var col5=document.createElement('td');
var col6=document.createElement('td');
col1.innerHTML="Name";
col2.innerHTML="<input type='text' name='stateactivityname' size='40' required>";
row1.appendChild(col1);
row1.appendChild(col2);
col3.innerHTML="Registration Applicable";
col4.innerHTML="<select name='regapp' required><option></option><option>Yes</option><option>No</option></select>";
row2.appendChild(col3);
row2.appendChild(col4);
col5.innerHTML="Registers Applicable";
col6.innerHTML="<select name='registers' required><option></option><option>Yes</option><option>No</option></select>";
row3.appendChild(col5);
row3.appendChild(col6);
t.appendChild(row);
t.appendChild(row1);
t.appendChild(row2);
t.appendChild(row3);
addrow('myTable');
}
PHP code for storing data to database is:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$conn=new mysqli("localhost","root","","newcomplyindia");
if($conn->connect_errno){
echo("connection error");
}
$actname=$_POST["actname"];
$industry=$_POST['industrytype'];
$centralorstate=$_POST["cors"];
$sql="insert into acts (actname,centralorstate) value ('".$actname."','".$centralorstate."')";
$regapp=$_POST["regapp"];
if($regapp=='Yes'){
$regapp=true;
}
else{
$regapp=false;
}
$registers=$_POST["registers"];
if($registers=='Yes'){
$registers=true;
}
else{
$registers=false;
}
$sub=$_POST["sub"];
if($sub=='Yes'){
$sub=true;
}
else{
$sub=false;
}
if($conn->query($sql)==true){
echo 'act name added ';
}
$lastid=$conn->insert_id;
$sql1="insert into actsstate (actid,registrationrequired,registersapplicable,sublocation)"
. "values('$lastid','$regapp','$registers','$sub')";
if($conn->query($sql1)==true){
echo '<br>name and central/state added';
}
$stateactivity=$_POST["stateactivityname"];
$activityname=$_POST["activityname"];
$activitymonth=$_POST["month"];
$activitydate=$_POST["date"];
$sql2="insert into activity (name,actid,activityname,activitymonth,activitydate)"
. "values('$stateactivity','$lastid','$activityname','$activitymonth','$activitydate')";
if($conn->query($sql2)){
echo 'activity added';
}
else{
echo 'no record';
}
$conn->close();
?>
i have a javascript like this. The table is created dynamically. And i want to store the data inside this table to database. am using mysqli for database connection
Am new to javascript. Can anyone help me to do this
Here's a way using Vanilla JS (pure js)
var xhttp = new XMLHttpRequest();
var url = "save.php";
xhttp.open("POST", url, true);
// uncomment this if you're sending JSON
// xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { // Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
// the 4 & 200 are the responses that you will get when the call is successful
alert(xhttp.responseText);
}
}
xhttp.send('the data you want to send');
And here's a way to save to the database (mysql in my case) with Flat PHP (pure php)
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
// connect to the DB
$conn = new mysqli($servername, $username, $password, $dbname);
// check if you're connected
if ($conn->connect_error) {
echo "Connection failed: " . $conn->connect_error;
}
else {
// echo "connecting to DB succeeded <br> ";
}
// uncomment the following if you're recieving json
// header("Content-Type: application/json");
// $array = json_decode(file_get_contents("php://input"), true);
$sql = "INSERT INTO table_name (columns,names) VALUES (columns,values)";
if ($conn->query($sql) === TRUE) {
echo "Data was saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
to learn more about the sql commands I suggest the w3schools tutorials
Of course you can by using AJAX:
$.post("php_script.php",{javascript variables}, function(result) {
alert(result);
});