Questions on PHP,MYSQL,AJAX - javascript

I have encountered a problem, where I planned to get values with javascript which is from mysql.
What I am trying to do is, when you load a PHP page to edit info, you add a div using javascript, there will be a bunch of types to choose from, But I would like to do it through retrieve from database. But it seems doesn't work, so I went on with another type of code.
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$mysql_server_name="localhost";
$mysql_username ="root";
$mysql_password ="root";
$mysql_database ="master_db";
$conn =mysql_connect($mysql_server_name,$mysql_username,$mysql_password);
if (!$conn)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysql_database,$conn);
$sql="SELECT * FROM `bopl_certification_type`";
$result = mysql_query($sql);
echo "<div class='span6 form-horizontal'><i class='icon-remove' onclick='removeDiv(this)'></i><div class='control-group'><label class='control- label'>Certificate Name: </label><div class='controls'><select style='width:250px' name='certType[]'>";
//To get option
while($row = mysql_fetch_array($result)) {
echo "<option value=$row[certName]>$row[certName]</option>";
}
//End of option
echo "</select><input type='text' class='input-xlarge' name='test' style='width:235px' name='fileInServ[]' readonly='readonly' /><input type='file' name='docupload[]' /></div><div class='control-group'><label class='control-label'>Issue date: </label><div class='controls'><input type='text' id='datepickerIs' name='certIsDate[]' placeholder='dd-mm-yyyy' class='comboDate' /></div></div><div class='control-group'><label class='control-label'>Expired date: </label><div class='controls'><input type='text' id='datepickerEx' name='certExDate[]' placeholder='dd-mm-yyyy' class='comboDate' /></div></div> </div>";
?>
</body>
</html>
That was the getuser.php and this is the index.html
<html>
<head>
<script>
function showUser() {
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","getuser.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onclick="showUser()">
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
This is the proper result that I wanted. But it seems that I tried to integrate into my existing codes. It doesn't work at all. Is there any other way around it?

First I would create a function for your server calls to simplify things. This is the one that i use but it uses the main thread so if you want it to be async then you will have to add on readystatechange and change true to false on the initial declaration however, this is my function for retrieving.
function httpGet(theUrl){
//FETCH Data From Server
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", theUrl , false );
xmlhttp.send();
return xmlhttp.responseText;
}
Then from anywhere in your script you can call
document.getElementById("txtHint").innerHTML = httpGet("getUser.php");
now for any additional help we really need to know, what errors your receiving.

Related

how to put search results inside a div using ajax

the idea is, I want to put my search results from mysql inside "result_div" without reloading the whole page using ajax. thank you.
<button class="btn btn-default" id = "search_jo" >
<?php
if(isset($_POST['search_jo'])){
?>
<div class="panel-body" id = "result_div">
<?php
$sql = "some sql statement here";
$retval = mysql_query( $sql, $db_conn);
while($row = mysql_fetch_array($retval, MYSQLI_ASSOC))
{
// php echo statement here fecthing data from sql
}
mysql_free_result($result);
?>
</div>
<?php
}
?>
try this w3school code
<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
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("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>

Send image data from an html tag using AJAX to PHP and save it in MySQL as blob data

I want to send the image data from the html img tag using AJAX and save it in my MySQL db. I have a column in my db which is a longblob datatype, thats where I'm going to store the image. I also have other data that I'm going to save along with it but my main concern is the image, I don't know how to do it. I did try to find answers here on and other sites but didn't find what I was looking for. My code looks like this.
HTML:
<div class="col-lg-12">
<div class="form-group col-lg-4">
<label>ARP No.</label>
<label>
<input type="text" name="arp-no" class="form-control" id='arp-no' required=""/>
</label>
</div>
<div class="form-group col-lg-4">
<label>Owner</label>
<label>
<input type="text" name="owner" id="owner" class="form-control" value="" required=""/>
</label>
</div>
</div>
this is where the image tag is
<div class="col-lg-6">
<div class="form-group col-lg-12">
<img name="map-sketch" id="image" width="100%" height="100%" src='http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg'></img>
</div>
</div>
<div class="row">
<div class="col-lg-1">
<button type="button" class="btn btn-primary" onclick="saveFaas()">Save</button>
</div>
<div class="col-lg-2" id="saving-info"></div>
</div>
Javascript AJAX:
function saveFaas(){
if (confirm('Are you sure you want to save this information?')) {
var params = 'kind=land';
params += '&arp-no='+document.getElementById('arp-no').value;
params += '&owner='+document.getElementById('owner').value;
//the image data
params += '&image=';
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("saving-info").innerHTML = xmlhttp.responseText;
}else { // waiting for result
document.getElementById('saving-info').innerHTML = '<img src="../images/ajax_loader.gif">';
}
}
xmlhttp.open("POST", "../functions/save-faas.php", true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(params);
}}
Can I pass the image data like the others?
Php:
<?php
//db info
include('../fragments/db-config.php');
// Create connection
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$kind = $_POST['kind'];
if ($kind == 'land') {
$image = $_POST['image']; // the image
$arp_no = $_POST['arp-no'];
$owner = $_POST['owner'];
$sql = "UPDATE faas SET arp_number='$arp_no', owner_name='$owner'
WHERE faas_id=$faas_id;";
}
if ($conn->query($sql) === TRUE) {
echo "<label>Record Updated</label>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); ?>
So to wrap it up. I have an image data in my html, call ajax to send the image and the other data in php and save it in mysql db.
My javascript code here is in plain javascript so I would like a plain javascript solution also. Thank you.

PHP session variable's value in 1st page not updating to value of session variable in 2nd page after 2nd GET request

I am using session variables in PHP. I am making an ajax request from modifyDetails.php to another php file named getDetails.php using :
xmlhttp.open("GET", "getDetails.php?val=" + str, true);
I am trying to change the values of form fields based on the selection made in dropdown list. I am getting it correct when I make a selection for the first time
but when i make a different selection now , the values are still the same.
I have checked the values of session variable $_SESSION['Member_details'] in getDetails.php and it's values are perfectly fine but the session variable in
modifyDetails.php is not updating it's value.
"modifyDetails.php"
<?php
session_start();
$fid = $_SESSION['fid_value'];
$get_Member_details = $_SESSION['Member_details'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Modify Details</title>
<script src="/prj/jquery.min.js"></script>
<script>
function fillData(str)
{
$(document).ready(function()
{
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("kk").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "getDetails.php?val=" + str, true);
xmlhttp.send();
//window.alert(str);
var jage= "<?php echo $get_Member_details['age'];?> ";
var jsex= "<?php echo $get_Member_details['sex'];?> ";
var jdob= "<?php echo $get_Member_details['dob'];?> ";
//alert(jdob);
var jrelation = "<?php echo $get_Member_details['Relationship'];?> ";
var jcontact = "<?php echo $get_Member_details['contact'];?> ";
var jaddress = "<?php echo $get_Member_details['address'];?> ";
var jpin = "<?php echo $get_Member_details['pin'];?> ";
document.getElementById("Age").value = jage;
//document.getElementById("Sex").value = jsex;
document.getElementById("Dob").value = jdob;
document.getElementById("Rel").value = jrelation;
document.getElementById("Contact").value = jcontact;
document.getElementById("Address").value = jaddress;
document.getElementById("Pin").value = jpin;
});
}
</script>
<style>
body{
background-color:lightgrey;
}
#button {
background-color: green;
border: none;
color: white;
padding: 8px 14px;
text-align: center;
text-decoration: none;
font-size: 17px;
margin: 2px 4px;
cursor: pointer;
}
table { padding:2px 6px;}
</style>
</head>
<body>
<h1>Customer Form </h1>
<h3>Please fill in the details below:</h3>
<form action="modified.php" method="post">
<table style="width:24%;">
<tr><td>Family ID:</td><td><input type="text" name="fid" value="<?php echo "$fid";?>" readonly /></td></tr><tr></tr>
<tr><td>Name:</td>
<td>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('project');
$sql_query = "SELECT name FROM family WHERE fid=$fid";
$records = mysql_query($sql_query);
echo"<select name='member_name' onchange='fillData(this.value)'>";
while( $family_member = mysql_fetch_array($records) )
{
echo "<option value='".$family_member['name']."' >".$family_member['name']."</option>";
}
echo "</select></td></tr>";
?>
<div id="kk">
</div>
<tr><td>Age:</td><td><input id="Age" type="text" name="age" required /></td></tr><tr></tr>
<tr><td>Sex:</td><td><input id="Sex" type="radio" name="sex" value="Male" required />Male
<input id="Sex" type="radio" name="sex" value="Female" required/>Female</td></tr><tr></tr>
<tr><td>Date of Birth:</td><td><input id="Dob" type="text" name="dob" required /></td></tr><tr></tr>
<tr><td>Relationship:</td><td><input id="Rel" type="text" name="relation" list="relations" required>
<datalist id="relations">
<option value="Son">Son</option>
<option value="Daughter">Daughter</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="GrandMother">GrandMother</option>
<option value="GrandFather">GrandFather</option></td></tr><tr></tr>
</datalist></td></tr>
<tr><td>Contact Number:</td><td><input id="Contact" type="text" name="contact" required /></td></tr><tr></tr>
<tr><td>Address:</td><td><input id="Address" type="text" name="address" required /></td></tr><tr></tr>
<tr><td>Pincode:</td><td><input id="Pin" type="text" name="pin" required /></td></tr><tr></tr>
</table> <br>
<input id="button" type="submit" value="Submit"/>
</form>
<br><br><br>
<h4>Back to Search Page</h4>
</body>
"getDetails.php"
<?php
session_start();
$fid =$_SESSION['fid_value'];
?>
<?php
$name=$_GET['val'];
echo $name;
mysql_connect('localhost', 'root', '');
mysql_select_db('project');
$sql_query = "SELECT * FROM family WHERE fid=$fid AND name='$name'";
$records = mysql_query($sql_query);
$_SESSION['Member_details'] = mysql_fetch_array($records);
$hold = $_SESSION['Member_details'];
//echo $hold['dob'];
//echo $hold['contact'];
?>
Ajax call happens after page load, you JS is getting rendered when the session is in State 'A'.
Once you make your Ajax call, it`s in sate 'B', but at that point call to Session has already been made and the initial view is already rendered.
So, to fix the situation you should pass variables that are changing through Ajax reposne with JSON for example.

How to give user defined timeout message when max execution time over by handeling properly

I am designing custom query page where user can fire query and get the desired result.
In my database I have crores of records obviously it takes time around 10 to 15 minutes to execute .
After timeout page gets terminated and code below the php script is not executed so it is not showing below design and footer.
Please let me know how to handle timeout properly so that whole page executes and gives proper user defined timeout message and also below design and footer if execution time exceeds.
Here is what I am trying to do...
<form onsubmit="custom.php;" id="usrform" method="post">
<textarea id="tarea" placeholder=" Example: select malindex,malname,virustype,filetype,count from CT_DETECTIONS;" name="query" form="usrform" style="width:800px;height:100px;"></textarea>
<br>
<br><input type="submit" value="Submit Query" onclick="validate();">
</form>
<br>
<?php
//DB connection
if(isset($_POST['query'])&& $_POST['query']!='')
{
$x = $_POST['query'];
$result = mysqli_query($con,$x);
if(!$result)
{
$msg='<b>Error: </b>Invalid query. Enter a valid query. Please refer to Database Schema <b style="color:black;">here</b> ';
}
else
{
$x="<b>Query: </b>" .$_POST['query'];
//fetching rows and drawing google chart table
<?php echo $x;
}
}?>
<div id="valid" style="color:red;">
<?php echo $msg; ?>
</div>
<div style="color:red">
<lable id="myP"> </lable>
</div>
</div>
</div>
<div id="visualization" style="width:800px; height: 450px;color:black;margin-left:22px;"></div>
</div>
</div>
Please let me know how to handle page termination due to timeout
You could either change the time limit by using set_time_limit(60*60); www.php.net which will set it to 1h or take a look on this article on Stackoverflow.
You can check for the maximum execution time value from this script:
if(ini_get('max_execution_time')</*Set value do you want(integer)*/{
//Overlimit
}
else{
//Your script
}
Using AJAX :
<?php
//DB connection
if(isset($_POST['query']))
{
// MUST BE FIRST OUTPUT (nothing before)
header('Content-type: text;charset=UTF-8');
$x = $_POST['query'];
$result = mysqli_query($con,mysqli_real_escape_string($con, $x));
if (!$result)
{
echo '<b>Error: </b>Invalid query. Enter a valid query. Please refer to Database Schema <b style="color:black;">here</b> ';
exit();
}
//fetching rows and drawing google chart table
echo $x;
exit();
}
?>
<form onsubmit="return submitUsrForm();" id="usrform" method="post">
<textarea id="tarea" placeholder=" Example: select malindex,malname,virustype,filetype,count from CT_DETECTIONS;" name="query" form="usrform" style="width:800px;height:100px;"></textarea>
<br>
<br><input type="submit" value="Submit Query" onclick="validate();">
</form>
<br>
<b>Query: </b><span id="query"></span>
<div id="valid" style="color:red;">
</div>
<div style="color:red">
<lable id="myP"> </lable>
</div>
</div>
</div>
<div id="visualization" style="width:800px; height: 450px;color:black;margin-left:22px;"></div>
</div>
</div>
<script type="text/javascript">
function validate() { return true; }
function submitUsrForm() {
// clear content between each query
document.getElementById("valid").innerHTML = "";
document.getElementById("visualization").innerHTML = "";
// get textarea content
var query = document.getElementById("tarea").value;
// Create AJAX request
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST", "custom.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("query=" + encodeURI(query));
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
// success
document.getElementById("visualization").innerHTML = xhr.responseText;
}
else {
// error
document.getElementById("valid").innerHTML = xhr.responseText;
}
}
}
return false;
}
</script>
To test execution timeout you can add after header :
ini_set('max_execution_time',1 );
sleep(3);

How to populate a response in the same div, which was populated as ajax

I have a html page
say main.php, which populates "upload.php" in div using ajax.
Now in this upload.php, I upload an image, and I want to somehow, make this div in main.php to show me the response of image load success or not.
my code is shown below:
The main.php
<script type="text/javascript">
function showHint()
{
var str = document.form1.filenumber.value;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
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","upload.php?filenumber="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="form1" >
<tr>
<td>File Number </td><td><input type="text" id="11" name="filenumber" /></td>
</form>
<td colspan="2"><input type="submit" onclick='showHint()'></td>
</tr>
</table>
<div id="txtHint"></div>
And the upload.php
<?php
$filenumber = clean($_GET['filenumber']);
if($filenumber != '') {
$qry = "SELECT * FROM profile WHERE filenum='$filenumber'";
$result = mysql_query($qry)
or die(mysql_error());
$row = mysql_fetch_array( $result );
if($result) {
if(mysql_num_rows($result) == 0) {
$errmsg = '<div style="width:300px; height:100px;color:red;margin:0px auto;position:relative;top: 30%">No such record found. Redirecting back to the status page. </p>';
$errflag = true;
}
else
{
?>
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
<?php
}
//#mysql_free_result($result);
}
else {
die("Query111 failed");
}
}
?>
And the upload.php calls for uploader.php, whose response I want to show in the same div
<?php
$target = "images/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
You suggestion are most welcome and your help is appreciated.
Thanks
Zee
As GolezTrol mentioned, you should consider using JQuery, it makes working with AJAX a lot easier.
To answer your question, you could use a JSON encoded response to be able to seperate information about the result of the uploading process and the real result you want to fill your div with.

Categories

Resources