Throwing Undefined plus the value in JavaScript to PHP - javascript

Hi I have a problem with this one. Instead of having a result of uniqueID = value I'm having a result like this uniqueID = undefinedvalue
JavaScript Code
function read(a){
var html;
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
html+="<a target='_blank' href='"+a+"'>"+a+"</a><br>";
html+=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID;
}
PHP Code
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $id;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.html');
}
}
This is the output in my URL. check this out to see the problem
Thank you in advance. :)

var uniqueID = document.getElementById("mapo").innerText;
console.log(uniqueID);
/*var uniqueID = document.getElementById("mapo").value;*/
<div id="mapo">123456789</div>
<!--<input id="mapo" type="hidden" value="123456789" />-->

I solved my own problem. This is the solution.
function read(a){
var html=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID;
}
I realized that the var=html dont have any value and when I concatenate it to my htmlEntities it resulted into an undefined index. So I remove it and place the htmlEntities straight to the var html. :)

Related

Edit data from table with javascript and php from ajax

I am a beginner in PHP and Javascript I used a live editable table and I am trying to edit them and then save them to mysql in another page I did like this, but I didn't know how to retrieve where to edit in mysql with the id could some one help please! Am i wrong in the request? it doesn't change in the database like it does in the table in the page. I sent the data like this:
function postedit()
{
var _type = $('#typeid').val();
var _pression = $('#pressionid').val();
var _code = $('input[name="code"]').val();
var _designiation = $('input[name="designiation"]').val();
var _diametre = $('input[name="diametre"]').val();
var _epaisseur = $('input[name="epaisseur"]').val();
var _prix = $('input[name="prix"]').val();
var _etat = $('input[name="etat"]').val();
$.post('update.php', {
posttype: _type,
postpression: _pression,
postcode: _code,
postdesigniation: _designiation,
postdiametre: _diametre,
postepaisseur: _epaisseur,
postprix:_prix,
postetat:_etat
},
function(data){
$('tbody').append(data);
});
}
var _trEdit = null;
$(document).on('click', '.btn-edit',function(){
_trEdit = $(this).closest('tr');
var _code = $(_trEdit).find('td:eq(0)').text();
var _designiation = $(_trEdit).find('td:eq(1)').text();
var _diametre = $(_trEdit).find('td:eq(2)').text();
var _epaisseur = $(_trEdit).find('td:eq(3)').text();
var _prix = $(_trEdit).find('td:eq(4)').text();
var _etat = $(_trEdit).find('td:eq(5)').text();
$('input[name="code"]').val(_code);
$('input[name="designiation"]').val(_designiation);
$('input[name="diametre"]').val(_diametre);
$('input[name="epaisseur"]').val(_epaisseur);
$('input[name="prix"]').val(_prix);
$('input[name="etat"]').val(_etat);
});
$('#btn-update').click(function(){
if(_trEdit){
var _code = $('input[name="code"]').val();
var _designiation = $('input[name="designiation"]').val();
var _diametre = $('input[name="diametre"]').val();
var _epaisseur = $('input[name="epaisseur"]').val();
var _prix = $('input[name="prix"]').val();
var _etat = $('input[name="etat"]').val();
$(_trEdit).find('td:eq(0)').text(_code);
$(_trEdit).find('td:eq(1)').text(_designiation);
$(_trEdit).find('td:eq(2)').text(_diametre);
$(_trEdit).find('td:eq(3)').text(_epaisseur);
$(_trEdit).find('td:eq(4)').text(_prix);
$(_trEdit).find('td:eq(5)').text(_etat);
alert("Ligne Modifier avec succée !");
_trEdit = null;
}
});
My sql request in a file update.php like this I thought that if I get the id from the database and search from it, it seems stupid but I am desperate:
$type_utilisation = $_POST['posttype'];
$pression_tube = $_POST['postpression'];
$code_tube = $_POST['postcode'];
$designiation_tube = $_POST['postdesigniation'];
$diametre_tube = $_POST['postdiametre'];
$epaisseur_tube = $_POST['postepaisseur'];
$prix_tube = $_POST['postprix'];
$etat_tube = $_POST['postetat'];
$id_req = ("select id from $pression_tube where typepehd='".$type_utilisation."' && code='".$code_tube."'");
$id_tube=$id_req;
echo"$id_tube";
if(isset($pression_tube)){
if($pression_tube=="pn4"){
if($type_utilisation=="pehdtelecom" && $pression_tube=="pn4" ){
echo "verifier le type du Tube S.v.p";
} else {
$sql="UPDATE pn4 SET typepehd='".$type_utilisation."',code='".$code_tube."',designiation='".$designiation_tube."',diametre='".$diametre_tube."',epaisseur='".$epaisseur_tube."',prix='".$prix_tube."',etat='".$etat_tube."' where id='".$id_tube."'";
$result = mysqli_query($link, $sql);
if($result){
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
}
thank you, i did solve it by using the id because its unique
$id_tube = $_POST['postid'];
by adding an input to it in type hidden
and make the column invisible by
style="display;none";

$.post to PHP file - callback not being hit till containing loop finished?

I'm making a stock table, where the user can input a number of stock to issue out, and this function is to verify, for each member of the table, whether or not the quantity of stock in the database is sufficient to make the issue.
When I breakpoint through the code on Chrome, it seems to never hit the inside code of the $.post until after its finished looping through the table. And by then the data that is supposed to be passed to AddIssue just becomes 1 and 10 and nothing else.
It's starting to drive me mad, so I'd appreciate a pointer on what I'm doing wrong here
var issueArray =[];
function VerifyIssue()
{
var numRows = document.getElementById("searchTable").rows.length - 2;
var running = true;
var str1 = "issue_";
while(running == true)
{
if (numRows < 0 && running == true)
{
running = false;
//insert code for success
break;
}
else if (running == false)
{
break;
}
var str2 = numRows;
var comb = str1.concat(str2);
var issue_element = document.getElementById(comb);
var q = issue_element.value;
var i = issue_element.name;
var idd = i.replace("issue_", "");
var trimId = idd.trim();
$.post
(
'includes/issueCheck.php',
{
id: trimId,
issueQuantity: q
},
function(result)
{
alert(result);
if (result < 0)
{
alert("One of more quantities inputted are greater than held in stock");
running = false;
}
if (result > 0)
{
addIssue(trimId, q);
}
}
);
numRows = numRows - 1;
}
alert(issueArray);
}
function addIssue(issueID, quant)
{
var item = {};
item.label = issueID;
item.value = quant;
issueArray.push(item);
}
This is the PHP that is called by the $.post
<?php
$server = 'SQL2008';
$connectionInfo = array( "Database"=>"rde_470585");
$conn = sqlsrv_connect($server,$connectionInfo);
$false = -1;
$true = 1;
$id = $_POST['id'];
$quantity = $_POST['issueQuantity'];
$query = "Select Quantity FROM Stock WHERE StockID = ?";
$param = array($id);
$res = sqlsrv_query($conn, $query, $param);
$row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC);
$dbQuantity = $row['Quantity'];
if ($dbQuantity < $quantity)
{
echo $false;
}
else if($dbQuantity >= $quantity)
{
echo $true;
}
Do you realise that your function(result){ ... } will only be called when the server response for your POST request is received? You have to build the code to take that delay into account.
I'm still working on this, reading up on Promises based on what #jojo said, but not sure if it's going to work for me.
How else can I make the javascript wait for a server response before resuming?

How to pass the data database to view using script and php?

I have getpunch method in script and PHP also what i want is pass the hours:minuts between in_time and current time
This is my script :
AttendanceAdapter.method('getPunch', function(successCallBack) {
var that = this;
var object = {};
object['date'] = this.getClientDate(new Date()).toISOString().slice(0, 19).replace('T', ' ');
object['offset'] = this.getClientGMTOffset();
var reqJson = JSON.stringify(object);
var callBackData = [];
callBackData['callBackData'] = [];
callBackData['callBackSuccess'] = successCallBack;
callBackData['callBackFail'] = 'getPunchFailCallBack';
this.customAction('getPunch','modules=attendance',reqJson,callBackData);
});
This is my PHP :
public function getPunch($req){
$date = $req->date;
$arr = explode(" ",$date);
$date = $arr[0];
$employee = $this->baseService->getElement('Employee',$this->getCurrentEmployeeId(),null,true);
//Find any open punch
$attendance = new Attendance();
$attendance->Load("employee = ? and DATE_FORMAT( in_time, '%Y-%m-%d' ) = ? and (out_time is NULL or out_time = '0000-00-00 00:00:00')",array($employee->id,$date));
if($attendance->employee == $employee->id){
//found an open punch
return new IceResponse(IceResponse::SUCCESS,$attendance);
}else{
return new IceResponse(IceResponse::SUCCESS,null);
}}
using this when user try to punch_out in that form showing in_time i want show in that form how many hours they worked when they try to punch_out

PHP to JAVA - Database JSON

There are plenty of examples of using database records to disable certain dates (unavailable) using JSON and AJAX however for some reason, these are done in PHP. Is there reason why it isn't done in JAVA and how can I replace the PHP file with Java for the exact same result?
checkDates.php
<? php
$sql = "SELECT start from gbh_rooster_afwijkend WHERE dlnmrID = '".$_GET['dld'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$checkDates = array();
while ($row = mysql_fetch_assoc($res)) {
$checkDate['start'] = $row['start'];
$checkDates[] = $checkDate;
}
echo json_encode($checkDates);
?>
Javascript
$.getJSON('script/php/afwijkendrooster/checkDates.php?dld='+ id, function(json){dates=json;});
function checkAvailability(mydate){
var myBadDates = dates;
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd-mm-yy', mydate);
// start loop
for(var x in myBadDates)
{
$myBadDates = new Array( myBadDates[x]['start']);
for(var i = 0; i < $myBadDates.length; i++)
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
//end loop
return [$return,$returnclass];
}

Multiple image array

I'm not too sure how to explain this, basically I want to make a array of images (hundreds of images) and then I would like a random 10 to be displayed on my website without any text. I'm not sure if it's possible to do this any other way.
function packOpen()
{
var card = new Array();
card[0] = "Messi";
card[1] = "Ribery";
card[2] = "Ronaldo";
card[3] = "Neymar";
card[4] = "Robben";
card[5] = "Casillas";
}
I have tried making a array, but it doesn't display a result.
If the number of images really is in the hundreds you could use a PHP script to generate the array. It will scan a directory and find the images then generate a JavaScript array.
Save this as images.php
<?php
header("Content-type:text/javascript");
//The directory of your images
$dir = "img";
echo "var images = [";
$arr = preg_grep("/[A-Za-z0-9].(jpg|gif|png|bmp|jpeg|svg)/",scandir($dir));
$index = 0;
foreach($arr as $value) {
$index++;
if($index < count($arr)) {
echo "\"" . $dir . "/" . $value . "\", ";
}
else {
echo "\"" . $dir . "/" . $value . "\"";
}
}
echo "];";
?>
Then if you include it in the HTML file you can use the array variable images to access the array.
The in the JavaScript file (script.js):
window.onload = function() {
var div = document.getElementById("images");
for(var i = 0; i < images.length; ++i) {
var img = document.createElement("img");
img.src = images[Math.floor(Math.rand() * 10)];
div.appendChild(img);
}
};
Finally the HTML file:
<script src="images.php"></script>
<script src="script.js"></script>
<div id="images"></div>
If you simply want a function to return the adress of an img you could try:
function packOpen()
{
var card = new Array();
card[0] = "Messi";
card[1] = "Ribery";
card[2] = "Ronaldo";
card[3] = "Neymar";
card[4] = "Robben";
card[5] = "Casillas";
return card[Math.floor(Math.rand() * card.length)];
}
Your array is certanly looking fine to me. One approach to your problem could be to use the javascript functions "slice", "splice" and "sort".
function packOpen(numResults)
{
var card = new Array();
card[0] = "Messi";
card[1] = "Ribery";
card[2] = "Ronaldo";
card[3] = "Neymar";
card[4] = "Robben";
card[5] = "Casillas";
card.slice(0);
card.sort( function() {
return .5-Math.random();
});
return card.splice(0,numResults);
}
var randomItems = packOpen(10);

Categories