How to turn an array of text into links? - php

I have an array of texts which I have kept in an array. The array is linked to a button and when that button is pressed, I'd like to open all the links in different tabs.
e.g
if(isset($_POST["open links"]))
{
foreach($array as $item)
{
<a href="$item" target="_blank" ></a>
}
}
The links are saved on a text file from a previous form and each item in the array is just the URL. How would I go about doing this?

How about trying to echo them
foreach($array as $item)
{
echo('<a href="' . $item . '" target="_blank" ></a>');
}
It prints the link tags with values of $item as target.

How about this
<?php foreach($array as $item)
{
?>
<script>
window.onload = function(){
window.open("<?=$item?>", "_blank"); // will open new tab on window.onload
}
</script>
<?php } ?>

To open multiple links at the same time you will need some (basic) javascript.
Try something like this:
<?php
$array = array( 'http://www.stackoverflow.com', 'http://www.google.com');
?>
<button id="my-button">Click me</button>
<script type="text/javascript">
var links = [
<?php
foreach($array as $i => $link)
echo '"' . $link . '"' . ($i < (sizeof($array) -1)? ',' : '');
?>
];
document.getElementById("my-button").onclick = function(){
links.forEach(function(link) {
window.open(link, '_blank');
});
}
</script>
Note that Chrome popup blocker doesn't let you programmatically open multiple new tabs at once, though. (Window.open isn't working for multiple links in Google Chrome)

consider your link file :-
links.txt
> http://google.com http://stackoverflow.com http://facebook.com
All links with sperated by space
then php code :-
<button id="my-button">Click me</button>
<script type="text/javascript">
document.getElementById("my-button").onclick = function(){
<?php foreach($links as $link) { echo"window.open(" . $link . ", '_blank');"; } ?>
}
</script>
Some code stolen from other answers :p , but that's a good practice ! Thanks :)

Related

PHP drop down menu, once clicked

I have created a drop down menu in php that is displayed however, when a value has been clicked, I don't know how to collect this information.
<html>
<body>
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
</body>
</html>
Based on your last comment, "i want it to be dynamic so as soon as the user clicks on something the relevant information will pop up", it sounds like you will probably want to use Ajax/JavaScript (I will demonstrate a simple jQuery example, notating for clarity):
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
?>
<html>
<!-- Add the jQuery library -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Act when the document is ready
$(function(){
// listen for the select to change
$('select[name=TeacherID]').on('change',function(){
// Run the ajax – you can also use the shortcut $.post method found at:
// https://api.jquery.com/jquery.post/
$.ajax({
// This is the page that is going to do the data lookup/display action
url: '/lookup.php',
// This is how it's sending the data to that page
type: 'post',
// This is what is being sent ($_POST['submit'] in this case)
data: {
// Use $(this) to isolate the current selected element and get value (.val())
// The value is represented as $topic in your php
'submit': $(this).val()
},
// If all goes well and the page (lookup.php) returns a response
success: function(response) {
// Place the response into the div (see html snippet)
$('#loadspot').text(response);
}
});
});
});
</script>
<body>
<?php
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
<!---------------------------------------------->
<!-- THIS IS WHERE THE CONTENT WILL LOAD INTO -->
<!---------------------------------------------->
<div id="loadspot"></div>
</body>
</html>
In order for this to work, you need the page lookup.php in the domain root (you can make it whatever/where ever you want, but you need to match in the javascript url):
/lookup.php
<?php
# This is what will get placed into the parent page <div id="loadspot"></div>
# Do you your php here in place of this line and return whatever "relative information" you want
print_r($_POST);
You should review the jQuery page I have linked to to get more information and direction for that library and make sure you use your browser's developer tools to monitor javascript errors in the console. Ideally, you want to understand all this via the documentation instead of just copy and paste and move on...

jQuery show div in PHP While loop

