Image not updating through AJAX PHP - 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.

Related

Check a Promo Code from MYSQL Table on Website

I'm trying to create a system on my HTML website where you can enter a code which then gets checked by a php-file. The php shall compare the code with codes that are in my MYSQL Table. The php shall also check whether the code was allready used or not. After the check is completed a message shall appear on the Website that tells the user if his code is valid or not.
If the Code is valid, it shall inform me somehow that somebody entered a code.
I've wrote some code but when I press the button it's not working at all.Here my HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11/jquery.min.js">
</script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 6;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' has allready been used.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<center><h1>Enter Promo Code</h1>
<form method="post" action="check_code.php">
<input type="text" id="code" name="code" maxlength="6" />
<div id="promo_code_status"></div>
<br>
<input type="submit" value="Let's go"></center>
</form>
</body>
</html>
And here you have my PHP File:
<?php
//connect to database
$user = "***"; //Username
$pass = "***"; //Password
$host = "localhost"; //Host
$dbdb = "***"; //Database name
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select Code from Codes where Code = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
By pressing the Button "Let's go" the PHP shall do it's Job and afterwards it shall give the user the information about his code.
What do I have to change?
I thing you not assign the post value in $code, that's reason.
$code = mysqli_real_escape_string($connect, $_POST['code']);
make sure the jquery CDN that you are using can be accessed. because it looks like wrong CDN.
in the checkcode() function, you use #Promo_code_status, P is uppercase, while in html you use promo_code_status with p is lowercase.
in php file you forget to assign values to the $code
I hope this helps

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.

PHP Include another php that queries MySQL

In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.

Display php variable into a JavaScript popup box

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.

Categories