Retrieving BLOB image from database using autocomplete selection - javascript

I'm trying to display a blob image stored in a database, I'm not getting any errors but the image isn't displaying, I'm just getting the default "no image" icon. Here's my code:
<script>
function showEmpimg(str) {
var xhttp;
if (str == "") {
document.getElementById("user-id").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("face").innerHTML = this.responseText;
}
};
xhttp.open("POST", "getimage.php?q="+str, true);
xhttp.send();
}
</script>
</head>
<body>
<div id="face" class="face">
</div>
<input type="text" class="form-control" id="user-id" placeholder="ID" name="emp_id" onchange="showEmpimg(this.value)" required maxlength="6" />
And the php file:
<?php
$db = mysqli_connect("localhost","root","test1","dar");
$sql = "SELECT emp_img FROM employees WHERE emp_id LIKE 'q'";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['emp_img'] ).'"/>';
?>
Any ideas?

Solved:
$db = mysqli_connect("localhost","root","test1","dar");
$sql = "SELECT * FROM employees WHERE emp_id=" . intval($_GET['q']);
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
//var_dump($result);
echo '<img class="face" src="data:image/jpeg;base64,'.base64_encode( $result['emp_img'] ).'"/>';

Related

How to print different varible value for different ids from ajax response?

How to get different variable value in different ids from ajax response.
In my programming get all responses from test.php file but i want to differently for both variable.
Index.php File:-
<html>
<span> Picture : </span>
<!-- In picture hint i want to print $varbilefirst value from test.php file -->
<span id="picturehintget"></span>
<input type="button" id="<?php echo "8"; ?>" class="submitnone" name="ansclick" onclick="QuestionId(this.id)" value="Submit">
<div> Demo : <p id="demoquiz"></p> </div>
<!--In Demo i want to print $varbilesec value from test.php file -->
<script type="text/javascript">
function QuestionId(obj)
{
var id = obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("demoquiz").innerHTML = this.responseText;
document.getElementById("picturehintget").innerHTML = this.responseText;
}
};
xhttp.open("GET", "test.php?id=" + id, true);
xhttp.send();
}
</script>
</html>
test.php file
<?php
$id = $_GET['id'];
$varbilefirst = "For Picture Hint";
echo $varbilefirst;
$varbilesec = "For Demo Hint";
echo $varbilesec;
?>
I want exactly different varible value for different ids.
<span id="picturehintget">For Picture Hint</span>
<p id="demoquiz">For Demo Hint</p>
You can try with in php file using array
<?php
$id = $_GET['id'];
$varbilefirst = "For Picture Hint";
$varbilesec = "For Demo Hint";
echo json_encode(["varbilefirst"=>$varbilefirst, "varbilesec"=>$varbilesec]);
?>
In Javascript
<script type="text/javascript">
function QuestionId(obj)
{
var id = obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("demoquiz").innerHTML = this.responseText.varbilesec;
document.getElementById("picturehintget").innerHTML = this.responseText.varbilefirst;
}
};
xhttp.open("GET", "test.php?id=" + id, true);
xhttp.send();
}
</script>
If I understood well your request you can return JSON from test.php like this:
<?php
$id = $_GET['id'];
$myObj->demo= $varbilefirst;
$myObj->picture = $varbilesec;
$myJSON = json_encode($myObj);
echo $myJSON;
?>
Inside if of Javascript:
if (this.readyState == 4 && this.status == 200)
{
var myObj = JSON.parse(this.responseText);
document.getElementById("demoquiz").innerHTML = myObj.demo;
document.getElementById("picturehintget").innerHTML = myObj.picture;
}

XMLHttpRequest not showing anything

