Link is cut after question mark in dynamic php table - php

I have a PHP dynamic table, and when I click on one of my link (http://www.xxxxxx.com/?r=xxxxxxxxx), the link open in a new tab and it's cut after the question mark (?), like www.xxxxxx.com/?.
Here is the table php code:
echo '<div class="row"><tr>';
echo '<td><form action='.$data['referral'].'>
<input class="btn" type="submit" formtarget="_blank" value='.$data['webadress'].' data-value='.gmdate("H:i:s",($data['timer']*60+60)).' data-start="false"></form></td>';
echo '<td>Now</td>';
echo '<td>'.$data['timer'].'</td>';
echo '<td>'.$data['payout'].'</td>';
echo '</tr></div>';
In my database, the $data['referral'] are my www.xxxxxx.com/?r=xxxxxxxxx link's.
I think is the type or something in my database option is wrong, so it cut after the question mark. Now I'm on varchar(255) and latin1_general_ci.
EDIT: I have put an input because I need store data for a timer, here is the JS:
$(window).load(function(){
var row = document.getElementsByClassName("color");
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
function redColor(element) {
$(element).css('background-color', 'rgba(255,0,0,0.7)');
}
function normalColor(elemen) {
$(element).css('background-color', 'transparent');
}
$('.btn').on('click', startTimer);
function startTimer() {
var dataStartElem = $(this);
var dataStart = dataStartElem.attr('data-start');
if (dataStart === 'false') {
dataStartElem.attr('data-start', 'true');
var nextElem = dataStartElem.parents('td').next();
var duration = dataStartElem.attr('data-value');
var a = duration.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
setInterval(function () {
seconds--;
if (seconds >= 0) {
nextElem.html(toTimeString(seconds));
redColor(nextElem);
}
if (seconds === 0) {
nextElem.html('Now');
dataStartElem.attr('data-start', 'false');
clearInterval(seconds);
normalColor(nextElem);
}
}, 1000);
}
}
});
This JS, start the timer and put it in red, and after the "now" appear when is finish.

By using a GET form, you override the query part of the action. Either convert your form to a normal link, or put the query part of the URL in a hidden input.

As #Otto said, try to do it in way near to this:
echo '
<div class="row">
<tr>
<td>
' . htmlspecialchars($data['webadress']) . '
</td>
<td>Now</td>
<td>' . $data['timer'] . '</td>
<td>' . $data['payout'] . '</td>
</tr>
</div>
';

Here is the solution, thanks to all have help me to figured out: i think it's the form who dont take "?" on link, so i have changed it to a normal link and here we go.
echo '<div class="row">
<tr>
<td>
<a href="'.$data['referral'].'" target="_blank">
<input type="submit" value="'.htmlspecialchars($data['webadress']).'" data-value="'.gmdate("H:i:s", ($data['timer'] * 60 + 60)).'" data-start="false" class="btn" formtarget="_blank">
</a>
</td>
<td>Now</td>
<td>'.$data['timer'].'</td>
<td>' . $data['payout'] . '</td>
</tr>
</div>';

Related

Stop page refresh on button click

I'm currently developing a system for internal use within my company to allow our service desk team to unlock user accounts/reset passwords.
I've completed the PHP/POST functions for this and have included them with the .load function on the dashboard of my system. This works and the function in question is LDAP account unlocks. The button is clicked, the post form is submitted and it all works fine. However it refreshes the entire page when submitted even though its been loaded via jQuery. I'm struggling to understand why this would happen, and how I can avoid it so I can give the end user successful or unsuccessful messages on button clicks. This is the main aim and is why I have started using JS load functions as I believed this would allow me to do so.
I'm entirely new to jQuery/JSON/JS and if this question is slightly in-descriptive or has an obvious answer apologies.
EDIT:
The way I have included the form is as such:
<div id="lockedout"></div>
<script>
$(document).ready(function(){
$("#lockedout").load('/modules/active-directory/includes/lockedout.php');
});
</script>
And the included form is:
<?php
set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
include ('/core/system/global.ldap.php');
$attributes = array("displayname", "mail", "samaccountname", "lockoutTime");
$filter = "(&(objectClass=User)(lockoutTime>=1)(title=*))";
$search = ldap_search($ldap_conn, $ldap_dn, $filter, $attributes) or die (ldap_error($ldap_conn));
$info = ldap_get_entries($ldap_conn, $search);
?>
<h4><i class="fa fa-lock"></i> Currently Locked Out (<?php echo $info["count"]; ?>)</h4>
<br>
<table class="table table-bordered">
<tbody><tr>
<th>Username</th>
<th>Unlock</th>
</tr>
<?php
for ($i=0; $i<$info["count"]; $i++) {
echo "<tr>";
echo "<td>" . $info[$i]["displayname"][0] . " (" . $info[$i]["samaccountname"][0] . ")</td>";
echo "</form><form method='post' action='/active-directory/' id='" . $info[$i]["samaccountname"][0] . "'></form>";
echo '<input type="hidden" name="dn" value="'. $info[$i]["dn"] .'" form="' . $info[$i]["samaccountname"][0] . '">';
echo "<td><center><button type='submit' id='unlock' name='unlock' class='btn btn-success btn-flat' form='" . $info[$i]["samaccountname"][0] . "'>Unlock </button></center></td>";
echo "</tr>";
}
?> </tbody></table>
This code is attached above the dashboard where i'm doing the JSON import.
<?php
if(isset($_POST['unlock']))
{
$attr["lockoutTime"] = "0";
$userdn = $_POST['dn'];
$result = ldap_modify($ldap_conn, $userdn, $attr);
echo '<script>
$(document).ready(function(){
$("#lockedout").load("/modules/active-directory/includes/lockedout.php");
});
</script>';
}
?>
if you want to submit content to backpage or verify users but not reload the entire page use AJAX.
if you want to simply show some alerts or validate form when you click the button use javascript or its derivatives

Refresh div contents without closing dropdown

I'm trying to learn php, mysql and javascript/jquery by building a live bidding system. I want to refresh the value of a bid button and dropdown automatically, but only if the value has changed. I've made a bidbuttons.php that outputs the buttons after querying the db for the current values, and I load and reload the page with this jquery I found elsewhere. I have tried several different methods of refreshing the div, and the best I came up with unfortunately closed the dropdown on the timer. This current version was described as exactly what I need but doesn't seem to work, in fact it logs me out. would prefer the div to refresh and the dropdown to close ONLY if the bidbuttons.php is updated. This is my first post, I hope I did this right.
<div id="bidbuttons"></div>
<script type="text/javascript">
var loadUrl = "includes/bidbuttons.php?id='.$item->id.'";
$("#bidbuttons").load(loadUrl).fadeIn("slow");
var auto_refresh = setInterval(function () {
$.get(loadUrl, function(data) {
if (data.changed) {
$("#bidbuttons").load(loadUrl).fadeIn("slow");
}
});
}, 10000);
</script>
and my bidbuttons.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$getid = (int)$_GET['id'];
// get current price
$result = $mysqli->query("SELECT ammount, bidder_id FROM bids WHERE ammount=(SELECT MAX(ammount)) && item_id like $getid order by ammount desc");
while($row = $result->fetch_assoc()) {
$bidder_id = $row["bidder_id"];
$current = $row['ammount'];
echo ($mysqli->error);
$result->free();
}
//get item info
$results = $mysqli->query("SELECT * FROM items WHERE id like $getid ");
while($row = $results->fetch_assoc()) {
if (empty ($current)) { $current = $row["start"];}
$title = $row["title"];
$item->thenext = ($current + $row["raise"]);
$buyout = $row["buyout"];
$raise = $row["raise"];
$sold = $row["sold"];
}
$results->free();
echo ('<div id="buttons">
<a class="btn btn-primary btn-lg" style="margin-bottom: 10px; margin-top: 10px; width: 80%;" href="includes\placebid.php?itemid=' . $getid . '&ammount=' . $item->thenext .'">Bid $' . $item->thenext . '</a>
');
if ($buyout){echo ('
<a class="btn btn-success btn-lg" style="margin-bottom: 10px; width: 80%;" href="includes\placebid.php?itemid='.$getid.'&ammount='.$buyout.'">Buyout $'.$buyout.'</a>
');}
echo '</div><!-- buttons -->';
echo ('
<div class="dropdown">
<button style="margin-bottom: 10px; width: 80%;" type="button" class="btn btn-info btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Custom Bid<span class="caret"></span></button>
<ul class="dropdown-menu">
');
// build the custom bid dropdown
if (!$buyout) { $maxcust = $item->thenext*25;
for ($cust = $item->thenext; $cust <= $maxcust; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
if ($buyout) {
for ($cust = $item->thenext; $cust <= $buyout; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
echo ('
</ul>
</div><!-- dropdown -->
');
}
mysqli_close($mysqli);
?>
I think the problem may be in that your PHP file is generating HTML which is continually replacing elements on your page due to them being loaded via AJAX.
Just an idea but you could make your PHP output a JSON instead that contains the database results, then have jQuery read the output. Your code would then process that JSON file and create or update the HTML elements accordingly (rather than replace them).
This way you have more fine grained control in the JavaScript for when your dropdown should close.
See this answer if you'd like to output from MySQLi to JSON.

Using jQuery function in a php while loop

I'm having trouble with a jQuery script for voting on posts. I have a "frontpage" with a list of posts from a mysql db. On each post there is a little votebox you can either vote up or down.
jQuery/ajax script:
<script type="text/javascript">
$(document).ready(function() {
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
$('.plus-button').html(data);
}
});
});
$('.minus-button').click(function(){
var postid = $(this).attr('id');
$('.plus-button').removeClass('liked');
$(this).toggleClass('disliked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=dislike&postid='+postid,
success: function(data){
$('.minus-button').html(data);
}
});
});
});
</script>
Votebox.php
<?php
// If postid is from frontpage use $postloopid as $postid
if(isset($postloopid)){
$postid = $postloopid;
}
$postid = htmlentities($postid, ENT_QUOTES);;
include("connect.php");
//For test purposes
echo $postid;
// If user logged in show votebox
if(isset($_SESSION['username'])){
$userid = $_SESSION['userid'];
$sql2 = mysqli_query($connect,"SELECT * FROM posts WHERE id='$postid' AND deleted=0");
if($sql2){
$voterow = mysqli_fetch_assoc($sql2);
$checkupvote = $voterow['upvoters'];
$checkdownvote = $voterow['downvoters'];
$checkupvote = explode(" ",$checkupvote);
$checkdownvote = explode(" ",$checkdownvote);
if($checkupvote = array_search($userid,$checkupvote) == true){
echo '<div class="plus-button liked" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
elseif($checkdownvote = array_search($userid,$checkdownvote) == true){
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button disliked" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
else{
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
}
else {
echo 'No result <br />';
}
}
else {
echo 'Cant find user';
}
?>
Frontpage:
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM posts WHERE totalupvotes < $trendmin AND deleted=0 ORDER BY added DESC LIMIT 0,10");
if($sql1){
while($row = mysqli_fetch_array($sql1)){
$postloopid = $row['id'];
?>
<div id="postlist">
<div style="width:400px; font-size:18px; font-weight:bold;">
<a target="_blank" href="post.php?id=<?php echo $row['id']; ?>"><?php echo $row['title']; ?></a>
</div><br />
<article class="slide"><?php echo nl2br($row['post']); ?></article>
<br />
<?php include("php/votebox.php"); ?>
<br />
by <a style="font-size:18px;" href="profile.php?id=<?php echo $row['submittedby']; ?>"><?php echo $row['submitteduser']; ?></a>
at <span style="font-size:12px;"><?php echo $row['added']; ?></span><span style="float:right; margin-right: 10px;"><a target="_blank" href="post.php?id=<?php echo $row['id']; ?>#commentfield"><?php echo $row['totalcomments']; ?> comments</a></span>
</div>
<?php
}
}
?>
The problem now is that when I click the votebox buttons it turns out I only get the postid from the first loaded post from the while loop. Another problem I have is that my total up- and downvotes changes in all the posts on the list, not the specific post.
Any ideas?
The Javascript code isn't in the loop, it can't reference postloopid. Or if it is, you're binding all buttons of the class every time through the loop, and clicking on them will run all the handlers, incrementing all the posts.
You should put the post ID as a data field in the button, and then access that from the Javascript:
echo '<div class="plus-button liked" data-postid="'+$postid+'" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" data-postid="'+$postid+'" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
Then your Javascript can do:
$('.plus-button').click(function(){
var postid = $(this).data('postid');
$(this).siblings('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
}
});
});
I made the following changes to the JS:
Use $(this).data('postid') to get postid.
Only remove the disliked class from the sibling minus button, not all minus buttons on the page.
Put the returned HTML just in this element, not in all plus buttons. I pass this in the context: parameter, so that the success function can refer to it.
Alright lets go through your jQuery code(just the like function):
Bind click handler to all elements with the class plus-button
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
Remove disliked class from all elements with class minus-button
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
Set inner html of all elements with class plus-button
$('.plus-button').html(data);
}
});
});
What you want is to store the postid as an attribute on the posts, then use
var postid = $(this).attr('postid')
only remove the disliked class from the current element
$(this)
.parents('{element containing plus and minus button}')
.find('.minus-button')
.removeClass('disliked')
;
store reference to the clicked element
var $this = $(this); // Cool guys do this right in the beginning and use only this variable instead of $(this)
then in your ajax success handler you want to set only the html of the button you clicked, so you may use the reference you stored in the parent function scope
$this.html(data);
EDIT in regards to infinite scroll script
When parts of your page are dynamic, you want to bind the click handler to a static parent element of the dynamic content using:
$("#postsParent").on('click', '.plus-button', function () {/*handler*/})

