onclick confirm function with different text from array - php

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>';
}

Related

PHP if variable contains string or multiple words

I have these two variables
$page_title = '[[+pagetitle]]';
$title_match = 'Marketing Campaign Calendar';
The first is pulling the name of an asset or page and the second are three words I want to search for within those titles. I currently have this if statement which works perfectly as is but I need to add another condition.
if(in_array($content_name, $open_modal_types)) {
// Return view / download buttons
return '<div class="button-group">
<a href="[[~[[+id]]]]"
class="button secondary open-modal"
data-mfp-src="#document-modal"
data-title="[[+pagetitle]]"
data-type="' . $content_name . '"
>View</a>
<a href="[[~[[+id]]]]" class="button secondary" download>Download</a>
</div>';
}
else if($is_binary == '1') {
// Return download button
return '<a href="[[~[[+id]]]]" class="button secondary" download>Download</a>';
}
So I'm trying to accomplish something like this:
if(in_array($content_name, $open_modal_types)) {
// Return view / download buttons
if($page_title contains all of the words in $title_match) {
return "something";
}else{
return '<div class="button-group">
<a href="[[~[[+id]]]]"
class="button secondary open-modal"
data-mfp-src="#document-modal"
data-title="[[+pagetitle]]"
data-type="' . $content_name . '"
>View</a>
<a href="[[~[[+id]]]]" class="button secondary" download>Download</a>
</div>';
}
}
else if($is_binary == '1') {
// Return download button
return '<a href="[[~[[+id]]]]" class="button secondary" download>Download</a>';
}
I've tried using strpos and preg_match but couldn't get it to work. I don't know if I have too many if statements or what. Any suggestions will be helpful.
Thanks
You can use a function like this
<?php
$words = "test1 test2 test3";
function containsAllWords($title, $words) {
$arrWords = explode(" ", $words);
foreach ($arrWords as $word) {
if (strpos($title, $word) === false) {
return false; // one word is not found, so it doesn't contain ALL
}
}
return true; // if we got here, it contains all the words
}
var_dump(containsAllWords("test1 test2 test4", $words)); // false
var_dump(containsAllWords("test1 test2 test3 test4", $words)); // true
may be instead of this
if($page_title contains all of the words in $title_match)
use preg_match:
$title_match = '('.str_replace(' ',')&(', $title_match).')';
if(preg_match('/'.$title_match.'/i', $title_match))
But you should be sure that $title_match not contains special symbols, or filter it by \
So the site I am working on is built in Modx which is fairly new to me. Instead of my original solution I was trying to attempt, I created a new content type within the CMS and wrote my modifications for that content type only. This makes much better sense than what I was trying to do before.
Any other Modx users out there, feel free to reach out to me if you want more details on my solution and what I was trying accomplish.
Thanks to those for trying to help.

How to turn an array of text into links?

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 :)

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>

[] operator not supported for strings. It happens JUST in one page [duplicate]