I am having a bit of problems trying to show an information in a div tag using jQuery inside the PHP while loop.
My code looks like this:
$i=1;
while($pack = mysql_fetch_array($packs))
{
$pricepack = $price * $pack['refcount'];
$pricepack = number_format($pricepack,2);
if($users > $pack['refcount'] ) {
$contents .= "
<a class='refbutton' style='text-decoration:none;' onclick=\"document.rent.refs.value='{$pack['refcount']}';document.rent.submit(); return false;\" >{$pack['refcount']}</a>
<div id='refinfo' style='display:none;'>
<span style='font-size:18pt;font-weight:bold;' id='refprice'></span><br />
<span style='color:#D01F1E;'>You don't have enough funds for this package.</span>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.refbutton').hover(
function() {
$('#refinfo').show();
$('#refprice').text(\"$\"+\"$pricepack\");
},
function() {
$('#refinfo').hide()
}
);
});
</script>
";
$i++;
}
}
The problem is that the code is generating a div next to each anchor element. This will cause this when the mouse hovers:
What I am trying to obtain is this on every button hover:
As you can see in the second picture, there isn't any design errors or mix-ups. How can I obtain this?
Thank you.
You need to start by cleaning up your code. You only need one refinfo div, and only one javascript block. The only thing in your loop should be the refbutton, and that tag should contain all the values needed for the javscript hover and click events to do their business. Look into HTML5 custom data attributes http://html5doctor.com/html5-custom-data-attributes/
Something more like this should work and provide a sounder basis on which to debug layout issues if any remain.
<?php
$i=1;
while($pack = mysql_fetch_array($packs)) {
$pricepack = $price * $pack['refcount'];
$pricepack = number_format($pricepack,2);
if($users > $pack['refcount'] ) {
$contents .= "
<a class=\"refbutton\" data-pricepack=\"{$pricepack}\" style=\"text-decoration:none;\" >{$pack['refcount']}</a>";
$i++;
}
}
?>
<div id="refinfo" style="display:none;">
<span style="font-size:18pt;font-weight:bold;" id="refprice"></span><br />
<span style="color:#D01F1E;">You don't have enough funds for this package.</span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.refbutton')
.bind('mouseover',function(event) {
$('#refinfo').show();
$('#refprice').text($(this).data("pricepack"));
})
.bind('click',function(event) {
document.rent.refs.value=$(this).text();
})
.bind('mouseout', function(event){
$('#refinfo').hide();
})
;
});
</script>

PHP Show/hide link

I have a function that prints out articles from my database and three links Edit , Add , Show/hide.
In the show/hide link i want to be able to hide/show that particular article.
How can i do that?
EDIT: I need to be able to hide/show articles in my backend page and it needs to stay hidden in the frontend page
function displaynews()
{
$data = mysql_query("SELECT * FROM news") // query
or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
$id = $info['id'];
echo "<br>
<a href=Edit.php?id=$id>Edit</a></a>
<a href='addnews.php'> Add </a>
<a href='#'>Show/Hide</a><br><strong>" .
$info['date'] .
"</strong><br>" .
$info['news_content'] .
"<hr><br>"; // Print Articles and Date
}
}
You could use some Javascript and set the style attribute to display:none to hide, then display:block to show it again. Or use jQuery.
Use jquery.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
show/hide
<div id="whatever">
Content
</div>
<script>
//Try these too
$('#whatever').hide();
$('#whatever').show();
$('#whatever').toggle();
</script>
Use following code:
PHP Code:
function displaynews()
{
$data = mysql_query("SELECT * FROM news") // query
or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
$id = $info['id'];
echo "<div class="news"><br><a href=Edit.php?id=$id>Edit</a></a><a href='addnews.php'> Add </a><a href=hide.php>Show/Hide</a><br><strong>". $info['date']."</strong><br>". $info['news_content'] . "<hr><br></div>"; // Print Articles and Date
}
}
Javascript/jQuery Code (Don't forget to add jQuery in your page)
<script type="text/javascript">
$(document).ready(function(){
$(".news").click(function(){
$(this).toggle();
});
});
</script>

onclick confirm function with different text from array

I am having an issue with attempting to show different confirm text from an array when using a hyperlink. The text always ends up being from the last confirmation text in the array. I have seen 2 examples on this forum using a function() in a function but I was not able to get this working from viewing the examples.
Here is my code:
echo '
<script type="text/javascript">
function getDetails(message)
{
if (confirm(message))
return true;
else
{
var links = document.getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].href = item_NoLink;
}
}
</script>';
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php;report='. $item['id'];
echo '
<script type="text/javascript">
var item_detail = ', json_encode($item['reported_spam']['detail']),'
var item_NoLink = ', json_encode('http://test_url/mytest.php;'),'
</script>
<a id="mylink[]" onclick="getDetails(item_detail);" href="'.$link.'" style="text-decoration:none;">
<img id="myImage" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
Thanks.
Edit: I figured it out.
#Grant Zhu: Arrays are not written like that in php and one can progress to the next key just using the empty square brackets. You were correct as I did make an err for the image id array and the js variables. Also for php when using single quotes inside echo with single quotes one must use the backslash (unless using php again).
I got it working as such:
echo '
<script type="text/javascript">
var item_NoLink = ', json_encode('http://test_url/mytest.php;'),'
function getDetails(message)
{
if (confirm(message))
return true;
else
{
var links = document.getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].href = item_NoLink;
}
}
</script>';
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php?report='. $item['id'];
echo '
<a id="mylink[]" onclick="getDetails(\'',$item['reported_spam']['detail'],'\');" href="'.$link.'" style="text-decoration:none;">
<img id="myImage[]" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
Thank you.
$link = 'http://test_url/mytest.php;report='. $item['id'];
this code is weird , I think your code might be
$link = 'http://test_url/mytest.php?report='. $item['id'];
You should check the javascript generated and you will find there're multiple declarations of item_detail and item_NoLink. That means you assign the values to the same variables again and again. Of course, the last assignment takes effect in the end.
You can put the detail text directly in the getDetails function. Make sure the text is quoted by '. And you'd better make the id of <a> and <img> unique because that's what id means. I'm not familiar with PHP, check the syntax below if it's correct.
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php;report='. $item['id'];
echo '
<a id="mylink$item['id']" onclick="getDetails(', json_encode($item['reported_spam']['detail']),');" href="'.$link.'" style="text-decoration:none;">
<img id="myImage$item['id']" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}

