PHP to JAVA - Database JSON - javascript

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];
}

Related

How to prevent users to search null/space value because it keeps returning all values from database

When I search null or space values, all the results from database come to my html table.
I wanted to prevent users to search null values or space values.
I tried this post, but now helped me, How to prevent a database search from running on an empty string?
Here is the backend script-
<?php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=searchv3", "root", "");
$output = '';
$query = '';
$data = [];
if(isset($_POST["query"]))
{
$search = str_replace(",", "|", $_POST["query"]);
$query = "
SELECT * FROM number_list
WHERE IMSI REGEXP '".$search."'
OR Mobile_no REGEXP '".$search."'
OR Backup_date REGEXP '".$search."'
OR Sr REGEXP '".$search."'
";
}
else
{
$query = "
SELECT * FROM number_list order by Sr DESC LIMIT 50;
";
}
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
$connect = null;
?>
I will share front-end jav script as well-
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch_numberlist.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td>'+data[count].Sr+'</td>';
html += '<td>'+data[count].IMSI+'</td>';
html += '<td>'+data[count].Mobile_no+'</td>';
html += '<td>'+data[count].Backup_date+'</td>';
}
}
else
{
html = '<tr><td colspan="4">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#tags').val();
load_data(query);
});
})
</script>
...
$data = [];
// `??` operator returns value if isset needed post element, else use empty string
// trim - remove start and ending spaces from string.
// So it return empty string if user input only space
$post_query = trim($_POST["query"] ?? '');
if($post_query)
{
$search = str_replace(",", "|", $post_query);
...

$.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?

increment php variable used in javascript

I wanted to display a graph in javascript using data from php. My code is:
<?php $i = 20; ?>
while (data.length < totalPoints) {
array_js.push(<?php echo json_encode($array_php[++$i][1]);?>);
}
The problem is that even though $i is declared before the while loop, it gets back to 20 all the time, so the data pushed in array_js is always $array_php[21][1].
Edit: here is more code, (not same variable name...)
startConn(); //connect to database
$query = "SELECT * FROM Reading";
$data = getAllDatas($query);
?>
<script type="text/javascript">
$(function() {
var data = [], totalPoints = 300;
function getRandomData() {
<?php $i = 20; ?>
while (data.length < totalPoints) {
data.push(<?php echo json_encode($data[--$i][1]);?>);
//data.push(<?php echo ++$i;?>);
}
} // END getRandomData()
You have a misunderstanding on how server side and client side code work.
I think this may help you
$(function() {
var data = [], totalPoints = 3;
var i = <?php $i = 1;echo $i; ?>;
var j = parseInt(i);
var arr = <?php echo json_encode($data); ?>;
function getRandomData() {
while (data.length < totalPoints) {
data.push(arr[j][1]);
j++;
}
return data;
}
var data1 = getRandomData();
console.log(data1);
});
Try this one. You can pass the value of the php variable using echo while declaring another variable on the java script.
<?php $i = 20; ?>
var i = <?php echo $i;?>;
while (data.length < totalPoints) {
array_js.push(<?php echo json_encode($array_php[++i][1]);?>);
}

PHP Query Array to Javascript Google Maps Iterator

PHP Code
$sql = "SELECT location FROM data";
$result=$conn->query($sql);
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row["location"];
}
Javascript
function getPoints(){
return [
var coordinateArray = <?php echo json_encode($data); ?>;
for(i-0;i<coordinateArray.length; i++({
var sep = coordinateArrays.split(',');
new google.maps.LatLng(sep[0], sep[1]);
}
];
}
Sample data in table:
location = 12.121212,13.131313 -> No quotes
data = "Hello"
author="Me"
Currently it breaks declaring the Array variable in javascript.Something is breaking there. Any help is appreciated
seems you have a name mismatch coordinateArray / coordinateArrays and and index problem try
var coordinateArray = <?php echo json_encode($data); ?>;
for(i=0; i<coordinateArray.length; i++) {
var sep = coordinateArray[i].split(',');
new google.maps.LatLng(sep[0], sep[1]);
}
and also problem with parentesis i++( and assignment i-1 instead of i++) and i=1

How to assign key:value pairs from SQL to JavaScript Object using PHP?

I have the following data in an SQL database
cname, ccode, colour
Great Britain, GB, 1
Italy, IT, 1
France, FR, 1
Spain, ES, 1
How can I create a JavaScript object like below?
var countries = {"GB":1, "IT":1, "FR":1, "ES":1}
So far, I have the following code;
PHP
$query2 = "SELECT ccode,colour FROM country_data WHERE 1";
$result2 = mysql_query($query2);
if (!$result2) {
die('Invalid query: ' . mysql_error());
}
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[] = $r2;
}
JS
var colours = '<?php print json_encode($rows2); ?>';
Which returns:
[{"ccode":"GB","colour":"1"},{"ccode":"IT","colour":"1"},{"ccode":"FR","colour":"1"},{"ccode":"ES","colour":"1"}]
change this code
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[] = $r2;
}
to this one:
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[$r2['ccode']] = $r2['colour'];
}
change php code as told in others answers too and it should be like
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[$r2['ccode']] = $r2['colour'];
}
if it does not work then try this:
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2["'".$r2['ccode']."'"] = $r2['colour'];
}
if it also does not work then try this:
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[{$r2['ccode']}] = $r2['colour'];
}

Categories