Display php variable into a JavaScript popup box - php

I have a php file which connects to a MySql db and read the last entry from a specific table. What I am trying to do, is to display(echo) the last entry from the table using a JavaScript popup box into the external html file
Below I have the code for the PHP file (which is working fine) and the html one but unfortunately I can't figure out how to pass the PHP variable to JavaScript function.
Many thanks in advance.
The php file would be this one:
<?php
// 1. Create a database connection
$connection = mysql_connect("localhost","root","password");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
// 2. Select database to use
$db_select = mysql_select_db("manage_projects",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
// 3. Perform database query
$result = mysql_query("SELECT survey_desc FROM subjects ORDER BY id DESC LIMIT 0,1", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
// 4. Use returned data
while ($row = mysql_fetch_array($result)) {
echo $row["survey_desc"]."<br />";
}
// 4.1 Alternative way to use returned data
/* $row = mysql_fetch_array($result);
echo $row["survey_desc"]."<br />";
*/
// 5. Close connection
mysql_close($connection);
?>
The html file:
<html>
<head>
<script type="text/javascript src="myscript.php"">
//if clicked Yes open new page if Cancel stay on the page
function popup(){
var r=confirm("echo the php query here");
if (r==true)
{
window.location = "http://example.com";
}
}
</script>
</head>
<body onload ="popup()">
</body>
</html>

You can echo into JavaScript:
var r=confirm("<?php echo $relevant_variable; ?>");
Also it's not recommended to use die() in a production environment.

<head>
<script type="text/javascript">
function popup(){
var xhr=null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if(xhr.readyState == 4){ alert_ajax(xhr); }
}
xhr.open("GET", "myscript.php", true);
xhr.send(null);
}
function alert_ajax(xhr){
var docAjax= xhr.responseText;
r=confirm(docAjax);
if (r==true)
{
window.location = "http://example.com";
}
}
</script>
</head>

Use PHP's json_encode()-function:
var r = confirm(<?php echo json_encode("the php query here"); ?>);
It escapes for you and always produces valid JavaScript, since JSON is a subset of the JavaScript syntax.

<?php
// Your php code;
$myVar="your value that you want to pass to js";
?>
<html>
<head>
<script>
//if clicked Yes open new page if Cancel stay on the page
function popup(){
var mvar = '<?php echo $myVar ;?>';
var r=confirm(mvar);
if (r==true)
{
window.location = "http://example.com";
}
}
</script>
</head>
<body onload ="popup()">
</body>
</html>
Just combine your both files in one php file.

Related

Image not updating through AJAX PHP

Following code is from a login page. I want to update the image of user when user fill username onkeyup. Image path is to get through PHP. Script code is given below:
function showUserPic(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// document.getElementById("img").innerHTML=xmlhttp.responseText;
x = document.getElementById("img");
x.src = 'users/'+xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
HTML Code is given below:
<input type="text" class="inputLabel1" style="margin:5px;" name="userText" onkeyup="showUserPic(this.value)" />
PHP file code is given below:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$user = intval($_GET['q']);
$conn = mysqli_connect("localhost","root","","pharmacy");
if (!$conn) {
die('Could not connect: ' . mysqli_error($con));
}
$query = "SELECT * FROM users WHERE username = '$user';";
$result = mysqli_query($conn, $query);
$userdata = mysqli_fetch_array($result);
mysqli_close($conn);
echo $userdata['image'];
?>
</body>
</html>
First of all a suggestion: $query = "SELECT * FROM users WHERE username = '$user';";is better to be $query = "SELECT image FROM users WHERE username = '$user';"; since there is no need to return all the columns from the table.
Then you should consider turning to PDO instead of deprecated mysql and mysqli extentions.
Then your issue is here:
$userdata = mysqli_fetch_array($result);
mysqli_close($conn);
echo $userdata['image'];
$userdata is an array. So you can't just echo it. You should consider to do:
foreach($userdata as $temp){
echo $temp['image'];
}
And also, as others are saying remove all the leading html from your php file and just echo image name.
As #dan-klasson stated - you need to return from server only image path. Your HTML and JS can stay AS-IS, but you need to change your PHP markup to just:
<?php
$user = intval($_GET['q']);
$conn = mysqli_connect("localhost","root","","pharmacy");
if (!$conn) {
die('Could not connect: ' . mysqli_error($con));
}
$query = "SELECT * FROM users WHERE username = '$user';";
$result = mysqli_query($conn, $query);
$userdata = mysqli_fetch_array($result);
mysqli_close($conn);
echo $userdata['image'];
?>
Your actual code are returning:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
example_image.jpg
</body>
</html>
and your script are inserting all of this into your image tag, so it will be:
<img src="users/%3C!DOCTYPE%20html%3E%0A%20%20%20%20%3Chtml%3E%0A%20%20%20%20%3Chead%3E%0A%20%20%20%20%3C%2Fhead%3E%0A%20%20%20%20%3Cbody%3E%0A%20%20%20%20example_image.jpg%0A%20%20%20%20%3C%2Fbody%3E%0A%20%20%20%20%3C%2Fhtml%3E"/>
It's probably not what you want :) Just change your PHP code.
EDIT:
One additional mistake in your code is that you have intval on your request parameter (which tries to be username):
$user = intval($_GET['q']);
Change it to:
$user = $_GET['q'];
You are passing username as string but getting variable using intval(). This will not work.
Print your response with this line of JS:
console.log(xmlhttp.responseText);
Or you can also inspect your image tag <img src="" /> with firebug and confirm whether you are getting the correct image name. If all is fine, check the file permissions of the user image folder and also the user image.

forgot password page in php

I wanted to create a forgot password page. To avoid mailing the user with his details, I decided to display his details in an alert box, although I know that it is much less secure!
So, here's my code in the php file "forgotdetails.php".
//Here are my database details, which I can't show.
$conn= mysql_connect($dbhost, $dbuser, $dbpass);
// Check connection
if(!$conn){
die('Could not connect'.mysql_error() );
}
$db_selected = mysql_select_db('users');
if(!$db_selected){
die('wrong'.mysql_error() );
}
$post_username = $_POST['email']; // the ajax post username
$query = "SELECT * FROM users WHERE id='". $post_username. "'";
$results= mysql_query($query);
$row=mysql_fetch_assoc($results);
$username=$row['id'];
$password=$row['pass'];
if(mysql_num_rows($results)==0)
{
echo "pass= " . $password;
echo "You haven't registered yet! Go to the Home-Page to Register!";
/*$query = "SELECT * FROM users WHERE id='$post_username' AND pass='$post_password'";*/
}
else
{
echo $password;
echo "Your Login details are-:"."\nUser ID- ". $username . "\nPassword- ". $password . "\nLogin to your account, to change your password. ";
}
And here's my ajax function (inside the html file) which is getting called as the forgot password button is clicked-:
<script lang="javascript" type="text/javascript">
function ajaxFunction1() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function ()
{ if (ajaxRequest.readyState == 4)
{ var ajaxDisplay = document.getElementById('results');
alert (ajaxRequest.responseText);
ajaxDisplay.innerHTML = "<br/><br/><h2><font color='#18E618'>"+ajaxRequest.responseText+"</font></h2>"; } }
// Now get the value from user and pass it to
// server script.
var email = document.getElementById('email').value;
//var bitsmailid = document.getElementById('bitsmailid').value;
if ( email== "" || email== null || email== '') {
alert("BITS ID Not Filled");
exit();
}
/*if ( bitsmailid== "" || bitsmailid== null || bitsmailid== '') {
alert("BITS Mail ID Not Filled");
exit();
}*/
var queryString = "?email=" + email;
ajaxRequest.open("POST", "forgotdetails.php" +queryString, true);
ajaxRequest.send(null);
}
</script>
My query is that, the I need to check whether the query returned through SQL in the PHP File ($results) is empty or not and then I need to perform the functions as i have mentioned in my code. I have used mysql_num_rows($results)==0 condition (which I got to know after reading similar posts on Stack Overflow). Although it doesn't seems to evaluate correctly. It evaluates true always, even though there are entries in the database.
I have read all the posts concerning this type of questions on Stack Overflow, and after 12+ hours of testing the code with many different possibilities, still I am still unable to solve my query. I have provided all the details necessary for my query, however If anyone needs anything, I will provide them with you.
I am a newbie into Web Development, so please help me to solve my query. Thank You in advance for your Help!
I am sorry if you feel that this question has already been answered earlier, however I posted this again because those posts sadly couldn't help me. I have read all of them. Sorry!
It should be
$sql = "SELECT * FROM users WHERE id='". $post_username. "'";
$result = mysql_query($sql, $conn);
if ($result && (mysql_num_rows($result) > 0)) {
// user exists
// here you get row
$row = mysql_fetch_assoc($result);
}
I know it is without pdo and it is insecure.

How do I show the PHP variable value in the JavaScript pop-up?

I have the following scripts. The user will pass a numerical value e.g. 123 as a parameter in the URL, and the app will load/fetch that value from MySQL and show it in the textarea.
E.g., entering, "example.com/index.php?id=123" in the URL will pull the 123rd record from the database and show it in the textarea. Everything seems to be working, but I want to show the last row/id of the "source" table when the form is submitted. So, instead of showing "Saved!" in the pop-up, it should show something like "124" (or, the last updated row/number).
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
connect-db:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password#123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
Please note that I do not need any advice on PDO or MySQLi, that is not important at this time. However, any suggestions on improving the security/SQL query etc. are welcome. Thanks.
I will try to answer in 2 parts:
[1] PHP side: in the "isset($_GET['id'])" section, just return the content of the text area you want to fill out. Say, in your DB, 123 -> 'Friday'. Just return the String 'Friday'.
[2] Client side: Do not "submit" the form. Call a JS function, and in there, create an XmlHttpRequest, and send the request to the server as an AJAX request. When you get the return value, examine it and populate your HTML textarea.
If you think this method is suitable for you and you need more details, let me know. I do this in many of my sites.

Why is PHP mysql_insert_id() returning zero?

I have the following code. The $last_id is always showing zero. I do have a column in the "source" table that has auto-increment id. What is the problem with this code?
index.php:
<?php
// connect to the database
include('connect-db.php');
$last_id = mysql_insert_id($connection);
$content = "Please type your content here!";
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: <?php echo $last_id;?>");
}
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
connect-db:
<?php
$server = 'localhost';
$user = 'mumbo';
$pass = 'mumbo123';
$db = 'jumbo';
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
try this as submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
echo mysql_insert_id();
}
?>
and in the javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: " + data);
}
);
return false;
});
});
</script>
This line is computed when the original page loads:
alert("Your ID: <?php echo $last_id;?>");
So it's effectively:
alert("Your ID: 0");
Since all you've done at that point is connect, there is no insert id. I'm not familiar with jquery, but presumably the data parameter to your callback should contain data about the response from submit.php. You need to make submit.php return the ID, then get that data through whatever means in jquery, and display it.
Edit: actually, it looks like what you're doing can't really do what I said, anyhow.
http://api.jquery.com/submit/
You're setting up a handler which is run whenever the form is submitted - however, this is before the submit actually happens, so you can't actually get the ID there. Your options are to use something like XmlHttpRequest to make an asynchronous call, or have this popup on the submit.php page.
First of all do not use mysql, use mysqli or pdo, mysql is a deprecated system and should not be used. It is not secure and can be hacked easily.
Second, mysql_insert_id only works if you call it directly after the insert...
AKA
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
$last_id = mysql_insert_id();
echo $last_id
mysql_close($connection);
then your jquery must say
alert("Your ID: "+data);
The function data that is returned is whatever you echo from your script. Jquery retrieves it in whatever callback variable you set (data) and then you can use it.