Passing a variable from jquery to php

I am trying to pass a variable from jquery to php
My jquery code:
<script>
$(window).load(function(){
$.get("as.php",url="http://www.wired.co.uk/news/archive/2013-01/10/chinese-desert-mystery", function(data,status){
$('#lax').html(data);
});
});
</script>
<div id="lax" >
</div>
And my "as.php" file is as follows:
<?php
include('phpQuery.php');
$file = mysqli_real_escape_string($dbc, strip_tags(trim($_GET['url'])));
phpQuery::newDocumentFileHTML($file);
$titleElement = pq('title');
$title = $titleElement->html();
echo '<a href="" >' . htmlentities( $title) . '</a><br/>';
foreach(pq('meta') as $li)
if ((pq($li)->attr('name')=='description')||(pq($li)->attr('name')=='Description')){
echo '<p>'.pq($li)->attr('content').'</p>';
}
?>
I am tryin to pass 'url' variable from jquery code to my "as.php" file , but not able to do so. Where must be I going wrong?
You need to create an object
url="http://www.wired.co.uk/news/archive/2013-01/10/chinese-desert-mystery"
Should be:
{url :"http://www.wired.co.uk/news/archive/2013-01/10/chinese-desert-mystery"}
jQuery docs
I don't see you opening a database connection, so with the code you posted $dbc will be NULL.
That causes mysqli_real_escape_string to return NULL as well.
As you are not doing any database operations, you should get rid of mysqli_real_escape_string completely.
in you jquery:
<script>
$(window).load(function(){
$.get("as.php",
{url:"http://www.wired.co.uk/news/archive/2013-01/10/chinese-desert-mystery"}, function(data){
$('#lax').html(data);
});
});
</script>
in your php try using $_REQUEST
<?php
include('phpQuery.php');
$file = mysqli_real_escape_string($dbc, strip_tags(trim($_REQUEST['url'])));
phpQuery::newDocumentFileHTML($file);
$titleElement = pq('title');
$title = $titleElement->html();
echo '<a href="" >' . htmlentities( $title) . '</a><br/>';
foreach(pq('meta') as $li)
if ((pq($li)->attr('name')=='description')||(pq($li)->attr('name')=='Description')){
echo '<p>'.pq($li)->attr('content').'</p>';
}
?>

Categories