How to display MediumBLOB from MySQL database using Javascript - javascript

So I am trying to display the information that I have retrieved from a database and I'm using Javascript to pass these info to their corresponding tags using the IDs. I have no problem with outputting the text, but I am having a hard time to output the images in the database which is a MediumBLOB.
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var buffer = new Buffer(userid.images);
var bufferBase64 = buffer.toString('base64');
$('#img').attr("src", "data:image/jpeg;base64," + bufferBase)
});
$('#viewModal').modal("show");
}
As for the update.php, here is the condition that receives the Post method.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'phpfinals');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ".$conn->connect_error);
}
//Sending details to be viewed
if(isset($_POST['sendview']))
{
$user_id = $_POST['sendview'];
$stmnt = mysqli_query($conn,"SELECT `username`, `password`, `firstname`, `middlename`, `lastname` , `gender`, `yearlevel`, `position`, `accesslevel`, `images` FROM phpfinals.records WHERE `username` = $user_id");
$result=array();
while($row = mysqli_fetch_assoc($stmnt))
{
$result = $row;
}
echo json_encode($result);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid or data not found";
}
?>

try creating an URL object
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var objectURL = URL.createObjectURL(userid.images);
$('#img').attr("src", objectURL)
});
$('#viewModal').modal("show");
}
and as a suggestion not related to your question instead of echo should be better use return for send the result
return json_encode($result);

Related

Populating a HTML table using JQUERY, PHP and AJAX

I am trying to populate a HTML table using JQUERY, AJAX and PHP code. When I run my code, my table is displayed but it is filled with 'undefined'.
I have three pieces of code. Here is my HTML and jQuery:
var integer = $("#transfers_in").attr("name");
alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {
dataType: 'json',
myData: integer
}, // data to submit
success: function(response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var name = response[i].name;
var amount = response[i].amount;
var tr_str = "<tr>" +
"<td align='center'>" + (i + 1) + "</td>" +
"<td align='center'>" + name + "</td>" +
"<td align='center'>" + amount + "</td>" +
"</tr>";
$("#money_in").append(tr_str);
}
}
});
<table id="money_in">
<tr>
<th>Name</th>
<th>Amount(Million £)</th>
</tr>
</table>
and here is my PHP Code:
<?php
if (isset($_POST['myData'])) {
$integer = $_POST['myData'];
if ($integer === "1"){
include 'db_connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$return_arr = array();
$query = "SELECT * FROM `money_in_19_20`";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result)){
$name = $row['Name'];
$amount = $row['Amount'];
$return_arr[] = array("Name" => $name,
"Amount" => $Amount);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
}
The Json data is being received in the format of
{"Name":"Hazard","Amount":"103000000"}
You are returning object as Name,Amount and checking as name,amount
var name = response[i].name;
var amount = response[i].amount;
it should be
var name = response[i].Name;
var amount = response[i].Amount;

Web API Controller POST & PUT & DELETE not working correctly

