PHP Search: Using Jquery to alter a php a value - php

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();
});

Related

How to fill a template file with data from a table

I am looking for some initial direction on this one because I cannot seem to find my way with it. Let me explain... I'm creating a music website and having a search bar. It filters information as the user types. I don't want to make a separate .php file for each song on the website. (Eg: song1.php, song2.php, etc...). There should be one PHP template file, that outputs the webpage for ALL songs. With my code, when I try searching with the search bar, it opens the template file as expected but it fills the file with information of only the first row from the mysql table. This is the form, its in the index page:
<script type = "text/javascript "src = "jquery.js">
<form class="navbar-form navbar-left" >
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search for songs, artists" autocomplete="off">
<div id = "searchresults"> </div>
Then there's the search.js file having two tasks, that is to check if a result has been clicked and also if the user has pressed a key. Its like this:
$('#search').keyup(function()
{
var searchterm = $ ('#search').val();
if (searchterm != '')
{
$.post('search.php', {searchterm:searchterm},
function(data)
{
$('#searchresults').html(data);
});
}
else{
$('#searchresults').html('');
}
});
$('#mylink').click(function(){
var wanted = $('#mylink').val();
$.post('/web/ztemplate.php', {wanted:wanted});
});
I think it's the one having an error but I can't figure out where it is. The template file has this php code :
$search = $_POST['wanted'];
$find = mysql_query("SELECT * FROM search WHERE title LIKE '%$search%'");
$row = mysql_fetch_assoc($find); $title = $row["title"];
There's a search.php file which queries the database to provide information for the instant search. It looks like this :
$search = mysql_real_escape_string(trim($_POST['searchterm']));
if ($search == '' && ' '){
echo 'No results found';
}
else {
$find_videos = mysql_query("SELECT * FROM search WHERE keywords LIKE '%$search%'");
$count = mysql_num_rows($find_videos);
if ($count ==0){
echo 'No Results found for '.$search;
}
else {
while($row = mysql_fetch_assoc($find_videos)){
$title = $row["title"];
$link = $row["link"];
echo "<a href = '$link'><h5 id = 'mylink'> $title <h5> </a> <hr /> ";
}
}
}
Any help is much appreciated.
why you not send an AJAX??
$('#search').keyup(function(){
var searchterm = $ ('#search').val();
if (searchterm != ''){
$.ajax({
type: 'POST',
data: {
"searchterm": searchterm,
"_token":"{{ csrf_token() }}"
},
url: "{{URL::asset('yourPHP')}}",
success: function(response){
$('#searchresults').html(response);
}
});
}else{
$('#searchresults').html('');
}
});
PHP
function searchSong($search =''){
$search = (trim($_POST['searchterm']));
$out='';
if ($search == '' && ' '){
echo 'No results found';
}else {
$sql = "SELECT * FROM search WHERE title LIKE '%$search%'";
$data= DB::select($sql);
$count = count($data);
if ($count ==0){
echo 'No Results found for '.$search;
}else {
foreach ($data as $key => $row) {
$title = $row["title"];
$link = $row["link"];
$out .= "<a href = '$link'><h5 id = 'mylink'> $title </h5> </a> <hr /> ";
}
}
}
return $out;
}

After ajax request php function not receiving variables

