ok maybe i must put all my code:
<?php
include('header_application.php');
$obj_clean->check_user();
$limit = 10;
if(!isset($_GET['page']))
$page = 1;
else
$page = $_GET['page'];
$from = (($page * $limit) - $limit);
$msg = "";
if (isset($_GET['unblock']))
{
$code = $obj_clean->unblockUser($_GET['unblock'],$_GET['code']);
if ($code == "error")
{
$msg = "Could not delete message!";
}
else
{
$msg = "You have unblocked ".$code;
}
}
//Get dynamic data required for this page from the database
$users = $obj_clean->getContacts($_SESSION['user_id'], $from, $limit);
$rows = $obj_clean->getContactsCount($_SESSION['user_id']);
include ("header.php");
?>
<div class="innerContainer">
<head>
<script type="text/JavaScript">
function yesnolist(val)
{
var e = confirm('Do you want to send a free chat request?');
if (e == true)
{
window.location.href = "http://www-rainbowcode-mobi/confirmfreechat.php";
//window.location('http://www-rainbowcode-mobi/confirmfreechat.php');
return true;
}
else
return false;
}
</script>
</head>
<span class="headings2">CONTACTS</span>
<?php if (isset($msg) && !empty($msg)) echo "<br/><font color='red'>".$msg."</font>"; ?>
<br/><br/>
<?php
if (count($users) > 0)
{
echo "<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
foreach ($users as $user)
{
//Breaks the unique code into 3 parts so that the numeric part can be a different colour
$codeLength = strlen($user['unique_code']);
$firstPartLength = $codeLength - 5;
$uniqueCode3 = substr($user['unique_code'], -2);
$uniqueCode2 = substr($user['unique_code'], -5, 3);
$uniqueCode1 = substr($user['unique_code'], 0, $firstPartLength);
echo '<tr>';
echo '<td>';
echo '<a class="charcoal_link" style="line-height: 20px;" href="'.ADDRESS.'view_profile.php?id='.$user['profile_id_contact'].'">'.$uniqueCode1.'<span class="pink_text">'.$uniqueCode2.'</span>'.$uniqueCode3.'</a>';
$requestor_id = $_SESSION['user_id'];
$profile_id = $user['profile_id_contact'];
$rel1 = $obj_clean->hasRelation($requestor_id,$profile_id);
$rel2 = $obj_clean->hasRelation($profile_id,$requestor_id);
if($rel1 && $rel2)
{
echo " ";
//echo 'Free Chat';
echo 'Free Chat';
}
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "You have no contacts yet";
}
?>
</div>
<?php include("footer.php"); ?>
hope this will help better
Free Chat
should be:
Free Chat
try this:
function yesnolist()
{
if (confirm('Do you want to send a free chat request?'))
window.location = "http://www-rainbowcode-mobi/confirmfreechat.php";
}
.
.
.
<a href="#" onClick="yesnolist()">
I'd assume changing the URLs to valid domains might help things, so try:
window.location.href = "http://www.rainbowcode.mobi/confirmfreechat.php";
window.location('http://www.rainbowcode.mobi/confirmfreechat.php');
function yesnolist()
{
var e = confirm('Do you want to send a free chat request?');
if (e == true)
{
window.location = "http://www-rainbowcode-mobi/confirmfreechat.php";
return true;
}
else
return false;
}
and
<label onClick="return yesnolist();">Free Chat</a>
You can not pass onclick event on (a href="") tag because href part redirects the page and after that the javascript redirect part is called.
Or
(a href="#" onclick="return yesnolist();")Free Chat(/a)
Related
I've written a short PHP programm which shows two pictures. With 2 radio buttons, you have to choose one and then you have to click the submit button. Then, the page saves the vote for the picture you have chosen and then shows the next two pictures.
I use a session variable to store, which images have to be showed.
Unfortunately, the variable is not increased after the first click on the "next" button. After, it works perfectly well.
What is wrong?
Here is my code:
<?php
session_start();
if (isset($_SESSION['image_nr'])) { /* If there is already a value set */
$x = $_SESSION['image_nr'];
echo $x;
}
else {
$_SESSION['image_nr'] = 1; /* Set to 1 */
$x = $_SESSION['image_nr'];
}
include('sql/db_connect.php');
include('sql/queries.php');
if($x == 9){
increaseParticipants();
$_POST['submit']='';
$_SESSION['image_nr'] = 1;
session_unset($_SESSION['image_nr']);
header( "Location: thankyou.php" );
}
?>
<html>
<header>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" language="JavaScript" src="functions.js"></script>
</header>
<body>
<form action= "" method = "post">
<div class='content' id='image1'><?php if($x == 1){echo"<img src='images/image_1.jpg' width='380'><br>Image 1";}?></div>
<div class='content2' id='image2'><?php if($x == 1){echo"<img src='images/image_2.jpg' width='380'><br>Image 2";}?></div>
<div id='bottom'>
<input type='radio' name='radio' id='radio1' value='<?php echo $x; ?>' onchange="enableButton()"> Image <?php echo $x; ?> <br>
<input type='radio' name='radio' id='radio2' value='<?php echo ($x+1);?>' onchange="enableButton()"> Image <?php echo $x+1; ?><br>
<input type="submit" id="button" name= "submit" value="Next" onclick="saveClick()" disabled />
</div>
<?php
if (isset($_POST['submit']) && $_POST['submit']!='') {
if(isset($_POST['radio'])) {
$image = $_POST['radio'];
increaseClicks($image);
$x = $x+2;
}
$_SESSION['image_nr'] = $x;
$next = getNext($image);
echo '<script type="text/javascript">'
, 'changeImage('.$next.');'
, '</script>'
;
$_POST['submit']='';
}
?>
</form>
</body>
</html>
Here are the JS functions:
function enableButton(){
document.getElementById("button").disabled = false;
}
function changeImage(next){
var firstpart = "<img src='images/image_";
var secondpart = ".jpg' width='380'><br>Bild"+next;
var inHtml = firstpart.concat(next, secondpart);
document.getElementById("bild1").innerHTML = inHtml;
var secondpart = ".jpg' width='380'><br>Bild"+(next+1);
var inHtml = firstpart.concat((next+1), secondpart);
document.getElementById("bild2").innerHTML = inHtml;
}
And the queries (I know that these are deprecated)
<?php
function getClicks ($image){
$q1 = "SELECT clicks from tbl_clicks WHERE ID_bild=".$image;
$rq1 = mysql_query($q1);
$return = mysql_fetch_array($rq1);
$number_of_clicks = $return['clicks'];
return $number_of_clicks;
}
function getClicksAll (){
$q1 = "SELECT ID_bild, name, clicks from tbl_clicks";
$rq1 = mysql_query($q1);
return $rq1;
}
function increaseClicks ($image){
$clicks = getClicks($image);
$clicks = (int)$clicks;
$clicks = $clicks + 1;
echo "this are the clicks: ".$clicks;
$q2 = "UPDATE tbl_clicks SET clicks = ".$clicks." WHERE ID_bild = ".$image;
mysql_query ($q2);
}
function getNext ($image){
$q3 = "SELECT next from tbl_clicks WHERE ID_bild=".$image;
$rq3 = mysql_query($q3);
$return = mysql_fetch_array($rq3);
$next = $return['next'];
return $next;
}
function getParticipants(){
$q4 = "SELECT participants from tbl_participants";
$rq4 = mysql_query($q4);
$return = mysql_fetch_array($rq4);
$participants = $return['participants'];
return $participants;
}
function increaseParticipants(){
$participants = getParticipants();
$q5 = "UPDATE tbl_participants SET participants = ".($participants+1);
mysql_query ($q5);
}
?>
I have simple pagination included in my homepage in order to display the latest news/images from my server. The pagination is working fine but when i try to move to other page number example page 2, the page loads but after refreshing it goes back again to page 1. I am new to PHP , Ajax and Jquery so I can't figure out where to solve this problem. Here are my codes:
pagination.php
<?php
function paginate($reload, $page, $tpages, $adjacents) {
$prevlabel = "‹ Prev";
$nextlabel = "Next ›";
$out = '<div class="pagin page_style">';
// previous label
if($page==1) {
$out.= "<span>$prevlabel</span>";
} else if($page==2) {
$out.= "<a href='javascript:void(0);' onclick='load(1)'>$prevlabel</a>";
}else {
$out.= "<a href='javascript:void(0);' onclick='load(".($page-1).")'>$prevlabel</a>";
}
// first label
if($page>($adjacents+1)) {
$out.= "<a href='javascript:void(0);' onclick='load(1)'>1</a>";
}
// interval
if($page>($adjacents+2)) {
$out.= "...\n";
}
// pages
$pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
$pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
for($i=$pmin; $i<=$pmax; $i++) {
if($i==$page) {
$out.= "<span class='current'>$i</span>";
}else if($i==1) {
$out.= "<a href='javascript:void(0);' onclick='load(1)'>$i</a>";
}else {
$out.= "<a href='javascript:void(0);' onclick='load(".$i.")'>$i</a>";
}
}
// interval
if($page<($tpages-$adjacents-1)) {
$out.= "...\n";
}
// last
if($page<($tpages-$adjacents)) {
$out.= "<a href='javascript:void(0);' onclick='load($tpages)'>$tpages</a>";
}
// next
if($page<$tpages) {
$out.= "<a href='javascript:void(0);' onclick='load(".($page+1).")'>$nextlabel</a>";
}else {
$out.= "<span>$nextlabel</span>";
}
$out.= "</div>";
return $out;
}
?>
/////////////////////////////////////////
Home.php
<?php session_start(); ?>
<?php
$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax'){
/* Connect To Database*/
$dbname = 'banaue.com';
$link = mysql_connect("localhost","root","") or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $link) or die("Couldn't select database");
include 'pagination.php'; //include pagination file
//pagination variables
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
$per_page = 1; //how many records you want to show
$adjacents = 5; //gap between pages after number of adjacents
$offset = ($page - 1) * $per_page;
//Count the total number of row in your table*/
$count_query = mysql_query("SELECT COUNT(title) AS numrows FROM news");
$row = mysql_fetch_array($count_query);
$numrows = $row['numrows'];
$total_pages = ceil($numrows/$per_page);
$reload = 'Home.php';
//main query to fetch the data
$result = mysql_query("SELECT * FROM news ORDER BY date_posted LIMIT $offset,$per_page");
//loop through fetched data
while($test = mysql_fetch_array($result)){
$id = $test['title'];
echo "<div class='content' stye=margin-bottom: 20px;>";
echo'<div class="img_content" ><img src='.$test['img_path'].' style=height:520px;width:100%;></div>';
echo"<p class=para_news2 style=margin-left:10px;><font color='#336699'>" .$test['title']."</p></font><br /><br />";
echo"<p class=para_news4 style=margin-left:10px;width:100%;><img src='images/user.gif'> Story By: <font color='lavander'>" .$test['author']."</font></p>";
echo"<p class=para_news4 style=margin-left:10px;width:100%;><img src='images/calendar.gif'> Date Posted: <font color='red'>". $test['date_posted']. "</font></p>";
echo"<p class=para_news3 style=margin-left:10px;width:100%;><img src='images/comments.gif'> <font color='black'>". $test['intro']. "</font></p><br>";
echo"<a href ='news.php?title=$id'><font style='float:right;margin-right:10px;background:url(images/bg_header.jpg);padding:2px;'>Read more ...</a><br>";
echo "</div>";
}
echo paginate($reload, $page, $total_pages, $adjacents);
} else{
?>
<!DOCTYPE html>
<head><!-- Head declaration -->
<script type="text/javascript">
$(document).ready(function(){
load(1);
});
function load(page){
$("#loader").fadeIn('slow');
$.ajax({
url:'Home.php?action=ajax&page='+page,
success:function(data){
$(".outer_div").html(data).fadeIn('slow');
$("#loader").fadeOut('slow');
}
})
}
</script>
</head>
<body>
<!-- Body Content -->
<div class="main_body" style="height:auto;">
<!-- Top Stories Query-->
<div class="outer_div">
</div>
</div>
</body>
</html>
<?php }?>
Please help me with this problem so that i can move on....
You could use a cookie to store the current pagination position in the clients web browser and read it back when creating the page, to start pagination from last position.
Something like this
setcookie('pagination_pos',$pagination_pos,time() + 86400); // 86400 = expire after 1 day
and then read it back
echo 'Current position '($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 0);
this will read the current position from the cookie, if no cookie is there it falls back to 0.
Okay as you requested on how to use it in your code, I made a simple example function you can use in your code:
function getPaginationPos(){
if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
setcookie('pagination_pos',$_REQUEST['page'],time() + 86400);
return $_REQUEST['page'];
} else {
return ($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 1);
}
}
this will check if there is a "page" variable in the request and if so it will store the position as a cookie. If no "page" variable is in the request it will check if there is a cookie or return 1.
If I understand your code right you have to replace this line
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
with
$page = getPaginationPos();
I see another problem in the javascript "load" function where you force page 1 on reload
$(document).ready(function(){
load(1);
});
you can try this:
$(document).ready(function(){
load();
});
add also a check for the page variable to the javascript function, to handle the case if page is not set.
<script type="text/javascript">
$( document ).ready(function() {
load()
});
function load(page){
if (typeof page === 'undefined') {
page = ''
} else{
page = '&page='+page
}
$("#loader").fadeIn('slow');
$.ajax({
url:'Home.php?action=ajax'+page,
success:function(data){
$(".outer_div").html(data).fadeIn('slow');
$("#loader").fadeOut('slow');
}
})
}
</script>
based on Sir Manuel's code, if you don't want to store your variable to be stored in cookies you can try to put it in session variable.
change this line:
function getPaginationPos(){
if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
setcookie('pagination_pos',$_REQUEST['page'],time() + 86400);
return $_REQUEST['page'];
} else {
return ($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 1);
}
}
into this:
function getPaginationPos(){
if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
$_SESSION['pages'] = $_REQUEST['page'];
return $_REQUEST['page'];
} else {
return $_SESSION['pages'];
}
}
and this:
$(document).ready(function(){
load();
});
into this:
$(document).ready(function(){
load(<?php print $_SESSION['pages']; ?>);
});
I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});
Ok, I am using a PHP editing form (previous person built) that submits data into an MSSQL database this works fine however when the information is submitted into the database and later retrieved the the form page (for editing) there is a <br> at the beginning of the text. If the fields start with a <ul> that <br> is not inserted. I have been trying to figure out how to stop this. One thing I tried ends up removing all <br> in the text which makes the formatting disappear, How can I keep it from inserting the <br> at the top but keeping the <br> everywhere else? here is the code I have: ( I am giving you everything up to the first field where I have the issue appear)
function fromhtml ($x) {
$x = preg_replace("/<p>/i","\n\n",$x);
//$x = preg_replace("/<br>/i","\n",$x);
$x = preg_replace("/<li>/i","\n<li>",$x);
return $x;
}
$PHP_SELF = $_SERVER['PHP_SELF'];
$course_id = #$_GET["course"];
if ($course_id == "") {
$sqlquery = "SELECT id, title, goals, outline, reference, deliverymode, updated2 = CONVERT(VARCHAR(19), updated, 120)
FROM courses WHERE division_id = '$division_id' ORDER by id";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
print "<table border=1 id=\"content_table\"><tr><th>ID</th><th>Title</th><th>Status</th><th>Last modified</th></tr>\n";
$i = 0;
while ($number > $i) {
$course_id = mssql_result($result,$i,"id");
$reference = mssql_result($result,$i,"reference");
$updated = mssql_result($result,$i,"updated2");
print "<tr><td>";
if ($reference == "") {
print "<a href=$PHP_SELF?division=$division_id&course=$course_id>$course_id</a>";
} else {
print "$course_id";
}
print "</td><td>";
print mssql_result($result,$i,"title");
print "</td><td>";
if ($reference == "") {
if ( (mssql_result($result,$i,"goals")=="") and (mssql_result($result,$i,"outline")=="") ) {
print "<b>No syllabus, or incomplete</b></td>";
}
} else {
print "Based on $reference";
}
print "</td><td>$updated</td>\n";
print "</tr>\n";
$i++;
}
print "</table>";
exit;
}
$sqlquery = "SELECT * FROM courses WHERE id = '$course_id'";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
if ($number == 0) {
print "<html><body>";
print "No course with the ID \"$course_id\" exists in the course database.";
print "</body></html>";
exit;
}
$i = 0;
$description = fromhtml(mssql_result($result,$i,"description"));
print "<html><head><title>DACC Course Syllabus - $course_id</title>";
print "<script language=\"JavaScript\" type=\"text/javascript\" src=\"/rte/richtext2.js\"></script>";
?>
<script language="JavaScript" type="text/javascript">
<!--
initRTE("/rte/images/", "/rte/", "");
//-->
function submitForm() {
updateRTEs();
document.edit-course.submit();
return false;
}
</script>
<?php
print "</head><body>\n";
//Begin Form
print "<form name=\"edit-course\" id=\"edit-form\" method=\"post\" action=\"write.php?course=$course_id\" onSubmit=\"return submitForm()\">\n";
print "<fieldset>";
print "<label for=\"description\">Course Description</label>";
$description=addslashes(preg_replace('`[\r\n]`','',$description));
?>
<script language="JavaScript" type="text/javascript">
<!--
writeRichText('description', '<?php print $description; ?>', 200, 300, true, false);
//-->
</script>
<?php
print "</fieldset>";
It that BR is at very very beginning of string then use this
$x = preg_replace("/^<br(\/|)>/i","\n",$x);
instead of that commented line
preg_replace has a fourth parameter, $limit. Setting this to 1 would limit the preg_replace to the first occurence. Alternatively you could use the regular expression ^<br>. This would only replace <br> when it is at the beginning of the string.
Edit: Sorry, I misunderstood your problem. Use $variable=preg_replace("/^<br>/i", "", $variable); to strip the first <br>.
I have this code: messages.php
if (count($row) > 0)
{
foreach ($row as $r)
{
//some code setting variables
if ($opened_once >= 1)
{
}
else
{
echo "<tr>";
echo '<td><a class="red_link" href="'.ADDRESS.'view_message.php?id='.$r['id'].'" id= "subject_id" ><span id = "subject">'.$r['subject'].'</span></a></td>';
echo '<td id = "unique_code1">'.$uniqueCode1.'<span class="pink_text" id = "unique_code2">'.$uniqueCode2.'</span><span id = "unique_code3">'.$uniqueCode3.'</span></td>';
echo "</tr>";
}
}
I need to update $r['id'], $r['subject'], $uniqueCode1, $uniqueCode2, $uniqueCode
My jQuery code:
<script>
$(document).ready(function()
{
refresh();
});
function refresh()
{
$.post('getMessageDetails.php', function (json) {
$("#subject").html(json.subject);
$("#subject_id").html(json.subject_id);
$("#unique_code1").html(json.unique_code1);
$("#unique_code2").html(json.unique_code2);
$("#unique_code3").html(json.unique_code3);
});
window.setTimeout(refresh,30000);
}
</script>
Then I have newMessageCnt.php
<?php
<?php
header('Content-Type: application/json; charset=utf-8');
include('header_application.php');
$limit = 15;
if(!isset($_GET['page']))
$page = 1;
else
$page = $_GET['page'];
$from = (($page * $limit) - $limit);
$row = $obj_clean->getMessages($_SESSION['user_id'], $from, $limit);
if (count($row) > 0)
{
foreach ($row as $r)
{
$codeLength = strlen($r['unique_code']);
$codeLength = strlen($r['unique_code']);
$firstPartLength = $codeLength - 5;
$uniqueCode3 = substr($r['unique_code'], -2);
$uniqueCode2 = substr($r['unique_code'], -5, 3);
$uniqueCode1 = substr($r['unique_code'], 0, $firstPartLength);
$message_id = $r['id'];
$subject = $obj_clean->getMessageDetails($message_id);
$opened_once = $obj_clean->getOpenedOnce($message_id);
if ($opened_once >= 1)
{
$array['subject'] = $r['subject'];
$array['subject_id'] = $r['id'];
$array['unique_code1'] = $uniqueCode1;
$array['unique_code2'] = $uniqueCode2;
$array['unique_code3'] = $uniqueCode3;
}
}
}
echo json_encode($array);
exit();
?>
?>
I call this .php somewhere else as well where I just want the value of echo $obj_clean->getUnopenedMessagesCount($_SESSION['user_id']);
But from my messages.php I want
echo '<td><a class="blue_link" href="'.ADDRESS.'view_message.php?id='.$r['id'].'">'.$r['subject'].'</a></td>';
echo '<td>'.$uniqueCode1.'<span class="pink_text">'.$uniqueCode2.'</span>'.$uniqueCode3.'</td>';
I'm not sure if I'm doing this right, some advice please?
$.post('ajax_call.php', function (json) {
$("#subject").html(json.subject);
$("#unique_code").html(json.unique_code);
});
//ajax_call.php
<?php
$array['subject']='bla-bla';
$array['unique_code']='1231312';
header('Content-Type: application/json; charset=utf-8');
echo json_encode($array);
exit();
Better would be to have your PHP return an object containing the values you want as properties. This can be sent back to the browser using JSON. Your client-side code see this as an object and can extract the properties and populate the HTML. This separates your presentation (VIEW) from your data (MODEL).
EDIT: Exactly as #TROODON has answered.