use dynamic php variable in javascript - javascript

i have a image database and a search form , so i want to show the images in next page and i have to use javascript to show (openlayer library)
i wrote this code`
<?php mysql_connect('localhost','root',"");
mysql_select_db('geo-image');
$am=0 ;
$sql="SELECT * FROM images WHERE satellite='".$_POST["satellite"]."'";
$result=mysql_query($sql)or die(mysql_error());
$count = mysql_num_rows($result);
for ($i=1; $i<=$count; $i++)
{
$rows = mysql_fetch_array($result);
${'a'.$i}=$rows['xpos'];
${'b'.$i}=$rows['ypos'];
${'c'.$i}=$rows['width'];
${'d'.$i}=$rows['height'];
${'e'.$i}=$rows['xoffset'];
${'f'.$i}=$rows['yoffset'];
${'g'.$i}=$rows['rotation'];
${'h'.$i}=$rows['resolution'];
${'i'.$i}=$rows['name'];
${'j'.$i}=$rows['url'];
}
?>
and the javascript code:
var a1="<?php echo $a1?>";
var b1="<?php echo $b1?>";
var c1="<?php echo $c1?>";
var d1="<?php echo $d1?>";
var e1="<?php echo $e1?>";
var f1="<?php echo $f1?>";
var g1="<?php echo $g1?>";
var h1="<?php echo $h1?>";
var a2="<?php echo $a2?>";
var b2="<?php echo $b2?>";
var c2="<?php echo $c2?>";
var d2="<?php echo $d2?>";
var e2="<?php echo $e2?>";
var f2="<?php echo $f2?>";
var g2="<?php echo $g2?>";
var h2="<?php echo $h2?>";
var l1=340;
var l2=346;
if("<?php echo $count?>"==1){
anArray[anArray.length] = [ a1,b1, c1, d1, e1, f1, g1, h1,l1,"image/<?php echo $j1?>.jpg"];
} else if("<?php echo $count?>"==2){
anArray[anArray.length] = [ a1,b1, c1, d1, e1, f1, g1, h1,l1,"image/<?php echo $j1?>.jpg"];
anArray[anArray.length] = [ a2,b2, c2, d2, e2, f2, g2, h2,l2,"image/<?php echo $j2?>.jpg"];
} else if("<?php echo $count?>"==3){
anArray[anArray.length] = [ a1,b1, c1, d1, e1, f1, g1, h1,l1,"image/<?php echo $j1?>.jpg"];
anArray[anArray.length] = [ a2,b2, c2, d2, e2, f2, g2, h2,l2,"image/<?php echo $j2?>.jpg"];
anArray[anArray.length] = [ a3,b3, c3, d3, e3, f3, g3, h3,l3,"image/<?php echo $j3?>.jpg"];
}
when in the database search i have two result this code work properly but when the result is more than two the code doesnt work, i know the problem is about my variable in javascript but i have no idea to fix it , can any one help me to solve it??

PHP :
<?php mysql_connect('localhost','root',"");
mysql_select_db('geo-image');
$ARR_DATA = array();
$sql="SELECT * FROM images WHERE satellite='".$_POST["satellite"]."'";
$result=mysql_query($sql)or die(mysql_error());
while($rows = mysql_fetch_array($result)
{
$arr_temp['a'] = $rows['xpos'];
$arr_temp['b'] = $rows['ypos'];
$arr_temp['c'] = $rows['width'];
$arr_temp['d'] = $rows['height'];
$arr_temp['e'] = $rows['xoffset'];
$arr_temp['f'] = $rows['yoffset'];
$arr_temp['g'] = $rows['rotation'];
$arr_temp['h'] = $rows['resolution'];
$arr_temp['i'] = $rows['name'];
$arr_temp['j'] = $rows['url'];
$ARR_DATA[] = $arr_temp;
}
$count = count($ARR_DATA);
?>
JS :
<script>
<?php
foreach($ARR_DATA as $key=>$arr_temp)
{
?>
var a = "<?php echo $arr_temp['a'];?>";
var b = "<?php echo $arr_temp['b'];?>";
var c = "<?php echo $arr_temp['c'];?>";
var d = "<?php echo $arr_temp['d'];?>";
var e = "<?php echo $arr_temp['e'];?>";
var f = "<?php echo $arr_temp['f'];?>";
var g = "<?php echo $arr_temp['g'];?>";
var h = "<?php echo $arr_temp['h'];?>";
var i = "<?php echo $arr_temp['i'];?>";
var j = "<?php echo $arr_temp['j'];?>";
var img = "image/"+j+".jpg";
anArray[<?php echo $key;?>] = [ a, b, c, d, e, f, g, h, i, j];
<?php
}
?>
</script>

try
in php code
<?php mysql_connect('localhost','root',"");
mysql_select_db('geo-image');
$am=0 ;
$sql="SELECT * FROM images WHERE satellite='".$_POST["satellite"]."'";
$result=mysql_query($sql)or die(mysql_error());
$count = mysql_num_rows($result);
$images = array();
for ($i=1; $i<=$count; $i++)
{
$rows = mysql_fetch_array($result);
$images[] = $rows;
}
?>
in js code
<?php
foreach ($images as $image){
?>
anArray[anArray.length] = [ "<?php echo $image['xpos'];?>","<?php echo $image['ypos'];?>", "<?php echo $image['width'];?>", "<?php echo $image['height'];?>", "<?php echo $image['xoffset'];?>", "<?php echo $image['yoffset'];?>", "<?php echo $image['rotation'];?>", "<?php echo $image['resolution'];?>","<?php echo $image['name'];?>","image/<?php echo $image['url']?>.jpg"];
<?php
}
?>

the safiest way to communicate between php and js is to use json in my opinion. additionnaly, I would suggest you to use pdo or mysqli instead of mysql for the communication with your database.

Related

Javascript code stops working after page Load More .load()

When data is fetched on auto Load More, another JavaScript (which is given below) stops working.
Even when it shows the 1st page default it works there but after scrolling down it does not work.
Updated with more explaination with index and getdata file. I'm fetching data like mentioned in the below codes.
index.php
<div>
<?php include('getdata.php'); ?>
</div>
<script>
$(document).ready(function(){
var is_ajaxed = false;
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()+1},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#faq-result").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height()-900) && is_ajaxed == false){
if($(".pagenum").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum").val()) + 1;
var pname = "<?php echo $pgianame; ?>";
var sname = "<?php echo $stianame; ?>";
getresult('sellers_forum_page_posts_getresult.php?page='+pagenum+'&pname='+pname+'&sname='+sname);
is_ajaxed = true
}
}
});
});
</script>
getdata.php
<?php
include ('db.php');
$perPage = 10;
$sql = "select * from posts where status = 1";
$faq3x = $dba3->query($sql);
$allrowscount = mysqli_num_rows($faq3x);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start <= 0) $start = 0;
$sqlsC = "select * from posts where status = 1 ";
$query = $sql . " limit " . $start . "," . $perPage;
$faq3xsC = $dba3->query($query);
echo '<input type="text" class="pagenum" value="'.$page.'" />';
echo '<input type="text" class="total-page" value="'.$pages.'" />';
while ($faqC = $faq3xsC->fetch_assoc()) {
$id = $faqC['id'];
$ext = ".doc";
$name = $id.$ext;
$filepath = "blog/posts/";
$filename = $filepath.$name;
if(file_exists($filename)) {
if(($fhP = fopen($filename, 'r')) !== false ) {
$headersxP = fread($fhP, 999000);
$commentsPP = nl2br($headersxP);
$countxP = 0;
$fhxP = fopen($filename, 'r');
while(!feof($fhxP)){
$frxP = fread($fhxP, 999999);
$countxP += strlen($frxP);
}
fclose($fhxP);
?>
<?php echo substr($commentsPP, 0, 511); ?>
<span id="dots_<?php echo $idPost; ?>">...</span>
<span id="more_<?php echo $idPost; ?>" style="">
<?php echo substr($commentsPP, 512, 999999); ?>
</span>
<a onclick="myFunctionx_<?php echo $id; ?>()"
id="myBtn_<?php echo $id; ?>"> See More <i class="fa fa-long-arrow-right"></i></a>
<script>
function myFunctionx_<?php echo $id; ?>() {
var dots_<?php echo $id; ?> = document.getElementById("dots_<?php echo $id; ?>");
var moreText_<?php echo $id; ?> = document.getElementById("more_<?php echo $id; ?>");
var btnText_<?php echo $id; ?> = document.getElementById("myBtn_<?php echo $id; ?>");
if (dots_<?php echo $id; ?>.style.display === "none") {
dots_<?php echo $id; ?>.style.display = "inline";
btnText_<?php echo $id; ?>.innerHTML = " See more <i class='fa fa-long-arrow-right'></i>";
moreText_<?php echo $id; ?>.style.display = "none";
} else {
dots_<?php echo $id; ?>.style.display = "none";
btnText_<?php echo $id; ?>.innerHTML = " <i class='fa fa-long-arrow-left'></i> See less";
moreText_<?php echo $id; ?>.style.display = "inline";
}
}
</script>
<?php } ?>

disable some custom dates range in a fullcalendar?

I want to block the technician holidays in the calendar, dates are scheduled in the SQL server.
So far I have managed to block the days before the current day.
I wanted to do the same but with the dates of the holidays.
dayRender: function (date, cell) {
if (moment().diff(date, 'days') > 0) {
cell.css("background-color", "#F5F5F5");
$(cell).addClass('disabled');
}
},
I appreciate all the help, thanks in advance.
EDIT:
This is what I want to do:
https://codepen.io/anon/pen/xyxeJm
EDIT 2
my events code:
<script>
var url = window.location.href;
var recortar = url.indexOf("agenda=");
var tec = url.substr(recortar + 7);
var table = $('#example').DataTable({
"iDisplayLength": 5,
"bLengthChange": false,
pagingType: "simple",
"order": [[ 1, 'asc' ]],
});
$('#example tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
<?php
if(isset($_GET['agenda'])){
$tec = selecttec($_GET['agenda']);
// curativas
$sql = "SELECT * FROM npedido WHERE tec1= '$tec' OR tec2= '$tec' OR responsable = '$tec' ";
$stmt2 = sqlsrv_query( $conn, $sql);
// agendamentos
$sql_agenda = "SELECT * FROM nagenda WHERE tec1= '$tec' OR tec2= '$tec'";
$stmt_agenda = sqlsrv_query( $conn, $sql_agenda);
?>
var name = "<?php echo utf8_encode($tec); ?>";
table.search(name).draw();
$("#tec_name").val(name);
$( "#example tr").each(function() {
if(this.id == tec){
$(this).addClass('selected');
}
});
var tec = "<?php echo $tec; ?>";
var events = function () {
return [
// curativas agenda
<?php while($row = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_NUMERIC)) {
if(strlen(str_replace(' ', '', $row[7])) < 15){ $start=date('h:i Y-m-d',strtotime(str_replace("18", "2018", substr($row[7], -16, 8)))) ;}else{ $start= date('Y-m-d H:i',strtotime($row[7])) ; }
if(strlen(str_replace(' ', '', $row[7])) < 15){ $end = date('h:i Y-m-d',strtotime(str_replace("18", "2018", substr($row[7], -16, 8)))) ;}else{ $end = date('Y-m-d H:i ',strtotime($row[7])) ; }
$start = substr($start,0,10)."T". substr($start,10);
$start = str_replace(" ","",$start);
$end = substr($end,0,10)."T". substr($end,10);
$end = str_replace(" ","",$end);
?> {
id: '<?php echo $row[0] ?>',
title: '<?php echo "Curativa - ".utf8_encode($row[8]).""; ?>',
start: '<?php echo $start; ?>',
end: '<?php echo $end; ?>',
color: '#0FB1DA',
},
<?php }?>
// agendamento
<?php while($row = sqlsrv_fetch_array($stmt_agenda, SQLSRV_FETCH_NUMERIC)) {?>
{
id: '<?php echo $row[0]; ?>',
title: '<?php echo "Agendamento - ".utf8_encode($row[4]).""; ?>',
start: '<?php echo $row[6]; ?>',
end: '<?php echo $row[7]; ?>',
dow: [1,4],
color: '<?php echo $row[10];?>',
},
<?php }?>
];
}
table.search("").draw();
<?php }else{?>
$('#example tbody tr:eq(0)').click();
<?php }sqlsrv_close($conn);?>
</script>
i just added the code and just set the background color, but i whant to disable the click funcion on those days...how i do that?
Code added:
// ferias
<?php while($row = sqlsrv_fetch_array($stmt_ferias, SQLSRV_FETCH_NUMERIC)) {?>
{
id: '<?php echo $row[0]; ?>',
title: '<?php echo "Férias - ".utf8_encode($row[2]).""; ?>',
start: '<?php echo $row[3]; ?>',
end: '<?php echo $row[4]; ?>',
dow: [1,4],
rendering: 'background',
color: '#ff9f89'
},
<?php }?>

$_POST is empty as a result of AJAX

The problem: var_dump($_POST['day']) is NULL, var_dump($b); is string(0) ""
As a result - return empty json
HTML Form with checkboxes
<form id="filter">
<input type="checkbox" name="day[]" value="1">
<input type="checkbox" name="day[]" value="2">
<input type="checkbox" name="day[]" value="3">
</form>
JS
var a = 0;
var b = 5;
var c = $( "#filter" ).serialize();
var Data = 'a=' + a + '&' + 'b=' + b + '&' + c;
var process = false;
$.ajax({
url: 'script.php',
method: 'POST',
data: Data,
beforeSend: function() {
process = true;
}
});
script.php var_dump($_POST['day']) is NULL
$a = $_POST['a'];
$b = $_POST['b'];
$c = implode(',', $_POST['day']); // Warning: implode(): Invalid arguments passed
$in = str_repeat('?,', count($c) - 1) . '?'; // Warning: Second argument has to be greater than or equal to 0
$sql = "SELECT * FROM table WHERE day IN ($in) ASC LIMIT :a, :b";
$stmt = $pdo->prepare($sql);
$stmt->execute($с, [$a, $b]);
$data = $stmt->fetchAll();
echo json_encode($data);
$result = [];
$a = (int) $_POST['a'];
$b = (int) $_POST['b'];
$c = array_filter( (array) $_POST['day'] );
if ( !empty($c) )
{
$c = implode(',', $_POST['day']);
$c = explode(",", $c);
$in = str_repeat("?,", count($c) - 1) . '?';
$sql = "SELECT * FROM table WHERE day IN ($in) LIMIT ?, ?";
$stmt = $pdo->prepare($sql);
$params = array_merge($c, [$a, $b]);
$stmt->execute($params);
$data = $stmt->fetchAll();
$result = $data;
}
echo json_encode($result);

PHP/HTML button picture change and script call

I have a page with buttons that a user clicks on.
When the button gets clicked I need it to change the image and call a php script to save the change.
I somehow can't get the button to do both, it changes the pic but won't call the php.
CODE:
<?php
$db = new PDO('mysql:host=localhost;dbname=MySettings;charset=utf8mb4', 'TestUser', '1234567890');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try {
$mytable = $_SESSION["SESS_myuserid"];
if($mytable == null)
{$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';}
$stmt = $db->prepare("SELECT * FROM ".$mytable);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn = null;
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo '}';
}
echo'</script>';
$myLeft=0;
$myTop=0;
$myRow=0;
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
$ThePic = "images/Boff.png";
}
else{
$ThePic = "images/Bon.png";
}
echo '<div>';
echo ' ';
echo '</div>';
$myTop=$myTop + 30;
$myRow=$myRow + 1;
if ($myRow == 12){
$myRow=0;
$myTop=0;
if ($myLeft == 0){
$myLeft = 292;
}
else {
$myLeft = 615;
}
}
}
}
catch(PDOException $e) {
$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
?>
Fixed :
Changed the script function. Added a hidden div to be called to load the php which outputs nothing so stays invisible.
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo' $("#HtmlConvo").load("Monitor.php?id='.$TheId.'&Table='.$mytable.'");';
echo '}';
}
echo'</script>';

I created a dropdown list and how to display the other columns data of selected item?

this is my code for dropdown list
<?php
$sql = "SELECT * FROM parts";
$result = mysql_query($sql);
echo "<select name='name' class='ed'>";
echo "<option id='0'> --Select Part Name-- </option>";
while ($row = mysql_fetch_array($result)) {
$op1=$row['part_description'];
$op2=$op1.$row['price'];
$op3=$op2.$row['weight'];
echo "<option value='" . $row['part_description'] ."'>" .$op3 ."</option>";
echo $op3;
}
echo "</select>";
?>
I have 3 columns for my database
part_description, price and weight. In the dropdownlist i created, you can select stored items at part_description. What I want to do is if I select that item in drop down list it will also display also the price and weight. But the display should be out of the box.
Please help me thanks
<?php
$sql = "SELECT part_description FROM parts";
$result = mysql_query($sql);
echo "<select name='name' class='ed'>";
echo "<option id='0'> --Select Part Name--</option>";
while ($row = mysql_fetch_array($result)) {
$op1=$row['part_description'];
$op2=$op1.$row['price'];
$op3=$op2.$row['weight'];
echo "<option value='" . $row['part_description'] ."'>" .$op3 ."</option>";
}
echo "</select>";
?>
This is for print three value in single option tag.
And let me know Is this your expectation.
You can do it in Javascript.
<?php
$parts = mysqli_query($conn, "SELECT part_description, price, weight FROM parts");
$theParts = [];
while ($row = mysqli_fetch_assoc($parts)) {
$part = [];
$part['description'] = $row['part_description'];
$part['price'] = $row['price'];
$part['weight'] = $row['weight'];
$theParts[] = $part;
}
?>
<script type="text/javascript">
var theParts = <?php echo(json_encode($theParts));?>;
function createDropDown() {
var theDropdown = "<select name='name' id='theDropDown' class='ed' onchange='didChange()'>";
theDropdown += "<option value='0'>--Select Part Name--</option>";
theParts.forEach(function(entry) {
theDropdown += "<option value='" + entry['description'] + "'>" + entry['description'] + "</option>";
});
theDropdown += "</select>";
return theDropdown;
}
function didChange() {
var e = document.getElementById("theDropDown");
var str = e.options[e.selectedIndex].value;
var price = null;
var weight = null;
theParts.forEach(function(entry) {
if (entry['description']==str) {
price = entry['price'];
weight = entry['weight'];
}
});
}
</script>
(I typed this code directly into StackOverflow and haven't tested it but it should work)
EDIT:
Here's how to do it using MySQL, although I don't recommend using it.
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database', $conn);
$results = mysql_query("SELECT part_description, price, weight FROM parts");
while ($row = mysql_fetch_assoc($results)) {
//Same as above.
}

Categories