I am using XMLHttpRequest like this:
I created one variable uname for storing username and one variable msg for storing messages.
<script>
function submitChat() {
if(form1.uname.value == '' || form1.msg.value == ''){
alert('ALL FIELDS ARE MANDATORY');
return;
}
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open('GET', 'insert.php?uname='+uname+'&msg='+msg, true);
xmlhttp.send();
}
</script>
My form looks like this
<form name="form1">
Enter your chat name: <input type="text" name="uname" /> <br />
Your message: <br />
<textarea name="msg"></textarea> <br />
Send <br/><br/>
<div id="chatlogs">
LOADING CHAT LOGS PLEASE WAIT...
</div>
what I am doing is that, when I am feeding data to the boxes(input and textarea) and then clicking the link(Send), then the chat logs should be displayed in the div section with id chatlogs, but its not happening, I created database like this:
<?php
$uname = $_REQUEST['uname'];
$msg = $_REQUEST['msg'];
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'chatbox');
mysqli_query($con, "INSERT INTO logs ('username', 'msg') VALUES ('$uname', '$msg')");
$result1 = mysqli_query($con, "SELECT * FROM logs ORDER by id DESC");
while ($extract = mysqli_fetch_array($result1)){
echo "<span class='uname'>" . $extract['username'] . "</span>: <span class='msg'>".$extract ['msg'] ." </span><br />";
}
?>
and logs look like this
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db('chatbox', $con);
$result1 = mysqli_query("SELECT * FROM logs ORDER by id DESC");
while($extract = mysqli_fetch_array($result1)){
echo "<span class='uname'>" . $extract['username'] . "</span>: <span class='msg'>" . $extract['msg'] . "</span><br />";
}
?>
Right now when I am filling the input and text area and then clicking the send link, nothing is happening. Neither the data is stored in database nor it is being displayed in the div section.
Thanks for your help in advance.

Ajax search doesnt connect to database