I keep getting results as false when running my POST & PUT & DELETE methods.
When I used POSTMAN I get 200 OK but my response returns as false?
Here's what I get when i use POST:
https://i.stack.imgur.com/fytB1.png
Here's what I get when i use UPDATE:
https://i.stack.imgur.com/y3vdv.png
Here's what I get when i use DELETE:
https://i.stack.imgur.com/hSNjy.png
Here is my controller code:
[HttpPost("AddNewOwner")]
public Boolean AddNewOwner(Owner theOwner)
{
DBConnect objDB = new DBConnect();
string strSQL = "INSERT INTO HomeOwnership_T (HomeOwnerID, FirstName, LastName, Address, City, State, ZipCode, TelNo, Email, BlockNo, LotNo, SaleDate, SalePrice, IsSold) " +
"VALUES ('" + theOwner.HomeOwnerID + "', '" + theOwner.FirstName + "', '" +
theOwner.LastName + "', '" + theOwner.Address + "', '" + theOwner.City +
"', '" + theOwner.State + "', '" + theOwner.ZipCode + "', '" + theOwner.TelNo + "', '"
+ theOwner.Email + "', '" + theOwner.BlockNo + "', '" + theOwner.LotNo + "', '"
+ theOwner.SaleDate + "', '" + theOwner.SalePrice + "', '" + theOwner.IsSold + "')";
//Execute the INSERT statement in the database
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
string command = "SELECT TOP 1 HomeOwnerID FROM HomeOwnership_T ORDER BY DESC";
DataSet ds = objDB.GetDataSet(command);
Tax taxInfo;
foreach (DataRow record in ds.Tables[0].Rows)
{
taxInfo = new Tax();
taxInfo.HomeOwnerID = int.Parse(record["HomeOwnerID"].ToString());
string strSQL2 = "INSERT INTO TaxInfo_T (AccessedVal, LandVal, AdditionalVal, TaxRate, TaxPerYear, RealEstateTax, HomeOwnerID)"
+ "VALUES (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '" + taxInfo.HomeOwnerID + "')";
objDB.DoUpdate(strSQL2);
}
return true;
}
else
{
return false;
}
}
[HttpPut]
public Boolean Update(Owner theOwner)
{
DBConnect objDB = new DBConnect();
HomeTax owner = new HomeTax();
string strSQL = "UPDATE HomeOwnership_T SET HomeOwnerID = " + theOwner.HomeOwnerID +
", FirstName = '" + theOwner.FirstName + "', LastName: '" + theOwner.LastName +
"', Address = '" + theOwner.Address + "', City = '" + theOwner.City +
"', City = '" + theOwner.City + "', State = '" + theOwner.State +
"', ZipCode = '" + theOwner.ZipCode + "', TelNo = '" + theOwner.TelNo +
"', Email = '" + theOwner.Email + "', BlockNo = " + theOwner.BlockNo +
", LotNo = " + theOwner.LotNo + "', SaleDate = '" + theOwner.SaleDate +
"', SalePrice = " + theOwner.SalePrice + ", IsSold = '" + theOwner.IsSold +
" WHERE HomeOwnerID = " + theOwner.HomeOwnerID;
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
return true;
}
else
{
return false;
}
}
[HttpDelete("{id}")]
public Boolean Delete(int id)
{
DBConnect objDB = new DBConnect();
string strSQL = "DELETE * FROM HomeOwnership_T INNER JOIN TaxInfo_T " +
"ON HomeOwnership_T.HomeOwnerID = TaxInfo_T.HomeOwnerID WHERE HomeOwnerID = " + id;
int result = objDB.DoUpdate(strSQL);
if(result > 0)
{
return true;
}
else
{
return false;
}
}
Here are my ajax calls:
$(document).on("click", "#btnAddHomeOwner", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/AddNewOwner";
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("btnAddHomeOwner selected");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
// Make an AJAX request to get a home and store the response in the appropriate div.
$.ajax({
type: "POST",
url: strURL,
contentType: "application/json", // set the data type sent to the Web Service.
dataType: "json", // set the data type expected from the Web Service.
data: strInput, // send an empty JSON object (no input required).
success: function (data) { // set callback function used to update the page/
console.log(data);
var result = data;
if (result == true)
$("#msg").text("The record was successfully added to the database.");
else
$("#msg").text("The record was not added to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnStoreHomeOwner click event
$(document).on("click", "#btnDelete", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/";
var param = $("#txtHomeOwnerID").val();
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Delete button selected.");
$.ajax({
type: "DELETE",
url: strURL + param,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{5}",
success: function (data) {
console.log(data);
var result = data;
if (result == true) {
$("#msg").text("The record with HomeOwnerID: " + param + " was deleted.");
alert("Deleted!");
}
else {
$("#msg").text("The record with HomeOwnerID: " + param + " was not deleted.");
alert("Not Deleted");
}
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnDelete click event
$(document).on("click", "#btnUpdateAll", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/Update";
// Clear the divs contents.
//$("#display").html("");
//$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Update home owner button selected.");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
//Make an AJAX request to get a home owner and display the response in the appropriate div
$.ajax({
type: "PUT",
url: strURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: strInput,
success: function (data) {
console.log(data);
var owner = data;
$("#display").html("<hr><p>".concat("HomeOwnerID: ", owner.HomeOwnerID,
"<br>FirstName: ", owner.FirstName, "<br>LastName: ", owner.LastName,
"<br>Address: ", owner.Address, "<br>City: ", owner.City,
"<br>State: ", owner.State, "<br>ZipCode: ", owner.ZipCode,
"<br>Telephone Number: ", owner.TelNo, "<br>Email: ", owner.Email,
"<br>Block Number: ", owner.BlockNo, "<br>Lot Number: ", owner.LotNo,
"<br>Date of Sale: ", owner.SaleDate, "<br>Sale Price: $", owner.SalePrice,
"<br>Sold Status: ", owner.IsSold, "<br>Accessed Value: $", owner.AccessedVal,
"<br>Land Value: $", owner.LandVal, "<br>Additional Value: $", owner.AdditionalVal,
"<br>Tax Rate: $", owner.TaxRate, "<br>Tax Per Year: $", owner.TaxPerYear,
"<br>Real Estate Tax: $", owner.RealEstateTax, "</p >"));
if (owner == true)
$("#updateResult").text("The record was successfully updated to the database.");
else
$("#updateResult").text("The record was not updated to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); //end of btnUpdate
check your sql string when you set the homeownerid is it suppose to be "SET hoID = '" + theOwner.HomeOwnerID + "', ownerName = '" + theOwner.ownerName + "'....etc

how can remove last comma from json using javascript forloop

$('#save').click(function() {
var loopvalue = "<?php echo $count; ?>"
var datajson = '[';
//alert(loopvalue + "length of array")
for (i = 1; i < loopvalue; i++) {
var fetchid = '.A' + i;
var fetchid_code = '.C' + i;
datajson = datajson + "{" + "maincode :" + $('#company').val() + ",acode : " + $(fetchid_code).text() +
" , Amount :" + $(fetchid).val() + ", periodfrom :" + $('#dFrom').val() +
", periodto : " + $('#dTo').val() + ", danounc : " + $('#dano').val() +
", period : " + $('#period').val() + ", fyear : " + $('#fyear').val() +
", frequency : " + $('#freq').val() + ", stype : " + $('#stype').val() +
", sseq : " + $('#sseq').val() + " }, "
}
datajson = datajson + ']'
//console.log(datajson);
$.ajax({
type: 'POST',
url: 'jsondecode.php',
data: {
datajson: JSON.stringify(datajson)
},
//data:postArray,
dataType: "json",
success: function(data) {
console.log("success:", data);
},
failure: function(errMsg) {
console.error("error:", errMsg);
}
});
});
first i remove last comma in json object and second when i am calling ajax page but it is displaying NULL value in jsonencode.php page how can I solve this problem any can suggest me this is my server site script now
<?php
header('Content-Type: application/json');
$data = json_decode($_POST["datajson"]);
// will echo the JSON.stringified - string:
echo $_POST["datajson"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach ($data as $Object) {
echo "maincode: " . $Object->maincode . ", Acode: " . $Object->acode . "<br/>";
}
?>
Or maybe you should use actual object instead of string-concatenation
Try this
var datajson = [];
for (i = 1; i < loopvalue ; i++)
{
var fetchid = '.A' + i;
var fetchid_code = '.C' + i;
var obj = {
maincode : $('#company').val(),
acode : $(fetchid_code).text(),
Amount : $(fetchid).val(),
periodfrom : $('#dFrom').val(),
periodto : $('#dTo').val(),
danounc : $('#dano').val(),
period : $('#period').val(),
fyear : $('#fyear').val(),
frequency : $('#freq').val(),
stype : $('#stype').val(),
sseq : $('#sseq').val()
}
datajson.push( obj );
}
datajson = JSON.stringify( datajson ); //converting to string here
Before you append ] to datajson, substring that value to remove last ,. That is.
datajson = datajson.toString().subString(0, datajson.toString().length - 1);
Then Append ]
It is not needed to use JSON.stringify(datajson) in data attribute of $.ajax because you are sending the json string. not json object.
Hope this helps
Write the single elements of your look into an array and then join the elements.
See here: javascript join
But of course building JSON yourself is not necessary. Use JSON.stringify for that.

Confirm scan barcode result

I have a project with barcodescanner library for phonegap. i have success scan QR Code image with this. And i want to authenticate the code inside QR Code with my database. How to do it?
i have barcodescanner.js:
document.addEventListener("deviceready", init, false);
function init() {
}
function scan() {
log("scanning");
cordova.plugins.barcodeScanner.scan(scanSuccessCallback, scanErrorCallback);
}
function scanSuccessCallback(result) {
log(JSON.stringify(result));
konfirmasi();
/*
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
*/
}
function scanErrorCallback(error) {
alert("Scanning failed: " + JSON.stringify(error));
}
function encode() {
log("encoding");
if (device.platform == "Android") { //Not supported on iOS
var stringToEncode = "http://www.sap.com";
cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, stringToEncode, encodeSuccessCallback, encodeErrorCallback);
}
else {
log("Encoding is not supported on iOS. See https://github.com/wildabeast/BarcodeScanner/issues/106");
}
}
function encodeSuccessCallback(result) {
log(JSON.stringify(result));
}
function encodeErrorCallback(error) {
alert("Encoding failed: " + JSON.stringify(error));
}
function log(line) {
var results = document.getElementById("scan_results");
//results.innerHTML+= "<br>" + line;
}
And this is my authentition php:
<?php
header("access-control-allow-origin: *") ;
include "connect.php";
$kode_konfirmasi = $_POST['konfirmasi'];
$kurir = $_POST['kurir'];
$miss = 'miss';
$delivered = 'delivered';
$query_kode = "SELECT * FROM pengiriman WHERE kode_transaksi = '$kode_konfirmasi' AND status = 'Belum Terkirim'";
$res_kode_ok = mysqli_query($dbc, $query_kode);
$query_exp = "SELECT * FROM pengiriman WHERE kode_transaksi = '$kode_konfirmasi' AND status = 'Terkirim'";
$res_kode_expired = mysqli_query($dbc, $query_exp);
$query_ok = "SELECT pengiriman.kode_transaksi, pengiriman.status FROM pengiriman, kurir WHERE pengiriman.id_kurir = kurir.id_kurir AND kurir.username = '$kurir' AND pengiriman.kode_transaksi = '$kode_konfirmasi'";
$res_kurir = mysqli_query($dbc, $query_ok);
if(mysqli_num_rows($res_kode_ok)>0 && mysqli_num_rows($res_kurir)>0){
$res_upd = mysqli_query($dbc, $query_upd);
$output = array('status' => true);
echo json_encode($output);
$query_upd = "UPDATE pengiriman SET status = 'Terkirim' WHERE kode_transaksi = '$kode_konfirmasi'";
}elseif(mysqli_num_rows($res_kode_ok)>0 && mysqli_num_rows($res_kurir)==0){
$output = array('status' => $miss);
echo json_encode($output);
}elseif (mysqli_num_rows($res_kode_expired)>0){
$output = array('status' => $delivered);
echo json_encode($output);
}else{
$output = array('status' => false);
echo json_encode($output);
}
?>
I have a script for authenticate the code inside QR Code manually by insert it in form html like this
$(document).on('pageinit','#manual',function(){
$(document).on('click','#submit',function(){
if($('#kode').val().length>0){
var un = window.localStorage.getItem('uname');
var kode = $('#kode').val();
$.ajax({
url:'http://qrkonfirmasi.16mb.com/delivery/konfirmasi.php',
data:{ kurir : un,
konfirmasi : kode
},
type:'post',
async:'false',
dataType: 'json',
beforeSend:function(){
$.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
},
complete:function(){
$.mobile.loading('hide');
},
success:function(hasil){
console.log(hasil);
if(hasil.status==true){
alert('Berhasil! Konfirmasi kode ' + kode + ' berhasil.')
$.mobile.changePage("#konfirmasi");
console.log('Konfirmasi Berhasil');
}else if(hasil.status=='delivered') {
alert('Error! Kode '+ kode + ' telah dikonfirmasi.');
}else if(hasil.status=='miss'){
alert('Error! Data kurir tidak sesuai.');
}else{
alert('Gagal, Kode konfirmasi tidak sesuai.');
}
},
error:function(request,error){
alert('Koneksi error. Silahkan coba beberapa saat lagi!');
}
});
}else{
alert('Masukkan username dan password!');
}
return false;
});
});
So, how i can authenticate the code from scanning result immediately when scan success?

How do I call the PHP mail() function in my JS?

I have a dilema. I've created this order request page for a website I'm building, and here's how it works:
You check/uncheck core items, and based on it's state (active or unactive), it'll apply a true/false value to a boolean in the coresponding order.js. Likewise, it'll take desired unit count for other items, and your information, and apply them to variables.
It groups those variables into arrays and, right now, console.log() them.
Here's where the trouble comes...this is a snippet of the order.js file.
function compileInfo() {
console.log("compileInfo active");
var name = "Name: " + $("#name").val() + "\n";
var email = "Email: " + $("#email").val() + "\n";
var phone = "Phone: " + $("#phone").val() + "\n";
var weddingDate = "Wedding Date: " + $("#date").val() + "\n";
var comments = "Comments: " + $("#comments").val() + "\n";
var base = "Base Experience: " + $("#base").hasClass("active") + "\n";
var special = "Special Edition: " + $("#special").hasClass("active") + "\n";
var teaser = "Teaser Trailer: " + $("#teaser").hasClass("active") + "\n";
var raw = "Raw Footage: " + $("#raw").hasClass("active") + "\n";
var standard = "Standard Shipping: " + $("#standard").hasClass("active") + "\n";
var expedited = "Expedited Shipping: " + $("#expedited").hasClass("active") + "\n";
var dvd = "Standard DVD: " + a + "\n";
var br = "Standard Blu-Ray: " + b + "\n";
var dvdSe = "Special DVD: " + x + "\n";
var brSe = "Special Blu-Ray: " + y + "\n";
var info = new Array();
info[0] = name;
info[1] = email;
info[2] = phone;
info[3] = weddingDate;
info[4] = comments;
var services = new Array();
services[0] = base;
services[1] = special;
services[2] = teaser;
services[3] = raw;
var delivery = new Array();
delivery[0] = standard;
delivery[1] = expedited;
var extras = new Array();
extras[0] = dvd;
extras[1] = br;
extras[2] = dvdSe;
extras[3] = brSe;
var dataVar = info + "\n" + services + "\n" + delivery + "\n" + extras;
var dataVarJSON = JSON.stringify(dataVar);
console.log(dataVar);
$.ajax({
type: "POST",
url: "order.php",
data: {data : dataVarJSON},
success: function() {
console.log("SUCCESS");
}
});
}
function validate() {
var name = $("#name").val();
var email = $("#email").val();
var weddingDate = $("#date").val();
if (name === "" || email == "" || weddingDate == "") {
alert("You must complete all required fields to send this request.");
} else {
console.log("working");
compileInfo();
return true;
}
}
Here's my recieving PHP:
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$body = json_decode(stripslashes($_POST['data']));
$to = "thekevinhaube#gmail.com";
$subject = "Order Request";
function sendInfo() {
mail($to, $subject, $body);
}
?>
Now, I'm far from a PHP expert. This is my first encounter with it, in fact. How can I get it to send. It seems to POST just fine, but isn't sending to the email adress listed. Any and all help is appreciated! Again, this is my first time with PHP, so...
You need to give sendInfo some parameters:
function sendInfo($to, $subject, $body) {
...
}
And don't try mail() on your localhost, try it - if possible - online.

Categories