Getting #hashtag tweet count in PHP while loop

I am creating the web application of twitter #hashtag search where I want to integrating the following code.
https://github.com/henrahmagix/tweetCount/blob/master/total_tweets.html
(Note : Just copy/paste above code for getting demo)
The above link contains the code for getting the number of tweets for any search (Useful for hashtag trending).
And following is my code:
<table width="100%">
<tr>
<th>#Hashtag</th>
<th>Description</th>
<th>Tags</th>
<th>Participants</th>
</tr>
<?php
$i = 1;
$j = 1;
while ($row = mysqli_fetch_array($result)):
?>
<tr>
<td class="hashtd"><?php echo "#" . $row['hashtag']; ?></td>
<td class="hashtd"><?php echo $row['description']; ?></td>
<td class="hashtd">Show</td>
<td class="hashtd">
<script type="text/javascript">
submitTerms("<?php echo $row['hashtag']; ?>","1","0");
</script>
<div id="totalTweets">Total tweets: <span></span></div>
<div id="loading">Loading!</div>
<div id="pagesDone">Pages done: <span></span></div>
</td>
</tr>
<?php
$i++;
$j++;
endwhile;
?>
</table>
Here I am using tweetCount script for this :
<td class="hashtd">
<script type="text/javascript">
submitTerms("<?php echo $row['hashtag']; ?>","1","0");
</script>
<div id="totalTweets">Total tweets: <span></span></div>
<div id="loading">Loading!</div>
<div id="pagesDone">Pages done: <span></span></div>
</td>
In the tweetCount script they are using form and searching for one keyword after submitting the form and getting the tweetcount result from http://search.twitter.com/search.json?q=
But I want to call that on page load thats why I am calling the submitTerms() function for getting the real time tweet count. Because of I am calling script in while loop I cannot use "id" for totalTweet, loading and pagesDone div tag. I tried by adding "class" there but it's resulting same tweet count finally for all hashtag which is not correct.
Hope you get this. Need Help.
I recommend you to fork the total_tweets.html ans do some modifications to the JS code. This way you can pass a param to specify the #id div you want to target.
// total_tweets function
function getTweets(search, page, pageTotal, **hashtag**) {
$.getJSON( url + search + '&page=' + page + '&callback=?',
function(data) {
if( data.results.length != 0 && page != pageTotal ) {
$('#pagesDone'** + hashtag + **' span').html(page);
getData(data);
}
else {
showTotal(**hashtag**);
}
}
);
}
function showTotal(**hashtag**) {
$('#totalTweets'** + hashtag + **' span').html(beforeCounter + totalTweets + afterCounter);
$('#pagesDone'** + hashtag + **' span').html('0');
totalTweets = 0;
loading = false;
}
function submitTerms(**hashtag**) {
$('#totalTweets'** + hashtag + **' span').html('');
$('#pagesDone'** + hashtag + **' span').html('0');
search = encodeURIComponent($('#query').prop('value'));
page = $('#startPage').prop('value');
pageTotal = $('#pageTotal').prop('value');
if( search == '' ) {
alert('Please enter search query');
return;
}
if( page == 0 ) {
alert('0 not allowed as start page');
return;
}
loading = true;
getTweets(search, page, pageTotal, **hashtag**);
}
Then in your php file you would call it:
<td class="hashtd">
<script type="text/javascript">
**submitTerms("<?php echo $row['hashtag']; ?>");**
</script>
<div id="totalTweets<?php echo $row['hashtag'];">Total tweets: <span></span></div>
<div id="loading<?php echo $row['hashtag'];">Loading!</div>
<div id="pagesDone<?php echo $row['hashtag'];">Pages done: <span></span></div>
</td>

