Changing all links with jquery - php

I want to take things from another site and add href's a link. But my JQuery code just took the first href and change every hrefs' with that.
The code takes a table and tag. I just want to add a link in front of href.
I mean first href is like "example/example1" and I want to change it like "https:example.com/example/example1".
PHP cUrl code:
<?php
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,"https://www.planetdp.org/subtitlelist?translator=Kill+Master");
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
$sonuc = curl_exec($curl);
preg_match_all('#<td class="subtitle1">(.*?)</td>#si',$sonuc,$info);
$info = $info[0];
echo '<ul class="movie-name">';
for($i=0; $i < count($info);$i++){
echo '<li class="content">';
echo $info[$i];
echo '</li>';
}
echo '</ul>';
?>
And JQuery code:
$(".alert-link").attr("href");
var href = $(".alert-link").attr("href");
$(".alert-link").attr("href", "https://planetdp.org"+href);

You need to iterate through all the classes you want to change href on
$('.alert-link').each(function() {
var value = $(this).attr('href');
$(this).attr("href", "https://planetdp.org"+href);
});

Tested working good. Hope this help you.
$('a').each(function() {
var value = $(this).attr('href');
$(this).attr("href", "https://planetdp.org"+href);
});

Related

Drop down list in PHP and MySQL

I need to make drop down list as a link to different pages. How do I do that using PHP, MySQL and HTML.
<?php
mysql_connect('localhost','root','');
mysql_select_db('test');
$sql="select first_name from users";
$result=mysql_query($sql);
echo "<select First_name=''>";
echo "<a href='index.html'>";
while($row=mysql_fetch_array($result)){
echo ":<option value='".$row['first_name']."'>".$row['first_name']."</option>";
}
echo"</a>";
echo"</select>";
?>
You can't use links on the option tag, in order to do that, you need to use javascript.
You can try to do something like this:
echo "<select name=\"First_name\" onchange=\"document.location='?'+this.value\">";
PHP is a server-side script and does not manipulate a page after a user has adjusted it. Like real time. Only javascript and others do that. PHP creates a page with what you want to see but if you need to change something bases on a dropdown use java. Here is a function that can do that. It unhides a div tag that can have your info you need.
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('dropdown');
var divtag1 = document.getElementById('divtag1');
var divtag2 = document.getElementById('divtag2');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 1) {
divtag1.style.display = 'block';
}
if(eSelect.selectedIndex === 2) {
divtag2.style.display = 'block';
}//or if you want it to open a url
if(eSelect.selectedIndex === 3) {
window.open("https://yourwebsite.com", "_NEW");
}
}
}
</script>
echo "<div id=\"divtag1\" style=\"display:none;\">/*your code*/
</div>";
echo "<div id=\"divtag2\" style=\"display:none;\">/*your code*/
</div>";

jQuery add 1 up with a php foreach loop

So I have this php foreach-loop that gets data from my database.
I use a $i++ to number up the same div.
$i=0;
foreach ($pages as $page){
echo '<div class="class_'.$i++.'">
echo '</div>';
}
Now I have a piece of jQuery in my footer that does something to the <div>
<script>
jQuery(document).ready(function($){
$('.class_1');
$('.class_2');
$('.class_3');
});
</script>
Because I will never know how many instances there are I want the jQuery to add up with the foreach-loop but the script is outside the loop so it won't add up.
I don't really know my jQuery that much so any help would be appreciated.
M.
You can get every element with that class and then use $.each for it.
$('[class^="class_"]').each(function() {});
$i=0;
foreach ($pages as $page){
echo '<div class="class_'.$i++.'">';
echo '</div>';
}
echo '<div number-of-divs=' . $i . ' style="display:none;"/>';
Your js code:
<script>
jQuery(document).ready(function($){
var number = $('div[number-of-divs]').attr('number-of-divs');
for (i = 1; i <= number; i++) {
$('.class_' + i);
}
});
</script>
A good approach for this is you should pass another class in your code or pass this only if above is the only case. $('[class^="class_"]').each(function() {}); This will not work in some cases so use below code
$i=0;
foreach ($pages as $page){
echo '<div class="catch_me class_'.$i++.'">
echo '</div>';
}
and get it from this script
$('.catch_me').each(function(){
//You code here
});

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

Jquery/ Javascript getting information from PHP scope issue?

