outputting data From Mysql to js/HTML - javascript

So Basically this is what i want to do , I want to take data from my database and then put that data on a page after the user logs in , however i am havinng problems understanding a way , So here's some sample code for clarity :
//user has logged in:
//fetched data from database to php file
$name = $result['name'] //result being the object after the queried row is fetched
now i want to add this name in lets say a div in my HTML
<div id="name"><!--$name comes here--></div>
So what is the way to do this using JS ? is AJAX the answer?

I guess that you have $name in the login.php file and the div is in profile.php. You can use session variables or ajax:
By php:
login.php
<?php
session_start();
$_SESSION["name"] = $result['name']
?>
profile.php
<?php
session_start();
?>
<div id="name"><?php echo $_SESSION["name"]; ?></div>
By ajax:
getName.php
$name = $result['name'];
echo $name;
profile.js
$.get("getName.php", function(data, status){
$("#name").append(data);
});

Related

PHP get information from database when echoed html code is clicked

In my code, I am retrieving data from the database using a while loop so i can have all the $FormData['fullname'] in the db.
What i want to do is, have each name display on the page and also have clickable so when someone clicks a name, it gets their user_id and pulls up information about them.
The problem i am having is that I can't figure out a way to make a it so where i can get the user_id when the user clicks a name. I tried putting a "name" in the button attribute and I checked if isset() but that didn't work.
If someone can properly figure out a way for me to basically, display all the fullnames in my database and when someone clicks a name, it pulls up information about them that is stored in the database. Here is my code
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch()){
echo "<button name='name'>$formData[fullname]</button>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(isset($_POST['name'])){
echo "ok";
}else{
echo "bad";
}
}
}
As far i can see you are trying hit a button inside the while loop , i would not say its a bad approach , but i will suggest you not to do that . and from your code i can see you have lack of understanding post and get request learn from here . and other than this you need to know the transition of web url . how its actually works . anyway , i have given a sample code without . i hope it will help you understanding this concept.
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch(PDO::FETCH_ASSOC)){
$id = $formData['formdataid'];
echo "<a href='somepagename.php?infoid={$id}'>". $formData['fullname']."</a></br>";
}
now in the somepagename.php file or in the same page you can actually show the details information for instance
if(isset($_GET['infoid'])){
$stmt = $handler->prepare("select * from formdata where formdataid='"$_GET['infoid']"'");
$qry = $stmt->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
echo "<p>id =".$row['formdataid']."</p></br>";
echo "<p>id =".$row['name']."</p></br>";
echo "<p>id =".$row['email']."</p></br>";
echo "<p>id =".$row['address']."</p></br>";
code is not executed , it may have semicolon or comma error warning . you have to fix those on your own . this example above shown you only the way it works .
if still you have problem ask , or see the documentation
I should stress that this is not production code and you should totally validate the data input coming in before posting queries to your DB. You can do something like this.
<?php
// Connect
$connection = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Grab all users
$sql = 'SELECT * FROM users';
$users = mysqli_query($connection, $sql);
if (($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['user_id'])) {
$query = "SELECT * FROM users WHERE user_id = {$_POST['user_id']};";
$user = mysqli_fetch_assoc(mysqli_query($connection, $query));
}
?>
// This only runs if our $user variable is set.
<?php if (isset($user)) : ?>
<?php foreach ($user as $key => $value) : ?>
<span><?= print_r($value) ?></span>
<?php endforeach; ?>
<?php endif; ?>
// Display all users in a dropdown and when the button is clicked
// submit it via post to this page.
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select name="user_id">
<?php foreach ($users as $user) : ?>
<option value="<?= $user['user_id'] ?>"><?= $user['name'] ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Submit</button>
</form>
This is going to refresh your page every time. If you want to have an interactive page you are going to need to use JavaScript/AJAX to update the page elements without reloading the page. This example just demonstrates how you can achieve this with PHP and HTML.
you need to know about server-side language(php) and client-side language(javascript).
php runs before page loaded. it cannot runs when click something by itself(with ajax, it can).
most interactions without page move runs with javascript.
in your case, there are two methods.
store all information into hidden input or button's attribute. and get them by user_id via javascript.
use ajax to call another php that can select informations you need by user_id.
both use javascript or jquery. so you must learn about them.

PHP variable is not included when loading with javascript .how to include php inside javascript?

My js code re-loads the comments.php in every 3 seconds .
I have included comments.php in index.php and it does get all the variables from index.php but when js reloads comments.php it does not get the variable and shows error .
First time it works cause it's included with php . After the re-load it's not included anymore .
How can i include comments.php in index.php inside js.
index.php
<?php
if (isset($_GET['slug'])){
$page_id = $_GET['slug'];
}
?>
<div id="comments">
<script type="text/javascript" >
$(document).ready(function(){
setInterval(function(){
$('#comments').load('comments.php')
},3000);
});
// when loading comments.php with js $page_id is not gotten and showing error
</script>
<?php include("comments.php") ; ?>
// first time shows this and comments.php does get the varible $page_id
</div>
comments.php
<?php
$page_id = $_GET['slug'];
$get_com = " SELECT * FROM `comments` where post_id='$page_id' ORDER BY `comment_id` DESC ";
$run_com = mysql_query($get_com);
?>
When you include("comments.php") it inherits the variables from index.php. When you reload with load('comments.php') you are doing it via HTTP and there is no GET variable slug because you are not passing it:
$('#comments').load('comments.php?slug=<?=urlencode($page_id)?>')
The simplest way to do this is to simply echo the PHP variable to JavaScript:
var page_id = '<? echo $page_id ?>';
var get_com = '<? echo $get_com ?>';
var run_com = '<? echo $run_com ?>';
Assuming those variables are populated by the time the PHP is finished, JavaScript will be able to make use of them.

Redirect and popup when sql is done

I want to get my application when a item is deleted pop up a messege and redirect to another page. I used javascipt for the popup and php header for the redirection. Now its only doing or the popup or the redirect depending which one is listed first. how do i fix this?
<?php
session_start();
require_once('../../includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: ../../login.php');
$Cursist = mysqli_query($con, "SELECT id FROM users WHERE id =".$_SESSION['id']);
if(!$Cursist){
header('location: ../login.php');
}
$test = $_GET['id'];
$sql = "DELETE FROM cursus WHERE id = $test";
$result = mysqli_query($con, $sql);
if ($result) {
echo "<script type='text/javascript'>alert('Verwijdert!')</script>";
header("Location: ../cursussen.php?destoyed=true&destroyed_id=".$_GET['id']);
}else {
echo "mislukt";
}
?>
If you send sometrhing before header will not work. You can use only header before sending sometrhing to the client.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
http://php.net/manual/en/function.header.php
You could do with javascript but It not recommended because the user could have javascript disabled:
echo "<script type='text/javascript'>";
echo "alert('Verwijdert!')";
echo "document.location.href='index.html'";
echo "</script>";
The best way is to use session and header, you can save a var in session and show a message when the var is true and when you show the messasge delete the session var
delete.php
$_SESSION['deleted'] = true;
header("Location: index.php);
index.php
<?php if($_SESSION['deleted']){ ?>
<?php unset($_SESSION['deleted']) ?>
<div>Item was deleted</div>
<?php } ?>
Well, the problem is that the redirect immediately moves you to a new page, so any javascript on the old page becomes irrelevant. You might be able to use a delay before redirect so that the javascript alert can display.
Otherwise, introduce a variable that you send to the redirect destination page, and use this variable to trigger a javascript popup there.

Assign a PHP variable into a javascript variable not working As expected

Hi I am checking my company web sites XSS vulnerability , by adding some script tags to inputs . actually my company site was vulnerable .
<script>alert("Xss Attack");</script>
This alerts
Xss Attack
Now I am trying to do more testing to understand it more , now I am trying to get the session id and pass it to some other web site , then I will get the session id and I will gain the user access using that session_id . this is my code to get session_id , I typed this to my input field and submitted the form.
<script>var sess_id = "<?php echo session_id(); ?>"; alert(sess_id); </script>;
but this only alert <?php echo session_id(); ?>
In my php I out put the variable as
<td> <?php echo $name;?> </td>
BUT
In my PHP page if I directly type the code
<script>var sess_id = "<?php echo session_id(); ?>"; alert(sess_id); </script>
It correctly gets me the session id like ba6k806tlcbvqs0l39ipcms956
I think in my 2 nd case it works correctly because it has no wrapping PHP tags.
In the 1 st case It has wrapping PHP tags <?echo $name;?> .
So how should i add the session_id to javascript variable sess_id ? , please help . thanks in advance :)

Update innerHTML by an email

I don't know if this is possible so I'm very open to trying other methods to achieve similar results.
Basically I have a website and a certain div
<div id="mainContent">Content here...</div>
What I want to do with this, is be able to send an email to a certain address or something similar and the body of the email will define the "innerHTML" of this div.
I can imagine it would look something like this in Javascript:
document.getElementbyId("mainConetent").innerHTML = emailBody;
With obviously "emailBody" being a pre-defined variable.
I am almost certain nothing like this could work but is there any way to achieve a similar thing?
I also know that 'innerHTML' in javascript becomes restored when a page is refreshed. I would like it to be there permenantly on the original document, until a new email is recieved with the new content. This method with javascript is probably not the way to do is. I just used it to explain bettter
Store email body in input hidden field and then using javascript you can retrieve them based on id and store them in respective div.Try this:
html:
<div id="mainContent">Content here...</div>
<input type="hidden" value="<?php echo $inputbody;?>" id="emailbody">
javascript:
var emailBody = document.getElementbyId("emailbody").value;
document.getElementbyId("mainContent").innerHTML = emailBody;
Updated Example:
<?php
$to = "someone#example.com";
$subject = "Test mail";
$inputbody = "Hello! This is a simple email message."; // insert this into hidden field
$from = "someonelse#example.com";
$headers = "From:" . $from;
?>
In your index.php file add the following piece of code for database connection
<?php
// Create connection
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM table_name Where type='mail'"));
//Inside your mainContent div
<div id="mainContent"><?php echo $result['innerhtml'] ?></div>
?>
In your js file
If your email is being sent on button click perform this
$('#button').on('click',function(){
emailBody = document.getElementbyId("mainConetent").innerHTML;
$.ajax({
type: "POST",
url: "update_mail content.php",
data: "emailBody="+ emailBody,
success: function(){
}
});
})
//Updates the content in the databse table usinganother php file named update_mail content.php .This flow might help u mate.. :)

Categories