.load() little part without toggle

I have a conversations flow who is refresh with .load() of jQuery every 3 seconds.
This system work, but in each conversation I have an answer button who slide a form (textarea and submit button) with .toggle().
To display the flow, I use a while with PHP.
My issue is, when the is loading by .load(), and answer button is clicked, the form hide again and text contain too.
<div id="the_river_loading">
<?php
$sql_the_river = 'SELECT u.nickname, u.firstname, u.lastname, u.main_photo, u.locality,
id_conversation, id_messages, owner, participants, text, date
FROM users AS u
INNER JOIN the_river
ON u.nickname = owner
WHERE answer = 0
ORDER BY date DESC';
$result_the_river = mysqli_query($mysqli, $sql_the_river);
$count = 0;
while ($data_the_river = mysqli_fetch_assoc($result_the_river))
{
$count++;
echo '<div class="message_container_news">'; // Start block conversation
echo '<a href="/profile/' . $nickname . '" class="name_links" style="vertical-align: top; font-size: 16px;">
<img src="' . $main_photo . '" title="' . $name . '" class="members_actu_photo" />' . $name . '</a>
<span style="vertical-align: top">, ' . $locality . '</span><span style="float: right; font-size: 12px;">Posté le Octobre 25, 2012</span>
<p style="margin-top: 5px;">' . $data_the_river['text'] . '</p>
<div class="btnAnswer_nb">' . $count_answer . '</div> Answers
See conversation
<div class="btnAnswer_news" id="btnAnswer_news_id_' . $count . '">Reply</div>
<form method="post" id="display_form_id_' . $count . '" action="" style="display: none;">
<br />
<textarea name="answer_text"></textarea><br />
<input type="submit" name="answer_valid_id_' . $count . '" value="Post" />
</form>
</div>'; // End block conversation
}
?>
</div>
<script type="text/javascript">
$(".btnAnswer_news").live("click", function(){
var num_show = this.id.replace(/\D/g, "");
$("#display_form_id_" + num_show).toggle("fast");
});
var auto_refresh = setInterval(
function() {
$("#the_river_loading").load("/home" + " .message_container_news");
}, 3000
);
</script>
In pleasure of read you.
This is because if you load the content again into the container, the styles applied per js will get removed (because they were applied through style="" and this gets refreshed). You should move the Form and the Button to another Div, wich is not in the loading Div.
If I understand your problem correctly (you've not be very descriptive), you just want to not hide the form when clicking again, for that use show() instead of toggle() , so replace your following line:
$("#display_form_id_" + num_show).toggle("fast");
for this one:
$("#display_form_id_" + num_show).show("fast");
If you want to keep the text of the textarea, you can like so:
var auto_refresh = setInterval(
function() {
tx = $("#the_river_loading textarea[name='answer_text']").val();
$("#the_river_loading").load("/home" + " .message_container_news", function(){
$("#the_river_loading textarea[name='answer_text']").val(tx);
});
}, 3000
);

Categories