I am trying to get some information from our database and then use it in javascript/JQuery and I think I might be doing something wrong with the scope of the coding.
Here is the current segment of code on my phtml page (magento)
<script type="text/javascript">
<?php
echo 'var $image-paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image-paths[';
echo $i;
echo '] = ';
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo ';';
}
?>
document.getElementById('main-image').href = $image-paths[1];
</script>
The bottom getElementById is just for testing to see if it really grabbed that image path. So far the php stuff is working and echo'ing the correct links. However, is simply echo'ing them not enough; does it actually register it into the javascript code?
Here is what my source code looks like on my server:
<script type="text/javascript">
var $image-paths = new Array();
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
$image-paths[1] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64566-a.jpg;
$image-paths[2] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64568-a.jpg;
$image-paths[3] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-D43114-a.jpg;
document.getElementById('main-image').href = $image-paths[1];
</script>
But the image link does not change to image-path[1]. Any ideas?
Thanks in advance!
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
^-- no quote here, or at the end of the string
You're producing invalid javascript. Pop up your javascript console (shift-ctrl-J in chrome/firefox) and you'll see the error.
Producing javascript dynamically is problematic. Anytime you insert something from a PHP variable/function, you should run that through json_encode(), which guarantees you get valid javascript:
echo json_encode($this->helper('catalog/image')->init($_child_products[$i], 'image'));
Or better yet, change the code to:
$links = array();
for ($i = 0; $i < count ($_child_products); $i++)
$links[] = $this->helper('catalog/image')->init($_child_products[$i], 'image');
}
echo '$image-paths = ', json_encode($links);
<script type="text/javascript">
<?php
echo 'var $image_paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image_paths[';
echo $i;
echo '] = "'; // Here the starting of quotes.
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo '";'; // Here the ending of quotes.
}
?>
document.getElementById('main-image').href = $image_paths[1];
</script>
This should work now. Hope it helps.

PHP and jquery, help passing PHP variable to javascript

I am trying to allow the users of my website, to upload images and then select one to be a back image, the uploading works fine, but I have a problem in my controller or view I think, i would appreciate it some could help me out,
VIEW:
<div id="background-select">
<?php
$count = 0;
if(isset($special)) {
foreach ($special as $row) {
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
$background = $row['background_name'];
echo $background;
}
}
if(isset($generic)) {
foreach ($generic as $row) {
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
$background = $row['background_name'];
echo $background;
}
}
if(isset($user_background)) {
foreach ($user_background as $row) {
print '<div class="select">';
print "<a class='background_btn' href='index.php/home/set_background/".$row['background_id']."'>$count</a>";
print '</div>';
$background = $row['background_name'];
echo $background;
}
}
?>
</div>
<script type="text/javascript">
$("a.background_btn").click(function(ev){
ev.preventDefault();
alert("hello");
var url = $(this).attr("href");
alert(url);
$.ajax ({
url : url,
type: "POST",
success : function (html) {
alert("<?php echo $background; ?>")
$('#wrapper').css('background', 'url(/media/uploads/backgrounds/<?php echo $background; ?>)');
}
})
});
</script>
<div id="wrapper">
CONTROLLER:
public function set_background() {
$this->load->model('image_model');
if($query = $this->image_model->get_background_by_id($this->uri->segments[3])) {
//die(var_dump($query));
foreach ($query as $row) {
$data['background'] = $row['background_name'];
}
}
$this->load->view('template/background-select', $data);
}
The problem is that I can only set the background to the first returned value for example if the first loop return $background to = red.png then I cannot get anything but red.png to load in.
Can any one suggest a solution?
You appear to load a background using AJAX. However, you set the value of $background in the initial request, and the 'success' method of your AJAX call never uses the returned HTML. Only the background that was originally set when the page was first loaded. You should make sure your AJAX call returns the background, so you can use that in your javascript. Don't try to set the background in your 'success' method using PHP.
Also, not sure about this though, but your controller seems to set a single property $data['background'], overwriting it every iteration of the foreach instead of creating an array or hashmap.
I think you should keep separate PHP and JS. After completed upload process you can redirect (or show dynamically by using AJAX) uploaded images page. After user clicked an uploaded image just change background attribute maybe like this:
<div id="back">
<img src="foo.jpg" alt="..." />
<img src="bar.jpg" alt="..." />
...
</div>
$(function(){
$("#back img").bind("click", function(e){
var src = $(this).attr("src");
$("#back").css({"background-image": "url(/images/" + src + ")"});
});
});

Categories