why ajax duplicate content - javascript

Hello I am new here and working on a project that requires this option of "Viewing content in DIV .posts_area, from database using AJAX",
I had a problem that the content I get in .posts_area sometimes duplicate itself.
Can anyone help me with the solution and I would also be happy for more detailed explanation about the subject.
// AJAX in
<script type="text/javascript">
$(document).ready(function() {
var flag = 0;
$.ajax({
type: 'GET',
url: 'getData.php',
data: {
'offset': 0,
'limit': 6
},
async: true,
success: function(data) {
$('.posts_area').append(data);
flag += 3;
}
});
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
$.ajax({
type: 'GET',
url: 'getData.php',
data: {
'offset': flag,
'limit': 5
},
success: function(data) {
$('.posts_area').append(data);
flag += 3;
}
});
}
});
});
</script>
//getData.php
<?php
include ('config/config.php');
include 'includes/classes/user.php';
include 'includes/classes/post.php';
if(isset($_GET['offset']) && isset($_GET['limit'])){
$limit = $_GET['limit'];
$offset = $_GET['offset'];
$data = mysqli_query($con,"SELECT * FROM posts WHERE deleted='no' ORDER by id DESC LIMIT {$limit} OFFSET {$offset} ");
if(mysqli_num_rows($data ) > 0) {
while($row = mysqli_fetch_array($data) ){
$id = $row['id'];
$comments_check = mysqli_query($con, "SELECT * FROM comments WHERE post_id='$id'");
$comments_check_num = mysqli_num_rows($comments_check);
?>
<script>
function myFunction<?php echo $id; ?>() {
var x = document.getElementById("toggleComment<?php echo $id; ?>");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
<?php
$added_by_user = $row['added_by_user'];
$post_profile_pic = $row['post_profile_pic'];
$added_by = $row['added_by'];
$body = $row['body'];
$date_time = $row['date_added'];
$user_session = $_SESSION['user'];
if($user_session == $added_by_user)
$delete_button = "<form action = 'delete_post.php?id=$id' method='POST' id = 'delete_post_id_form'>
<input type ='submit' class = 'delete_post_class_input' id = 'delete_post_id_input' value = 'Delete'></input>
</form>";
else
$delete_button = "";
// if($user_session == $added_by_user)
// $update_button = "<form action = 'update_post.php?post_id=$id' method='POST'>
// <input type ='submit' class = 'update_post_class' id = 'update_post_id' value = 'Update'></input>
// </form>";
// else
// $update_button = "";
$str .= "<div class='status_post' >
<div class='on_post_profile_pic_class' id = 'on_post_profile_pic_id'>
<a href='$added_by_user' class='posted_by_on_img'><img src='$post_profile_pic' width='50' id = 'on_post_profile_img_id'></img></a>
</div>
<div class='posted_by1' id='added_by_on_post' style='color:#ACACAC;'>
<a href='$added_by_user' class='posted_by'> $added_by </a>
</div>
<img src='assets/images/icons/more_info_button_black_down.png' onClick='show_hide()'alt='more_info_on_post_button_black_down_button_alt' class='more_info_on_post_button_black_down_btn' id ='more_info_on_post_button_black_down_btn_id' name ='more_info_name'></img>
<img src='assets/images/icons/more_info_button_black_up.png' alt='more_info_on_post_button_black_up_button_alt' class='more_info_on_post_button_black_up_btn' id ='more_info_on_post_button_black_up_btn_id'></img>
<div class = 'date_added_on_post_class' id = 'date_added_on_post_id'>$date_time</div>
<div class = 'update_post_class' id = 'update_post_id'>$update_button</div>
<div class = 'delete_post_class_div' id = 'delete_post_id'>$delete_button</div>
<div id='post_body' dir=auto>
$body
</div>
</div>
</div>
<div class='span_class' id='span_id' onclick='myFunction$id()' >Comments($comments_check_num) </div>
<hr>
<div class='post_comment' id='toggleComment$id' >
<iframe src='comment_frame.php?post_id=$id' class = 'comment_iframe_class' id='comment_iframe' frameborder='0'></iframe>
</div>
<hr class ='hr'>";
}
echo $str;
}
}
?>

$('.posts_area').html(data);
Use this instead of append()

Related

Add Active Link Class

I have a dynamic navigation bar that stores the pages/URLs in a database. The nav.php is the script that handles displaying and running through the SQL queries to display the links. I'm having a difficult time adding a script that adds an active class to the links.
My page URLs are as follows:
/page/2/full-service-fleet
/rate-request
/employment
/page/5/links
/page/6/contact
PHP:
<nav>
<?php
while ($row = $result->fetch_assoc())
{
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != ''){
$navlink = $navurl;
}
else{
$navlink = "page.php?id=".$navid."&title=".$navslug;
}
if (substr($navlink,0,4) != "http"){
if ($server_name <> "") {
$navlink = "http://".$server_name."/".$navlink;
}
}
if ($navurl == '#'){
$navlink = $navurl;
}
if ($navnum ==0){
?>
<?php echo $navname; ?>
<?php
}else{
?>
<!-- the rest isn't necessary -->
......
</nav>
Browser Rendered Output
The actual links that are being displayed is this line:
<?php echo $navname; ?>
JS Script:
jQuery(document).ready(function($){
// Get current path and find target link
var path = window.location.pathname.split("/").pop();
// Account for home page with empty path
if ( path == '' ) {
path = 'index.php';
}
var target = $('nav a[href="'+path+'"]');
// Add active class to target link
target.addClass('active');
});
You can use this code as it is or you can grab some idea from this one
:
<div class="w3-top" style="z-index: 999;">
<div class="navcontainer">
<div class="w3-hide-small">
<img src="/images/-logo.png" alt="U.S. Transportation" title="" style="">
<div class="abovenav w3-right">
<button class="w3-button w3-round-large" onclick="">Customer Login</button>
<button class="w3-button w3-round-large" onclick="">Carrier Login</button>
</div>
</div>
<div class="w3-bar nav w3-card-2 w3-left-align w3-large" style="text-overflow: auto;" id="nav">
<div class="w3-hide-large w3-hide-medium">
<a class="w3-hide-medium w3-hide-large w3-right w3-margin-right w3-text-white buttons" href="javascript:void(0);" onclick="myFunction()" title="Toggle Navigation Menu"><span class="fa fa-bars"></span></a>
<a href="<?php
if ($server_name <> "") {
echo "http://" . $server_name . "/";
}
?>/index.php" title="Home" class="w3-left w3-margin-left w3-text-white buttons"><span class="fa fa-home w3-xlarge"></span></a>
</div>
<div style="margin-right: 10%;">
<nav>
<?php
include 'yortal\db.php';
$sql = "SELECT *,(select count(*) from pages where parent = p.id) as num from pages p where parent = 0 and status = 'ON' order by sort DESC";
$result = $mysqli->query($sql);
while ($row = $result->fetch_assoc()) {
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != '') {
$navlink = $navurl;
} else {
$navlink = "page.php?id=" . $navid . "&title=" . $navslug;
}
if (substr($navlink, 0, 4) != "http") {
if ($server_name <> "") {
$navlink = "http://" . $server_name . "/" . $navlink;
}
}
if ($navurl == '#') {
$navlink = $navurl;
}
if ($navnum == 0) {
$current_link = $_SERVER[REQUEST_URI];
$active_class = ($navlink==$current_link)?'active':'';
?>
<?php echo $navname; ?>
<?php
} else {
?>
<div class="w3-dropdown-hover w3-hide-small w3-right" onclick="javascript:window.location.href = '<?php echo $navlink; ?>'">
<button class="w3-button"><?php echo $navname; ?></button>
<div class="w3-dropdown-content w3-white w3-card-4">
<?php
//Subpages
$sql2 = "SELECT *,(select count(*) from pages where parent = p.id) as num from pages p where parent = " . $navid . " and status = 'ON' order by sort";
$result2 = $mysqli->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
$dropid = $row2['id'];
$dropname = $row2['nav'];
$dropurl = $row2['url'];
$dropslug = $row2['slug'];
$dropnum = $row2['num'];
if ($dropurl != '') {
$droplink = $dropurl;
} else {
$droplink = "page.php?id=" . $dropid . "&title=" . $dropslug;
}
if (substr($droplink, 0, 4) != "http") {
if ($server_name <> "") {
$droplink = "http://" . $server_name . "/" . $droplink;
}
}
if ($dropurl == '#') {
$droplink = $dropurl;
}
?>
<?php
$actual_link = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
$active_class = ($actual_link==$droplink || $_SERVER[REQUEST_URI] == $droplink)?'active':'';
?>
<?php echo $dropname; ?>
<?php
}
?>
</div>
</div><?php
}
}
?>
</nav>
</div>
</div>
</div>
First of all I'm pretty sure that you may have got wrong path. I suggest the following implementation which will depend on each():
$(document).ready(function(){
loc = window.location.pathname;
$("nav a").each(function(){
if ($(this).attr("href") == loc){
$(this).addClass("active");
$(this).attr("href") = "#"; // to prevent link to the same page
return true;
}
});
});