This question already has answers here:
Fatal error: [] operator not supported for strings
(9 answers)
Closed 7 years ago.
I wrote (thanks to Stackoverflow help, too) a PHP script (called wunder_temp.php) which shows the temperature and location for a given number of Weatherunderground.com Stations.
I included this script in my footer, and it works well BUT on a single page.
If I open http://www.flapane.com/guestbook/guestbook.php the temperatures won't be shown in my footer, and error.log says:
[09-Sep-2012 09:46:45 UTC] PHP Fatal error: [] operator not supported for strings in /home/xxx/public_html/wunder_temp.php on line 47
$display = file($cachename, FILE_IGNORE_NEW_LINES); //ignore \n for non-reporting stations
foreach ($display as $key=>$value){
if($key % 2 == 0){
$temperature[] = $value; // EVEN (righe del file cache pari)
}else{
$location[] = $value; // ODD - **HERE IS LINE 47**
}
}
The weird thing is that guestbook.php is the ONLY page of my website where wunder_temp.php doesn't work.
What the above code does is reading the cachefile and put in a $temperature[] array the even lines and in $location[] array the odd lines.
Here's a sample from my cachefile:
26.8
Stadio San Paolo di Napoli, Napoli
24.4
Pozzuoli
Honestly I don't know why I see that errors just on my guestbook page.
It turns out that the "culprit" is the function loadmore.php which loads the guestbook comments (and which is included in guestbook.php) using a twitter-style ajax function. If I don't include it, wunder_temp.php works well, and it doesn't produce any error.
loadmore.php:
<div id='contcomment'>
<div class="timeline" id="updates">
<?php
$sql=mysql_query("select * from gbook_comments ORDER BY id DESC LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['id'];
$name=$row['name'];
$url=$row['url'];
$email=$row['email'];
$location=$row['location'];
$date= strtotime($row['dt']); //unix timestamp
$country_code=$row['country_code'];
$message=$row['body'];
$link_open = '';
$link_close = '';
if($url){
// If the person has entered a URL when adding a comment,
// define opening and closing hyperlink tags
$link_open = '<a href="'.$url.'" target="_blank" rel="nofollow">';
$link_close = '</a>';
}
// Needed for the default gravatar image:
$url_grav = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
// Show flags
$image = strtolower($country_code) . ".png";
if (file_exists("./img/flags/" . $image)){
$show_image = true;
$image_link = "<img src='/guestbook/img/flags/$image' alt='user flag' />";
}else{
$show_image = false;
}
echo '<div class="comment">
<div class="avatar">
'.$link_open.'
<img src="http://www.gravatar.com/avatar/'.md5($email).'?size=50&default='.urlencode($url_grav).'" alt="gravatar icon" />
'.$link_close.'
</div>
<div class="name">'.$link_open.$name.$link_close.' </div><div class="location"><i>(da/from '.$location.' '.$image_link.' )</i></div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$date).'">'.date('d M Y',$date).'</div>
<p>'.$message.'</p>
</div>' ;
} ?>
</div>
<div id="more<?php echo $msg_id; ?>" class="morebox">
Carica Commenti più vecchi / Load older entries
</div>
</div>
ajax_more.js AJAX twitter-style load-more-comments function:
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('Nessun altro commento / No more comments');
}
return false;
});
});
ajax_more.php (needed by the above script):
<?
include "connect.php";
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$lastmsg=mysql_real_escape_string($lastmsg);
$result=mysql_query("select * from gbook_comments where id<'$lastmsg' order by id desc limit 9");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['id'];
$name=$row['name'];
$url=$row['url'];
$email=$row['email'];
$location=$row['location'];
$date= strtotime($row['dt']); //unix timestamp
$country_code=$row['country_code'];
$message=$row['body'];
$link_open = '';
$link_close = '';
if($url){
// If the person has entered a URL when adding a comment,
// define opening and closing hyperlink tags
$link_open = '<a href="'.$url.'" target="_blank" rel="nofollow">';
$link_close = '</a>';
}
// Needed for the default gravatar image:
$url_grav = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
// Show flags
$image = strtolower($country_code) . ".png";
if (file_exists("./img/flags/" . $image)){
$show_image = true;
$image_link = "<img src='/guestbook/img/flags/$image' alt='user flag' />";
}else{
$show_image = false;
}
echo '<div class="comment">
<div class="avatar">
'.$link_open.'
<img src="http://www.gravatar.com/avatar/'.md5($email).'?size=50&default='.urlencode($url_grav).'" alt="gravatar icon" />
'.$link_close.'
</div>
<div class="name">'.$link_open.$name.$link_close.' </div><div class="location"><i>(da/from '.$location.' '.$image_link.' )</i></div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$date).'">'.date('d M Y',$date).'</div>
<p>'.$message.'</p>
</div>' ;
}
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
Carica Commenti più vecchi / Load older entries
</div>
<?php
}
?>
Any help is appreciated
$location is already a string on that page. This is why you properly initialize variables before you use them:
$temperature = $location = array();
foreach ($display as $key => $value){
if ($key % 2 == 0){
$temperature[] = $value;
} else {
$location[] = $value;
}
}
Even better, separate your variable scopes better so you don't get a name clash like that. Use functions and classes with their private variable scopes and don't put everything in the global scope.
It seems a matter of variable scope.
When you include loadmore.php in guestbook.php you are implicitly declaring $location as a string:
$location=$row['location'];
So this line of your loop:
$location[] = $value; // ODD - **HERE IS LINE 47**
is not implicitly declaring a new array variable on the first iteration but trying to append $value to the previously declared string variable, hence the error.
Try giving a different name to $location either in loadmore.php or guestbook.php or making loadmore.php a function (so it runs in its own scope) and then call it from your guestbook.php script after including its code on it. Or use explicit declaration of $location variable if you want to reuse it as an array (just add $location = array(); before the loop).
I think that loadmore.php and/or ajaxmore.php are setting a global variable ($location) to a string. When the guestbook page tries to index this variable you get the error.
Solution: use functions and local variables.
$location=$row['location']; is the issue. Because PHP doesn't have block level scope, you are essentially pre-setting this variable and trying to set it's array index using []. Because it's a string, that will break.
You should always initialize your variables to avoid these kinds of conflicts:
i.e.
$location = array();
Rename $location for one of the scripts. You have $location=$row['location'] somewhere. Also, declare the variable when using it as an array:
$array = array();
$array[] = 'item'; // when you add an item here, $array will always accept an array push.

