Loading dynamic PHP echo in webpage without reloading the page - javascript

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>";

Related

Update Database with javascript variable/ transfare javascript variable to php

I want to Update my database with a variable from javascript.
This is my javascript code i want the testusersGeld variable to transfare over to php.
var testusersGeld = 111;
var sendUsersGeld = new XMLHttpRequest();
sendUsersGeld.open("POST", "usersGeldSenden.inc.php");
sendUsersGeld.setRequestHeader("Content-Type", "application/json");
sendUsersGeld.send(testusersGeld);
and this is my php code:
<?php
session_start();
$requestPayload = file_get_contents("php://input");
$object = json_decode($requestPayload);
var_dump($object);
if(isset($_POST['update']))
{
require_once 'includes\dbh.inc.php';
$query = "UPDATE users SET usersGeld='".$object."' WHERE usersName LIKE '{$_SESSION["usersName"]}'";
$result = mysqli_query($conn, $query );
if($result)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
mysqli_close($conn);
}
When i var_dump than i can see the 111 but when i try to echo it out it wont work. The part of Update works when i use another variable.

i can't put the input data into the database

this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe

Receiving multiple values back from Ajax using JSON, without JQuery, not working

I'm just trying Ajax for the first time, with PHP, and I'd like to avoid using JQuery for now.
I got it to send back 1 list of states wrapped in a drop down element. woo hoo!
Now when I added JSON to return 2 values to be parsed back out (wrapped in an array - one a string, and one am array), it's not working. I suspect that the data is getting passed around property, but a headers-warning-message is being appended at the front of the return req so the entire string can't properly be parsed. Seems to be just a header issue of some sort. I'm not familiar with header stuff so I'm not sure where to go next. I have now pasted that content below.
Main Page:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error)
{
die("Connection failed");
}
$sql = 'SELECT country_name, country_id
FROM countrylist
ORDER BY 1';
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
//Create entry form on page
echo
"<form action = 'searchresults.php' method='post'>
<h1>FIND A PET SITTER</h1>
<br/>
Enter either a ZipCode
<table>
<tr>
<td style='text-align:right'>
Zip Code:
</td>
<td>
<input name='search_zip'></input>
</td>
</tr>
<br/><br/>
Or Country, City, and State
<tr>
<td style='text-align:right'>";
echo "Country: <td>
<select onChange='getState(this.value)' name='search_country' value=''>";
while ($row = $result->fetch_assoc())
{
if ($row[country_name] == 'United States of America')
{
echo "<option value ='".$row['country_id']."' selected>".$row['country_name']." </option>
";
}
else
{
echo "<option value='".$row['country_id']."'> ".$row['country_name']."</option>
";
}
}
echo
"
</select>
</td>
</tr>
<tr>
<td style='text-align:right'>
City:
</td>
<td>
<input name='search_city'>
</input>
</td>
</tr>
<tr>
<td style='text-align:right'>
<div id='statelab'></div>lab
</td><td>
<div id='statediv'></div>div
</td>
</tr>
</table>
<input type='submit'>
</input>
</form>";
?>
<script>
function getState(countryId) {
var strURL="getStates.php?countryIn="+countryId;
var req = new XMLHttpRequest();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) { //if success
alert(req.responseText);
var obj = JSON.parse(req.responseText);
document.getElementById('statediv').innerHTML=obj.stateselectbox;
document.getElementById('statelab').innerHTML=obj.statelabel;
}
else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
getState(230);/*united states*/
</script>
Ajax calls this page:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countryId = intval($_GET["countryIn"]);
if ($countryId < 1 || $countryId > 1000) exit();
$sql = 'SELECT divisions_are_called
FROM countrieslist
WHERE country_id = 0'.$countryId ;
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$divisionsAreCalled = $row[divisions_are_called];
//echo $divisionsAreCalled.': </td><td>';
$sql = 'SELECT state_name
FROM stateslist
WHERE state_name <> ""
AND country_id = 0'.$countryId . '
ORDER BY 1' ;
$result = mysqli_query($con, $sql);
$stateSelectBox = '<select name="statename">';
while ($row = mysqli_fetch_assoc($result))
{
$stateSelectBox=$stateSelectBox. '<option value="'.$row["state_name"].'">'.$row["state_name"].'</option>';
}
$stateSelectBox=$stateSelectBox. '</select>';
$data=array('divisionsarecalled'=>$divisionsAreCalled,
'stateselectbox'=>$stateSelectBox);
//header('Content-Type: application/javascript');
header('Content-Type: application/json');
echo JSON_encode($data);
?>
Here is the response:
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/professional/www/dan/myFiles/getStates.php:2) in <b>/home/professional/www/dan/myFiles/getStates.php</b> on line <b>43</b><br />
{"statelabel":"State","stateselectbox":"<select name=\"devices\"><option value=\"Alabama\">Alabama<\/option><option value=\"Alaska\">Alaska<\/option><option value=\"American Samoa\">American Samoa<\/option><option value=\"Arizona\">Arizona<\/option><option value=\"Arkansas\">Arkansas<\/option><option value=\"Armed Forces Americas\">Armed Forces Americas<\/option><option value=\"Armed Forces Europe\">Armed Forces Europe<\/option><option value=\"Armed Forces Pacific\">Armed Forces Pacific<\/option><option value=\"California\">California<\/option><option value=\"Colorado\">Colorado<\/option><option value=\"Connecticut\">Connecticut<\/option><option value=\"Delaware\">Delaware<\/option><option value=\"Florida\">Florida<\/option><option value=\"Georgia\">Georgia<\/option><option value=\"Guam\">Guam<\/option><option value=\"Hawaii\">Hawaii<\/option><option value=\"Idaho\">Idaho<\/option><option value=\"Illinois\">Illinois<\/option><option value=\"Indiana\">Indiana<\/option><option value=\"Iowa\">Iowa<\/option><option value=\"Kansas\">Kansas<\/option><option value=\"Kentucky\">Kentucky<\/option><option value=\"Louisiana\">Louisiana<\/option><option value=\"Maine\">Maine<\/option><option value=\"Maryland\">Maryland<\/option><option value=\"Massachusetts\">Massachusetts<\/option><option value=\"Michigan\">Michigan<\/option><option value=\"Minnesota\">Minnesota<\/option><option value=\"Mississippi\">Mississippi<\/option><option value=\"Missouri\">Missouri<\/option><option value=\"Montana\">Montana<\/option><option value=\"Nebraska\">Nebraska<\/option><option value=\"Nevada\">Nevada<\/option><option value=\"New Hampshire\">New Hampshire<\/option><option value=\"New Jersey\">New Jersey<\/option><option value=\"New Mexico\">New Mexico<\/option><option value=\"New York\">New York<\/option><option value=\"North Carolina\">North Carolina<\/option><option value=\"North Dakota\">North Dakota<\/option><option value=\"Northern Mariana Islands\">Northern Mariana Islands<\/option><option value=\"Ohio\">Ohio<\/option><option value=\"Oklahoma\">Oklahoma<\/option><option value=\"Oregon\">Oregon<\/option><option value=\"Pennsylvania\">Pennsylvania<\/option><option value=\"Puerto Rico\">Puerto Rico<\/option><option value=\"Rhode Island\">Rhode Island<\/option><option value=\"South Carolina\">South Carolina<\/option><option value=\"South Dakota\">South Dakota<\/option><option value=\"Tennessee\">Tennessee<\/option><option value=\"Texas\">Texas<\/option><option value=\"U.S. Virgin Islands\">U.S. Virgin Islands<\/option><option value=\"Utah\">Utah<\/option><option value=\"Vermont\">Vermont<\/option><option value=\"Virginia\">Virginia<\/option><option value=\"Washington\">Washington<\/option><option value=\"Washington DC\">Washington DC<\/option><option value=\"West Virginia\">West Virginia<\/option><option value=\"Wisconsin\">Wisconsin<\/option><option value=\"Wyoming\">Wyoming<\/option><\/select>"}
EDIT: I added changed these 3 lines in the page ajax calls and it works now:
<?php
ob_start(); //<--ADDED THIS
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xx ...
...$data=array('statelabel'=>$divisionsAreCalled,
'stateselectbox'=>$stateSelectBox);
header('Content-Type: application/javascript');
//echo json_encode($data); //<--CHANGED THIS TO THE 2 LINES BELOW
ob_end_clean(); // this clears any potential unwanted output
exit(json_encode($data));
?>