check duplicate rand function value in database and generate it again

i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.

Can update page with ajax

I have a div element which is populated by the query result(in index.php). I have also another file widget.php which has same query to update page. I have variable in widget.php "page" which navigates through the pages. If I use widget.php?page=2 it will load next page with results. I want to update a div element in index.php on click.(Click "next" and show another 8 news without reloading page).
in index.php :
<button type="button" id="prevbutton">Previous</button>
<button type="button" id="nextbutton">Next</button>
<div id="list"></div>
in script.js:
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var page = 0;
if (id_name == '#prevbutton' || id_name == '#nextbutton') {
if (id_name == '#prevbutton') {
page -= 1;
}
if (id_name == '#nextbutton') {
page +=1;
}
}
$.ajax({
url: 'widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
in widget.php :
<?php
header("Cache-Control: public, max-age=60");
include("logindb.php");
$page = $_GET['page'];
$page = $page*9;
?>
<div id="list">
<?php
$abfrage59 = "SELECT n.news_title,n.news_id,FLOOR(TIMESTAMPDIFF(HOUR, n.timestamp, NOW())) as diff
FROM news n
WHERE n.domain_id = '2' AND n.timestamp < NOW()
ORDER BY timestamp DESC
LIMIT $page,9";
$ergebnis59 = mysql_query($abfrage59);
while ($row59 = mysql_fetch_object($ergebnis59)) {
$newstitleslug = $row59->news_title;
$newstitleslug = str_replace(' ', '-', $newstitleslug);
$newstitleslug = strtolower($newstitleslug);
echo "<div class=\"col-sm-6 col-md-4\" style=\"padding-bottom: 15px;\">
<div class=\"item\">
<img class=\"main\" src=\"http://www.example.com/news/$row59->news_id.png\" />
<div class=\"text\">
<div class=\"inner\">
<a href=\"http://www.example.com/$newstitleslug/$row59->news_id/\" style=\"color:white;\">$row59->news_title<br />
<span class=\"date\">$row59->diff hours ago</span>
</div>
</div>
</div>
</div>";
}
?>
<?php
include("close_connect.php");
?>
So I want to update value $page on click and refresh content of DIV with new data. Thanks in advance.
Edit: removed script from script.js and put in the end of the index.php body:
<script>
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var temppage = 1;
if (id_name == 'prevbutton' || id_name == 'nextbutton') {
if (id_name == 'prevbutton') {
temppage -= 1;
}
if (id_name == 'nextbutton') {
temppage +=1;
}
var page = temppage;
}
$.ajax({
url: 'widgets/news_archive_widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
</script>
Remove the # you're prefixing to prevButton and nextButton as $(this).attr('id') will return the id without the #. The value of id_name will either be prevButton or nextButton.
UPDATE:
Your final js script should look like this:
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var page = $("#currPageNumber").val();
if (id_name == 'prevbutton' || id_name == 'nextbutton') {
if (id_name == 'prevbutton') {
page -= 1;
}
if (id_name == 'nextbutton') {
page +=1;
}
}
$.ajax({
url: 'widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
PHP script:
<?php
header("Cache-Control: public, max-age=60");
include("logindb.php");
$page = $_GET['page'];
$page = $page*9;
?>
<div id="list">
<?php
$abfrage59 = "SELECT n.news_title,n.news_id,FLOOR(TIMESTAMPDIFF(HOUR, n.timestamp, NOW())) as diff
FROM news n
WHERE n.domain_id = '2' AND n.timestamp < NOW()
ORDER BY timestamp DESC
LIMIT $page,9";
$ergebnis59 = mysql_query($abfrage59);
while ($row59 = mysql_fetch_object($ergebnis59)) {
$newstitleslug = $row59->news_title;
$newstitleslug = str_replace(' ', '-', $newstitleslug);
$newstitleslug = strtolower($newstitleslug);
echo "<div class=\"col-sm-6 col-md-4\" style=\"padding-bottom: 15px;\">
<div class=\"item\">
<img class=\"main\" src=\"http://www.example.com/news/$row59->news_id.png\" />
<div class=\"text\">
<div class=\"inner\">
<a href=\"http://www.example.com/$newstitleslug/$row59->news_id/\" style=\"color:white;\">$row59->news_title<br />
<span class=\"date\">$row59->diff hours ago</span>
</div>
</div>
<input type='hidden' value='".$_GET['page']."' id='currPageNumber'>
</div>
</div>";
}
?>
<?php
include("close_connect.php");
?>

How to add an array from the data attribute and id using javascript and combine them in array php?

I just want to ask if how to merge this two array from all id value and data-rate value on my list order? there is too many ul li, so i need to get them all and store it into array.
this is my code in javascript:
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("ul.reorder-photos-list li").each(function() { x.push($(this).attr('data-rate').substr(9)); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {
ids: " " + h + "",
rate: " " + x + ""
},
success: function(html)
{
window.location.reload();
/*$("#reorder-helper").html( "Reorder Completed - Image reorder have been successfully completed. Please reload the page for testing the reorder." ).removeClass('light_box').addClass('notice notice_success');
$('.reorder_link').html('reorder photos');
$('.reorder_link').attr("id","");*/
}
});
and this is my html code:
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?= $row['rate']?>" data-rate="<?php echo $row['rate']; ?>" >
and then in my order_update.php this is my code.
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n], "data" => $rates[$n]);
$n++;
}
and this is my insert query from orderArray
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$update = mysqli_query($this->connect,"UPDATE `test` SET `order` = $count, `rate`=$array[rate] WHERE id = $array[id]");
$count ++;
}
return true;
}
hope someones helps me. :)thanks in advance!
When setting up your data, you don't need to have multiple loops. You can loop through the data once:
var dataArray = [];
$("ul.reorder-photos-list li").each(function() {
var el = $(this),
input = el.children(':input'); // This gets the input decendent of the li
// When adding one item at a time to an array, array[array.length] = item is better
dataArray[dataArray.length] = {
id: el.attr('id').substr(9),
rate: input.val(),
};
});
$.ajax({
type: "POST",
url: "order_update.php",
data: { items: dataArray }, // items gives the PHP something to use as a key in the POST data
success: function(html) {...}
});
Your PHP will look like this:
// The data passed from the Ajax call is already an array
$itemsArray = $_POST['items'];
// Your function to process the array
function updateOrder($orderArray) {
foreach ($orderArray as $index => $array) {
// $index will already have a count, you need to +1 because it's 0-based
mysqli_query($this->connect, "UPDATE `test` SET `order` = " . ($index + 1) . ", `rate`=" . $array['rate'] . " WHERE id = " . $array['id']);
}
return true;
}
var rates;
$("ul.reorder-photos-list li").each(function() {
rates.id.push($(this).attr('id').substr(9));
rates.rate.push($(this).attr('data-rate').substr(9));
});
This will create your JSON object of h/x pairs.
$.ajax({
type: "POST"
, url: "order_update.php"
, data: { JSON.stringify(rates); }
, success: function(html) {
window.location.reload();
/* $("#reorder-helper").html(
* "Reorder Completed - Image reorder have been successfully completed.
* Please reload the page for testing the reorder."
* ).removeClass('light_box').addClass('notice notice_success');
* $('.reorder_link').html('reorder photos');
* $('.reorder_link').attr("id","");
*/
}
});
This should fix your call to send the correct data.
Your PHP side is going to want to have something similar to this:
if(isset($_POST['rates'])) {
$ratesString = $_POST['rates'];
$rates = json_decode($ratesString);
}
// Do other things with $hx`
Your insert query is off, too. You need to declare each value as a variable or your compiler is going to hate your PHP, too. You also have some unnecessary quotes in your query.
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$rate = $array['rate'];
$id = $array['id'];
mysqli_query($this->connect,"UPDATE test SET order = $count, rate = '$rate' WHERE id = '$id'");
$count ++;
}
return true;
}
For your HTML, I think this is what you were going for, but not sure since it's not really explained all that well...Feel free to comment on your intentions.
<ul>
<?php foreach($orderArray as $array) : ?>
<li id="image_li_<?php echo $array['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?php echo $array['rate']?>" data-rate="<?php echo $array['rate']; ?>" ></li>
<?php endforeach; ?>
</ul>
Hope this helps.
-C§
I got the code now. thanks for your help guys!
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("input").each(function() { x.push($(this).val()); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {ids: " " + h + "",rate: " " + x + ""},
/*data: { items: dataArray },*/
success: function(html)
{
...
}
});
In Php side:
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n] , "rate" => $rates[$n]);
$n++;
}
$db->updateOrder($orderArray);
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
mysqli_query($this->connect, "UPDATE `test` SET `morder` = " . $count . ", `mtoursrate`=" . $array['rate'] . " WHERE id = " . $array['id']);
$count ++;
}
return true;
}

PHP post variable is not being rendered

I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>

Categories

Resources