Live select/show/reload data from MySQL db when delete

I have three pages :
1)index.php (get results from select.php and put them into div#result )
2)select.php (loops into MySQL's table)
3)delete.php (gets user_id as a parameter and deletes it from MySQL's table).
My goal is : After user clicks on delete! to show updated results (after changes/deletes)
from MySQL's table
my problem is I could not know how to tell jQuery: listen process delete.php?id=123 & then
reload select.php while staying in index.php without redirecting to delete.php
so user actually does not see what happens or does not see that he's being redirected to
another page.
index.php
<html>
<title>a</title>
<head>
<script type="text/javascript" src="jquery-1.8.0.js"></script>
<script type="text/javascript">
$(function() {
$('#result').load('select.php');
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>
select.php
<?php
$con = mysql_connect("localhost","root","123");
if (!$con) { die('Could not connect: '); }
mysql_select_db("test", $con);
$result = mysql_query("select * from users");
while($rs3 = mysql_fetch_array($result)) {
echo $rs3["user_email"]." ".$rs3["user_name"]." ";
echo "Delete";
echo "<br />";
}
?>
delete.php
<?php
$con = mysql_connect("localhost","root","123");
if (!$con) { die('Could not connect: '); }
mysql_select_db("test", $con);
$id = mysql_escape_string($_GET["id"]);
$delete = "delete from users where user_id='{$id}'";
#mysql_query($delete);
?>
thank you.
Create not links, but AJAX query for delete. Make JQuery call for links. For example:
<script type="text/javascript">
$(function() {
function refreshContent(){
$('#result').load('select.php');
}
$('#result').on('click','a',function(event){
// prevent going by link `href`
event.preventDefault();
// get deleting row id
var ids = $(this).data('ids');
// make AJAX call for delete
$.get("delete.php", { id: ids},function(data){
// on success - refresh tcontent
refreshContent();
});
return false;
});
// making content load on start
$(document).ready(function(){
refreshContent();
});
});
</script>
Also u must add ids in <a>. In this line:
echo "<a href='delete.php?id=".$rs3[user_id]."' data-ids='".$rs3[user_id]."'>Delete</a>";

Categories