I'm developing a website using php. I have some problems. I want to know know how to get modified table values while running the php page without refreshing the page.
<html>
<?php
function fun_get_user_name() {
$host_name = "localhost";
$db_user_name = "root";
$password = "";
$database_name = "database_name";
$connect = mysqli_connect($host_name, $db_user_name, $password, $database_name);
$query = "SELECT * FROM `users` ";
$result = mysqli_query($connect, $query);
$output = "";
while ($row = mysqli_fetch_array($result)) {
$output = $output."<br/>"..$row[0];
}
}
?>
<script>
function js_function() {
result = "<?php echo fun_get_user_name; ?>";
document.getElementById('div_body_users').innerHTML = result;
}
window.setInterval(function() {
js_function();
}, 1000);
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
when I made a change in phpmyadmin table the change didn't affect the page. But I expected the updated table.
So move the fun_get_user_name to another file and then in a setInterval do a n ajax call to that file.
$.get( "users.php", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
For more info on ajax request look at this link
https://api.jquery.com/jquery.get/
On user.php you just need to add fun_get_user_name
You can do it with using ajax, here changed with your ajax url and database connection details.
<html>
<?php
function fun_get_user_name()
{
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
}
if($_GET['ajax']==1){
$data=fun_get_user_name();
echo $data;
exit(0);
}
?>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function(){
setInterval(js_function,1000);
function js_function()
{
$.ajax({
url: "http://localhost/test2/test.php?ajax=1",
data: '',
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (result) {
document.getElementById('div_body_users').innerHTML=result;
}
});
}
});
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
You for update page without page refresh you have to use AJAX along with setInterval function.
Please check below link
https://www.w3schools.com/asp/asp_ajax_intro.asp
Related
I want to display the array data that I have called in getword.php into the text field in index.php using AJAX. but how ?
this is the index.php
<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "POST",
url: "getword.php",
dataType: "json",
success: function($result){
$('#wordlist').val('');
}
});
});
})
</script>
and this is the sql query to get data from database into array (getword.php)
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "wordlist";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select kata from word";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
$result[]= $row[0];
}
echo json_encode(array('kata'=>$result));
mysqli_close($con);
?>
I would suggest you write PHP code as below it will be lot more simple
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "wordlist";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT kata FROM word";
$res = $con->query($sql);
while($row = mysqli_fetch_array($res)){
$dataToSend = $row[0];
}
mysqli_close($con);
echo json_encode($dataToSend);
?>
Now the script be like this to place the result in the text box
$.ajax({
type: "POST",
url: "getword.php",
dataType: "json",
success: function($result) {
var val = JSON.parse($result);
console.log(val); // see console in browser to check what is sent back
var txtBox = docuent.getElementById('wordlist');
txtBox.value = val;
}
});
Here I guess the data from the PHP file will be a single value since you are using a single text box. if multiple values are there then use an array to store data in PHP and send it in json_encode() itself.
hope that this becomes helpful to you.
I have my php file on a server that retrieves data from my database.
<?php
$servername = "myHosting";
$username = "myUserName";
$password = "MyPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM tableName;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row_number = 0;
while($row = $result->fetch_assoc()) {
$row_number++;
echo $_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Unfortunately, I do not know how to receive data from a php file using javascript.
I would like the script in javascript to display the received data in the console in browser.
The script written in javascript is Userscript in my browser extension(tampermonkey) and php file is on my server.
I've tried to use ajax, unfortunately without positive results.
(the php script works as expected).
JS(not working):
$.ajax({
url: 'https://myserver.com/file.php',
type: 'POST',
success: function(response) {
console.log(response);
}
});
The code within the loop is a little screwy
$_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"]
that suggests a very oddly named querystring parameter which is not, I think, what was intended.
Instead, perhaps try like this:
<?php
$servername = 'myHosting';
$username = 'myUserName';
$password = 'MyPassword';
$dbname = 'myDbName';
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) {
die( 'Connection failed: ' . $conn->connect_error );
}
$sql = 'select `id`, `name`, `description` from `tablename`;';
$result = $conn->query($sql);
if( $result->num_rows > 0 ) {
$row_number = 0;
while( $row = $result->fetch_assoc() ) {
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
} else {
echo '0 results';
}
$conn->close();
?>
A full example to illustrate how your ajax code can interact with the db. The php code at the top of the example is to emulate your remote script - the query is more or less the same as your own and the javascript is only slightly modified... if you were to change the sql query for your own it ought to work...
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* emulate the remote script */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql= 'select `id`, `address` as `name`, `suburb` as `description` from `wishlist`';
$res=$db->query( $sql );
$row_number=0;
while( $row=$res->fetch_assoc() ){
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Basic Ajax & db interaction</title>
<script>
$( document ).ready( function(){
$.ajax({
url: location.href,
type: 'POST',
success: function( response ) {
console.log( response );
document.getElementById('out').innerHTML=response;
}
});
} );
</script>
</head>
<body>
<div id='out'></div>
</body>
</html>
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["id"])) {
$id = $_POST["id"];
if (is_int($id)) {
$query = "select * from alumni_users where userId = '$id' ";
$update = mysqli_query($mysqli, $query);
$response = array();
while($row = mysqli_fetch_array($update)){
.......
fill your response here
}
echo json_encode($response);
}
}
break;
}
}
Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter
then in your ajax:
function getdetails() {
var value = $('#userId').val();
return $.ajax({
type: "POST",
url: "getInfo.php",
data: {id: value}
})
}
call it like this:
getdetails().done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data
}
})
Hope it helps
I'm new to PHP programming and I'm trying to test out a login page alongside JSON and MySQL. I managed to make most of it functional but I can't seem to find a way to make the query in which I verify the username and password to work.
Please help.
Here's the code:
login.js:
$(document).ready(function(){
$('#errorLogin').hide();
$('#formLogin').submit(function(e){
var username=$('#inputUser').val();
var password=$('#inputPassword').val();
$.ajax({
type:'get',
dataType: 'json',
url: 'dist/php/connection-login.php',
data: {
user: username,
pass: password
},
success: function(e){
console.log(e);
}
});
});
});
connection-login.php:
<?php
$con = new mysqli("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$result = mysqli_fetch_assoc($qry);
$row = mysqli_fetch_assoc($result);
if ($row != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
Your PHP should be more like:
connect.php - make sure this is a separate secure page
<?php
function db(){
return new mysqli('localhost', 'root', 'root', 'solucionar_manutencoes_db');
}
?>
I would change your JavaScript AJAX to a POST request, unless you have a reason for it.
connection-login.php
<?php
sesson_start(); include 'connect.php';
if(isset($_POST['user'], $_POST['pass'])){
$db = db(); $r = array();
$prep = $db->prepare('SELECT `lg_user` FROM login WHERE `lg_user`=? && lg_user=?');
$prep->bind_param('ss', $_POST['user'], $_POST['pass']); $prep->execute();
if($prep->num_rows){
$prep->bind_result($lg_user); $r['user'] = $lg_user;
$_SESSION['logged_in'] = $lg_user;
}
echo json_encode($r);
}
?
Now if your JavaScript AJAX result does not contain the a e.user then they are not logged in. Of course, you would probably want to store the original password as a SHA1 or stronger and use AES_ENCRYPTION or better for Personal Information, along with SSL.
I see several errors in your code. The first is that you are executing mysqli_fetch_assoc twice: once on the result, and then again on the array the first call returned. The next is that the $response variable was never declared. Here is the fixed PHP script:
<?php
$con = mysqli_connect("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$results = mysqli_fetch_assoc($qry);
$response = [];
if (count($results) != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
In your JavaScript make sure to use e.preventDefault() inside #formLogin's submit handler to prevent page reload when that form is submitted.
Below is my php file to apply query
$host = "localhost";
$user = "root";
$pass = "abc123";
$databaseName = "class";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT id, name FROM lecturer");
if (mysql_num_rows($result)) {
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
header('Content-type: application/json');
echo json_encode( $data );
}
And this is my other file where i am applying javascript. I have searched a lot of same queries but could not find solution. Please help me
<script type="text/javascript">
function lecturer(){
$("#a1_title").empty();
$("#a1_title").append("<option>Default</option>");
$.ajax({
type:'POST',
url : 'get-data.php',
contentType :"application/json; charset-utf8",
dataType:'json',
type:'POST',
success:function(data){
$('#a1_title').empty();
$('#a1_title').append("<option>Default</option>");
$.each(data, function(i, data){
$('#a1_title').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
});
},
complete: function(){
}
)};
}
$(document).ready(function(){
lecturer();
});
</script>
Please help me I have tried to solve this problem buy i am not able to do it.
Your PHP code had bad syntax since you had your array() was surrounded with curly braces rather than parentheses. You also had some errors in your $.ajax, a misplaced parentheses. In addition, you do not need an iterator ([i]) in your $.each() function - you can just get each item's bit of information by associating this iteration's values. And as #Jay Blanchard said, mysqli would be used best here.
Try the following editions:
PHP:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "test";
$con = mysqli_connect($host, $user, $pass, $databaseName);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, name FROM lecturer");
if (mysqli_num_rows($result)) {
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
JS:
<script type="text/javascript">
function lecturer() {
$("#a1_title").empty();
$("#a1_title").append("<option>Default</option>");
$.ajax({
type: 'POST',
url: 'get-data.php',
contentType: "application/json; charset-utf8",
dataType: 'json',
type: 'POST',
success: function (data) {
$('#a1_title').empty();
$('#a1_title').append("<option>Default</option>");
$.each(data, function (k, v) {
$('#a1_title').append('<option value="' + v.id + '">' + v.name + '</option>');
});
},
complete: function () {
}
});
}
$(document).ready(function () {
lecturer();
});
</script>
I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.