Server Side Event doesn't work when database update

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]')");
}
?>

How to get data from php in JS on a native android app?

I'm working on a cross-platform application and I got some troubles with my data.
Actually I have a full website with a lot of php and I'm working with the Intel XDK to make a native application of this website.
But here is the thing, I know I can execute php on my native app, so i'm trying to execute few scripts directly on my server and to take back the result with an ajax request.
Here is the code : (Javascript)
var games = location.search;
var res = games.split("=");
$.ajax({ //create an ajax request to a page that prints the address.
url: "http://tonight-app.fr/php/mobile_app/getGamesLists.php", //url for the address page
data: {"name": res[1]},
success: function(result){
var games = result; //create a variable and give it the value of the response data
var gamesSplit = games.split(";");
for(i=0;i<gamesSplit.length;i++){
var gamesSplit2 = gamesSplit[i].split(",");
test(gamesSplit2[0]);
}
}
});
function test(gamesSplit2) {
console.log(gamesSplit2);
var ul = document.createElement("ul");
ul.id = "email-list";
ul.innerHTML = gamesSplit2;
document.getElementById('test').appendChild(ul);
}
Here is the php on the server (to this address mention in the url of the ajax)
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
$name = $_GET["name"];
$sql="SELECT * FROM `games`";
$reponse = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($reponse, MYSQL_NUM)) {
if ($row[2] == $name) {
echo $result = '
<a href="gamesReceipes.php?id=',$row[0],'">
<li class="unread clickable-row">
<div class="name">
',$row[1],'
</div>
<div class="message">
Voir la préparation
</div>
</li>;';
}
}
echo $result;
?>
So to explain, I'm executing my php script which gave me the $result and i'm supposed to display this result in my Ajax.
It's working on the emulator in the Intel XDK but not after when i'm building the app ! (Of course my phone have the 4g activated)
It's supposed to be like this on the display :
[
I hope you can understand my problem here ... Thanks guys !
By this link :
https://software.intel.com/en-us/articles/cordova-whitelisting-with-intel-xdk-for-ajax-and-launching-external-apps
Thanks yo #OldGeeksGuide who gave me this link ! I just had to add the link to my script in the intel xdk and it worked ! Thanks !
You appear to be trying to echo the same thing twice. returning data to an AJAX call should be done once and the last thing you do in the script.
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
$name = $_GET["name"];
$sql="SELECT * FROM `games`";
$reponse = mysqli_query($con, $sql);
// init the $result var
$result = '';
// incorrect parameter constant
//while ($row = mysqli_fetch_array($reponse, MYSQL_NUM)) {
while ($row = mysqli_fetch_array($reponse, MYSQLI_NUM)) {
if ($row[2] == $name) {
//echo $result = '
$result .= '
<a href="gamesReceipes.php?id=' . $row[0] . '">
<li class="unread clickable-row">
<div class="name">
' . $row[1] . '
</div>
<div class="message">
Voir la préparation
</div>
</li>;';
}
}
echo $result;
?>
You could also simplify this.
As you are passing the name of the game to this script you could add that to the query as a search criteria like so and then remove a lot of unnecessary processing.
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
// init the $result var
$result = '';
if ( isset($_GET['name'] ) {
$name = $_GET["name"];
$sql="SELECT * FROM `games` WHERE `name` = '$name'";
$reponse = mysqli_query($con, $sql);
// I assume there is only one ro w that contains this name
// so the loop is not required now
while ($row = mysqli_fetch_array($reponse, MYSQLI_NUM)) {
$result .= '
<a href="gamesReceipes.php?id=' . $row[0] . '">
<li class="unread clickable-row">
<div class="name">' . $row[1] . '</div>
<div class="message">Voir la préparation</div>
</li>;';
}
} else {
$result = 'No name parameter passed';
}
echo $result;
exit;
?>

Categories

Resources