I'm developing a searcher and I made a function that gets the data from a db, saves each ad in a variable and saves pagination (from another function) in another variable, so they can be returned in an array to be printed in the html later.
It works like this: you hit a buy or rent button and you go to the search page (/search?do?=buy/rent) then you have to select the property type, optionally a city/zone and hit search. Ajax sends the data via post (to search.php, the same file), hides the first container and shows the second container that has the list of properties with a pagination at the end of the page.
These are the main variables and a script to hide/show containers:
$mode = filter_input(INPUT_GET, 'do', FILTER_SANITIZE_STRING); // buy or rent
$prop_type = filter_input(INPUT_POST, 'prop_type', FILTER_SANITIZE_STRING); // res or com AJAX
$city = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_NUMBER_INT); // AJAX
$zone = filter_input(INPUT_POST, 'zone', FILTER_SANITIZE_NUMBER_INT); // AJAX
$page_number = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT);
if (isset($page_number) && $page_number >= 1) {
$cont1 = 'display: none;';
$cont2 = NULL;
// need a way to get the prop_type (the checked checkbox before changing the page) without using $_GET.
} else {
$cont1 = NULL;
$cont2 = 'display: none;';
}
This is the function:
function get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage) {
if ($prop_type == 'res') {
$table2 = 'res_prop';
} else if ($prop_type == 'com') {
$table2 = 'com_prop';
}
if ($city != 0) {
$optional_cond = ' WHERE t2.city = ' . $city;
$optional_cond2 = NULL;
if ($zone != 0) {
$optional_cond2 = ' AND t2.zone = ' . $zone;
}
} else $optional_cond = $optional_cond2 = NULL;
$mysqli = new mysqli('127.0.0.1', 'db', '123456', 'name');
// pagination
if ($stmt = $mysqli->prepare('SELECT COUNT(id) FROM ' . $table)) {
$stmt->execute();
$stmt->bind_result($totalitems);
$stmt->fetch();
if (!isset($page)) {
$page = (int)$page_number <= 0 ? 1 : (int)$page_number;
}
$limit = 4;
if ($page > ceil($totalitems / $limit)) {
$page = ceil($totalitems / $limit);
}
$start = ($page - 1) * $limit;
$stmt->close();
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1
INNER JOIN ' . $table2 . ' t2 ON t2.id = t1.id
' . $optional_cond . $optional_cond2 . '
LIMIT ?, ?')) {
$stmt->bind_param('ii', $start, $limit);
$stmt->execute();
$stmt->bind_result($id, $id, $type, $status, $bhk, $baths, $area1, $area2, $age, $description, $price, $city, $zone, $img1, $img2, $img3, $img4);
$test = "";
while ($row = $stmt->fetch()) {
if ($status === 0) {
$possesion = 'En construcción';
} else if ($status === 1 || $status === 2) {
$possesion = 'Inmediata';
} else $possesion = 'Desconocida';
if ($prop_type == 'res') {
$is_res = '<p><span class="bath">Bed</span>: <span class="two">' . $bhk . ' BHK</span></p>
<p><span class="bath1">Baths</span>: <span class="two">' . $baths . '</span></p>';
} else $is_res = NULL;
$test .= '<div class="box-col">
<div class="col-sm-6 left-side ">
<img class="img-responsive" src="' . $img1 . '" alt="">
</div>
<div class="col-sm-6 middle-side">
<h4>Disponibilidad: ' . $possesion . '</h4>
' . $is_res . '
<p><span class="bath2">Built-up Area</span>: <span class="two">' . $area1 . ' m²</span></p>
<p><span class="bath3">Plot Area</span>: <span class="two">' . $area2 . ' m²</span></p>
<p><span class="bath4">Age of property</span>: <span class="two">' . $age . ' Year(s)</span></p>
<p><span class="bath5">Price</span>: <span class="two">' . $price . ' €</span></p>
<div class="right-side">
Contact Builder
</div>
</div>
<div class="clearfix"> </div>
</div>
';
$pagination = functions::getPaginationString($page, $totalitems, $limit, $adjacents = 1, $targetpage, $pagestring = "&page=");
}
} //else echo "Statement failed: " . $mysqli->error . "<br>";
} //else echo "Statement failed: " . $mysqli->error . "<br>";
return array($test, $pagination);
}
This is the main code:
if (empty($_GET)) {
echo 'under construction';
}
else if (isset($mode) && $mode == 'buy') {
$table = 'to_sell';
$targetpage = '/search?do=buy';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else if (isset($mode) && $mode == 'rent') {
$table = 'to_rent';
$targetpage = '/search?do=rent';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else {
echo 'invalid url';
}
This is the AJAX script that sends the checkbox value via post (it's not working correctly, I don't get an undefined error in $prop_type (I don't know why???) but I get it in $table2, that it's inside the if ($prop_type == '')):
$('.search, .pagination').click(function() { // search button and change page
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.post('search.php', { // same file, maybe self
prop_type: $prop_type,
city: $('select[name=city]').val(), // optional
zone: $('select[name=zone]').val(), // option value="0" by default
success: function(){
$('.cont-1').hide();
$('.cont-2').show();
}
});
});
It works perfectly if I manually set $prop_type = 'res';. Any ideas?
Another problem is that the pagination buttons link does not work, it just triggers the ajax script (they need to send the data, otherwise the script will restart when changing pages).
I really would appreciate any optimization to the scripts. Thanks.
You're mixing your javascript and php here.
In PHP you declare a variable with $varname, in Javascript, $ represents the jQuery operator. As such your code that says $prop_type is totally invalid since this is javascript code. You're telling jQuery to execute some functionality called prop_type which doesn't exist, and as such you're getting an error that this is undefined.
if ($('#res_prop').is(':checked')) {
var prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
var prop_type = $('#com_prop').val();
}
And change the line which reads prop_type: $prop_type, to prop_type: prop_type,
If you want to import the <div class="results"></div> container with ajax:
you should use this tested and working code:
$(document).ready(function(){
$('.search, .pagination').click(function() { // search button and change page
$prop_type = '';
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.ajax({
method: "POST",
url: "go.php",
data: {
'prop_type': $prop_type,
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val()
}
}).done(function(data) {
var _html = $.parseHTML(data);
$('.cont-1').hide();
$('.cont-2').show();
$(_html).each(function(i, el) {
if (el.className == 'results') {
$('.results').html($(el).html());
};
});
});
return false;
});
});

help formatting news entry in PHP

On My Site users can login and add news. That works fine. I have problems when trying to display the news. First problem is if the news text doesn't fill all the space by the side of the news image, then the next news item gets displayed too soon (not below the orange breaker) as you can see on the site at the moment. I was thinking to get around this I could set the height of each news post div to the height of the image, although the image is a little shorter than the div so I'm not sure how I'd do that.
Secondly, users put links in their news posts. How do I get them to be displayed as active? on firefox they just come out as text. Could someone point me in the right direction please!
Here's the code:
$query="SELECT id, date, title, text, author, media1, media2, deleted FROM news ORDER BY id DESC LIMIT 4";
$result=mysql_query($query);
$counter = 0;
$number1 = 1;
$number2 = 2;
while($row = mysql_fetch_array($result)){
if($row['deleted'] == 0) {
if (($counter % 2) == 0) {
echo '<div id="text">';
echo '<a name="'.stripslashes($row['title']).'" id="'.stripslashes($row['title']).'"></a>';
echo '<span class="kisstitle">'.stripslashes($row['title']).'</span><br>';
echo ' (';
echo $row['date'];
echo ')';
echo '<br>';
echo '<br>';
if((preg_match ("/\bjpg\b/",$row['media1'])) || (preg_match ("/\bjpeg\b/",$row['media1'])) || (preg_match ("/\bpng\b/i",$row['media1'])) || (preg_match ("/\bgif\b/i",$row['media1']))){
echo '<img style="max-width:300px;" src="media/news/'.$row['media1'].'" class="floatRightClear" id="border">';
}
if((preg_match ("/\bjpg\b/",$row['media2'])) || (preg_match ("/\bjpeg\b/",$row['media2'])) || (preg_match ("/\bpng\b/i",$row['media2'])) || (preg_match ("/\bgif\b/i",$row['media2']))){
echo '<img style="max-width:300px;" src="media/news/'.$row['media2'].'" class="floatRightClear" id="border">';
}
if((preg_match ("/\bmp3\b/", $row['media1']))) {
echo ' <p id="audioplayer_'.$number1.'" class="floatRightClear">Media Content</p>
<script type="text/javascript">
AudioPlayer.embed("audioplayer_'.$number1.'", {soundFile: "http://kiddiessupportscheme.org/media/news/'.$row['media1'].'"});
</script>';
echo '<br>';
}
if((preg_match ("/\bmp3\b/", $row['media2']))) {
echo ' <p id="audioplayer_'.$number2.'" class="floatRightClear">Media Content</p>
<script type="text/javascript">
AudioPlayer.embed("audioplayer_'.$number2.'", {soundFile: "http://kiddiessupportscheme.org/media/news/'.$row['media2'].'"});
</script>';
echo '<br>';
}
echo stripslashes(nl2br($row['text']));
echo '<br><br>';
echo stripslashes($row['author']);
echo '</div>';
echo '<p align="right" id="seperater">Top<img src="images/seperater.jpg" width="950" height="6" style="border:none;" /></p>';
}
else {
echo '<div id="text">';
echo '<a name="'.stripslashes($row['title']).'" id="'.stripslashes($row['title']).'"></a>';
echo '<span class="kisstitle">'.stripslashes($row['title']).'</span><br>';
echo ' (';
echo $row['date'];
echo ')';
echo '<br>';
echo '<br>';
if((preg_match ("/\bjpg\b/",$row['media1'])) || (preg_match ("/\bjpeg\b/",$row['media1'])) || (preg_match ("/\bpng\b/i",$row['media1'])) || (preg_match ("/\bgif\b/i",$row['media1']))){
echo '<img style="max-width:300px;" src="media/news/'.$row['media1'].'" class="floatLeftClear" id="border">';
}
if((preg_match ("/\bjpg\b/",$row['media2'])) || (preg_match ("/\bjpeg\b/",$row['media2'])) || (preg_match ("/\bpng\b/i",$row['media2'])) || (preg_match ("/\bgif\b/i",$row['media2']))){
echo '<img style="max-width:300px;" src="media/news/'.$row['media2'].'" class="floatLeftClear" id="border">';
}
if((preg_match ("/\bmp3\b/", $row['media1']))) {
echo ' <p id="audioplayer_'.$number1.'" class="floatLeftClear">Media Content</p>
<script type="text/javascript">
AudioPlayer.embed("audioplayer_'.$number1.'", {soundFile: "http://kiddiessupportscheme.org/media/news/'.$row['media1'].'"});
</script>';
echo '<br>';
}
if((preg_match ("/\bmp3\b/", $row['media2']))) {
echo ' <p id="audioplayer_'.$number2.'" class="floatLeftClear">Media Content</p>
<script type="text/javascript">
AudioPlayer.embed("audioplayer_'.$number2.'", {soundFile: "http://kiddiessupportscheme.org/media/news/'.$row['media2'].'"});
</script>';
echo '<br>';
}
echo stripslashes(nl2br($row['text']));
echo '<br><br>';
echo stripslashes($row['author']);
echo '</div>';
echo '<p align="right" id="seperater">Top<img src="images/seperater.jpg" width="950" height="6" style="border:none;" /></p>';
}
$number1++;
$number1++;
$number1++;
$number2++;
$number2++;
$number2++;
$counter++;
}}
to your first problem:
First problem is if the news text doesn't fill all the space by the side of the news image, then the next news item gets displayed too soon (not below the orange breaker) as you can see on the site at the moment. I was thinking to get around this I could set the height of each news post div to the height of the image, although the image is a little shorter than the div so I'm not sure how I'd do that.
You only have to edit your css file:
Change:
#seperater {
float: left;
}
To:
#seperater {
clear: both;
}
For your second problem, I found this link: http://www.sitepoint.com/forums/3713338-post5.html There is exactly the solution you need.
Code from the link I posted above:
define( 'LINK_LIMIT', 30 );
define( 'LINK_FORMAT', '%s' );
function prase_links ( $m )
{
$href = $name = html_entity_decode($m[0]);
if ( strpos( $href, '://' ) === false ) {
$href = 'http://' . $href;
}
if( strlen($name) > LINK_LIMIT ) {
$k = ( LINK_LIMIT - 3 ) >> 1;
$name = substr( $name, 0, $k ) . '...' . substr( $name, -$k );
}
return sprintf( LINK_FORMAT, htmlentities($href), htmlentities($name) );
}
$s = 'Here is a text - www.ellehauge.net - it has some links with e.g. comma, www.one.com,
in it. Some links look like this: http://mail.google.com - mostly they end with a
space or carriage return www.unis.no
<br /> - but they may also end with a period: http://ellehauge.net. You may even put
the links in brackets (www.skred-svalbard.no) (http://one.com).
From time to time, links use a secure protocol like https://gmail.com |
This.one.is.a.trick. Sub-domaines: http://test.ellehauge.net |
www.test.ellehauge.net | Files: www.unis.no/photo.jpg |
Vars: www.unis.no?one=1&~two=2 | No.: www.unis2_check.no/doc_under_score.php |
www3.one.com | another tricky one:
http://ellehauge.net/cv_by_id.php?id%5B%5D=105&id%5B%5D=6&id%5B%5D=100';
$reg = '~((?:https?://|www\d*\.)\S+[-\w+&##/%=\~|])~';
print preg_replace_callback( $reg, 'prase_links', $s );

javascript for onClick not executing?

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)

on click change questions displayed

I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.

Categories