PHP jQuery Post - returns too much HTML

I have a problem when using jQuery Post, the PHP returns all the HTML of the page up to the newly created HTML, rather then just the HTML that is output by the PHP.
As an example say the php outputs: '<div>Some Content</div>'
Then the jQuery Post returns: '<html><head>...all the head content...</head><body>...other content...<div>Some Content</div>'
Here's the jQuery (link to full code: http://pastebin.com/U7R8PqX1):
jQuery("form[ID^=product_form]").submit(function() {
var current_url = js_data.current_url;
form_values = jQuery(this).serialize();
jQuery.post(current_url+"?ajax=true", form_values, function(returned_data) {
jQuery('div.shopping-cart').html(returned_data);
}
});
return false;
});
And here's the PHP (version 5.3.6 - link to full code: http://pastebin.com/zjSUUbmL):
function output_cart()
{
ob_start();
echo $this->output_cart_html();
$output = ob_get_contents();
ob_end_clean();
echo $output;
exit();
}
function output_cart_html() {
if (!isset($_SESSION['cart_items']))
{
$output = '<div class="cart_content faded">BASKET - Empty</div>';
return $output;
} else {
$total_items = 0;
$total_items = 0;
$items_in_cart = $_SESSION['cart_items'];
// work out total price and total items
foreach ($items_in_cart as $item_in_cart) {
$total_items += $item_in_cart['quantity'];
$total_price += floatval($item_in_cart['updated_price']*$item_in_cart['quantity']);
}
$template_url = get_bloginfo('template_directory');
$output = '';
$output_price = $dp_shopping_cart_settings['dp_currency_symbol'].number_format($total_price,2);
if($total_items == 1){ $item_text = ' Item'; } else { $item_text = ' Items'; }
$output .= $total_items . $item_text;
$output .= ' <span class="bullet"></span> Total '.$output_price;
// empty cart btn
$output .= '<form action="" method="post" class="empty_cart">
<input type="hidden" name="ajax_action" value="empty_cart" />
<span class="emptycart"> <img src="'.$template_url.'/images/empty.png" width="9" height="9" title="Empty Your Items" alt="Empty Your Items" />Empty Your Cart</span>
</form>';
// check out btn
$output .= ' <span class="bullet"></span> <span class="gocheckout">'.$this->output_checkout_link().' </span>';
return $output;
}
}
You need to check if the form has been posted yet with the PHP. To do this, just check if the 'ajax' parameter is there, or send another $_GET variable if you wish (by adding &anotherparementer=1 to the end of the jQuery post URL). Example:
<?php
if(isset($_GET['ajax'])) {
//your PHP code here that submits the form, i.e. the functions that you have, etc.
}
else {
?>
<html>
<head>
head content here...
</head>
<body>
body content here...
</body>
</html>
<?php
}
?>
I hope this helps.
Ok it turns out my problem was with the way Wordpress processes AJAX requests. The plugin I was building on top of was using AJAX but didn't have these issues (I'm not sure why maybe because they were using eval), so I hadn't realised there was a correct way of using AJAX with Wordpress. Here's a bunch of information if anyone else has similar problems:
http://codex.wordpress.org/AJAX_in_Plugins
http://byronyasgur.wordpress.com/2011/06/27/frontend-forward-facing-ajax-in-wordpress/
(this one really helped me out, a very simple example that I was able to adapt)
-- sorry I couldn't post more links because I'm too new on this site, but check out the links at the bottom of the first link above, especially the '5 Tips'.
As I'm using classes I instantiated the class from the index file of my plugin with this:
if ($_POST['action'] === 'action_name') {
$class_obj = new \namespace_name\class();
add_action('wp_ajax_action_name', array($class_obj, 'method_name'));
add_action('wp_ajax_nopriv_action_name', array($class_obj, 'method_name'));
}

Categories