Iam trying to make a live ajax search . When you put a word it automatically shows suggestions bellow just like w3schools. But for some reason my index file and my php doesnt exchange data value or my database doesnt connect for some reason.What i always get is "no country found". Can you check the code for errors?
this is the php file :
<?php
include_once('dbconnect.php');
$q = intval($_GET['q']);
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
?>
and this is my index.php file :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function showCountry(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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","indexsearchquery.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input id="search-box" name="q" type="text" autocomplete="off" placeholder="Search country..." onchange="showCountry(this.value)" />
<input type='image' name='search' id="search-icon" value='Submit' src="search-icon.png" >
<p style="color:white;">Suggestions: <span id="txtHint" ></span></p>
Your country name will not in integer. but you convert it into intval change your php file to
include_once('dbconnect.php');
$q = $_GET['q']; //<-----remove intval
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
it is important to know the content of the dbconnect.php file because it the one that contains database connection variables.
Check if your MySQL Server is up and that all variable are well set.

New values don't update on db

I want to get data from database and change it, all with ajax but when I try to change the input ajax send the same data that was on database.
<script>
function showMore(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtMore").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtMore").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "getmore.php?q="+str, true);
xhttp.send();
}
</script>
<body>
<div class="content">
<button id="edit">Update</button>
<form action="">
<h3>Last Name:</h3><input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<span id="txtMore"></span>
</div>
</body>
<script type="text/javascript">
$('#edit').click(function(){
var ID = $('#id_field').attr('value');
var name_field = $('#FirstName').attr('value');
var last_field = $('#LastName').attr('value');
var telefone_field = $('#Telefone').attr('value');
var email_field = $('#Email').attr('value');
var check = $('#CheckIn').attr('value');
var dataString = 'id=' +ID+ '&FirstName=' +name_field+ '&LastName=' +last_field+ '&Telefone=' +telefone_field+ '&Email=' +email_field+ '&CheckIn=' +check;
alert(dataString);
$.ajax({
type: "GET",
url: "edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#txtHint").html('Actualizado');
}
});
});
</script>
And the php file where I get the data from database
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con = mysqli_connect('localhost','root','root','client_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$q = mysqli_real_escape_String($con, $_GET['q']);
mysqli_select_db($con,"client_db");
$sql='SELECT * FROM user WHERE id = "'.$q.'" ';
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo'<form method="GET" class="form_user">';
echo'<input type="hidden" name="id" id="id_field" value="'.$row['id'].'" class="inputForm"><br><br>';
echo'Primeiro Nome<br>';
echo'<input type="text" name="FirstName" id="FirstName" value="'.$row['FirstName'].'" class="inputForm"><br><br>';
echo'Ultimo Nome<br>';
echo'<input type="text" name="LastName" id="LastName" value="'.$row['LastName'].'" class="inputForm"><br><br>';
echo'Telefone<br>';
echo'<input type="text" name="Telefone" id="Telefone" value="'.$row['Telefone'].'" class="inputForm"><br><br>';
echo'Email<br>';
echo'<input type="text" name="Email" id="Email" value="'.$row['Email'].'" class="inputForm"><br><br>';
echo'<input type="checkbox" name="Check" id="CheckIn" value="Check">Check-in<br><br>';
echo'</form>';
}
mysqli_close($con);
?>
Thanks.
EDIT: The problem isn't the sql query but the values inside <input> if I change that values javascript read the old values and send them to php.
You're missing an UPDATE request on your DB.
Right now your request only do a SELECT, so no matter what data are sent to your server, you're not using it.
$sql='SELECT * FROM user WHERE id = "'.$q.'" ';
$result = mysqli_query($con,$sql);
You could to something like this :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con = mysqli_connect('localhost','root','root','client_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$q = mysqli_real_escape_String($con, $_GET['q']);
$Username = $GET['Firstname'];
$Lastname= $_GET['Lastname']
// Do so for every inputs your form will give you
$sql = "UPDATE 'user' SET 'Firstname' = '$Firstname','Lastname' = '$Lastname', etc...";
$result = mysqli_query($con,$sql);
mysqli_close($con);

Send multiple variable with PHP AJAX GET onclick of a button

I have two dynamically loaded dropdowns: one containing golf course holes information and another holding users- together the information will be used to generate a scorecard.
When the course is selected and a user is selected I want to click a button and then this will generate the scorecard.
Below is the code for the 'course' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT courseID, name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$courses[] = '<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
}
?>
Below is the code for the 'user' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT userID, forename, surname FROM user";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$users[] = '<option value="'.$row['userID'].'">'.$row['forename'].' '.$row['surname'].'</option>';
}
?>
Below is the HTML code for the dropdowns
<form>
<select id="selectCourse" onchange="showCourse(this.value)">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
At the moment I have code that uses the 'onchange' to load the first part of the scorecard which contains the hole information about that course. I am having problems changing this to the click of the button and also consider another variable from the user dropdown.
The below code is taken from W3Schools which loaded the hole information correctly based on 'onchange'.
<script>
function showCourse(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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
xmlhttp.send();
}
}
</script>
The below code shows the first half of the scorecard being generated from the selection of the first dropdown.
<?php
$cValue = mysql_real_escape_string($_GET['cValue']);
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT DISTINCT holeNumber, strokeIndex, par FROM holes WHERE courseID= '".$cValue."'";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
echo '<div class="scorecardTable">
<table>
<tr>
<th>HoleNumber</th>
<th>Par</th>
<th>Stroke Index</th>
<th>Score</th>
<th>Points</th>
</tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['holeNumber'] . "</td>";
echo "<td>" . $row['par'] . "</td>";
echo "<td>" . $row['strokeIndex'] . "</td>";
echo "<td> <input required type=text /></td>";
echo "<td> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
What I am looking to know is can I pass two variables through at this point below:
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
and if so how would I get the second variable.
EDIT
<script>
function showCourse(course, user) {
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
if (user || course == "") {
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","generateSC.php?course="+course+"&user="+user,true);
xmlhttp.send();
}
}
</script>
I've updated what I have above... the problem now is how do i get the button to work with the two variables?
<form>
<select id="selectCourse">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
Just fetch the values from both dropdowns and concatinate the URL:
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
xmlhttp.open("GET","generateSC.php?cValue="+course+"&user="+user,true);
Then your generateSC php script will of course have to fetch the value from the user parameter and work with that as well.
$_GET['user'] will fetch the value from the user parameter.

Categories