简体   繁体   中英

Set the value/text of a div using javascript/jquery - inside a php LOOP

I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys.

Objectives:

  1. Retrieve data from database.
  2. Set the value of an element using javascript/jquery (inside a loop) from the database.
  3. Make the value a link

I have this a_link column from links table with the ff. values:

- www.google.com

- https://www.google.com

- www.stackoverflow.com

And here is my code:

<?php
    $querylink = "SELECT * from links";
    $resultlink = mysql_query($querylink);

    while ($rowlink = mysql_fetch_array($resultlink))
    { 
     $thelink = $rowlink['a_link'];
?>

     <div class = "row">
         <span id = "linkhere"></span> 
     </div>

     <script>

        var link = "<?php echo $thelink; ?>";
        $("#linkhere").html(urlify(link));

        function urlify(text) {
           var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
           //var urlRegex = /(https?:\/\/[^\s]+)/g;
           return text.replace(urlRegex, function(url,b,c) {
               var url2 = (c == 'www.') ?  'http://' +url : url;
              // return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
              return '<a href="' +url2+ '" target="_blank">' + url + '</a>';
          }) 
        }

     </script>
<?php
    }
?>

Any help would be highly appreciated. Thanks.

That's not how it works, that's not how any of this works

Now let's assume that you really need to use Javascript to process your generated links (which is not).

You first need to separate your Javascript code from your PHP code. You will only use Javascript once you have fetched your data and generated some output.

I guess you just want some kind of working code

<?php
    $querylink = "SELECT * from links";
    $resultlink = mysql_query($querylink);

    while ($rowlink = mysql_fetch_array($resultlink)) : 
     $link = $rowlink['a_link'];
?>
     <div class="row">
         <a href="" data-url="<?php echo $link ?>"></a>
     </div>
<?php 
    endwhile;
?>

<script type="text/javascript">
    $(function() {
        $('.row a').each(function() {
            var urlified = urlify($(this).data('url'));
            $(this).attr('href', urlified.url)
                   .text(urlified.label);
        });
    });

    function urlify(text) {
        var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
        return text.replace(urlRegex, function(url,b,c) {
          var label = (c == 'www.') ?  'http://' +url : url;
          return {url: url, label: label};
        }); 
    }
</script>

@aimme is technically not wrong about using a different database library. Please read " Why shouldn't I use mysql_* functions in PHP? " for reasons why not to use mysql_ and for some neat alternatives, some tutorials, and some good reads. (yes, all in the same page! just scroll down)

I think you're trying to:

  • display a <div> of class 'row'
    • with an <a> tag inside that uses the 'a_link' column of the 'links' table as the href and the label.
      • The href for the tag must always have a scheme (http://).

Just PHP and HTML

<?php
    $querylink = "SELECT * from links";
    $resultlink = mysql_query($querylink);

    while ($rowlink = mysql_fetch_array($resultlink))
    { 
        $theLink= $rowlink['a_link'];
        $regexMatches = array();

        // removed (what seemed to be) needless groups in regex
        $urlFound = preg_match("@((https?:\/\/|www\.)[^\s]+)@",$theLink,$regexMatches);

        if($urlFound === 1) {
            // only add http:// if http:// was not detected
            $href = ($regexMatches[2] === "www." ? "http://" : "") . $theLink;
?>
    <div class="row">
        <a href="<?php echo $href; ?>" target="_blank"><?php echo $theLink; ?></a>
    </div>
<?php  }
    }
?>

This code won't echo a row if a_link doesn't contain either 'http://' or 'www.' in it. so google.com will not be displayed.

Of note, as written, the regex will work on "urls" like 'applewww.google.com'. Don't know if that matters. Adding a '^' to the beginning of the regex may solve the problem (like so: preg_match("@^((https?:\\/\\/|www\\.)[^\\s]+)@",$theLink,$regexMatches); )

A (better|different) solution could use parse_url($url)

<?php
    $querylink = "SELECT * from links";
    $resultlink = mysql_query($querylink);

    while ($rowlink = mysql_fetch_array($resultlink))
    { 
        $theLink= $rowlink['a_link'];

        $href = (parse_url($theLink,PHP_URL_SCHEME) === NULL ? "http://" : "") . $theLink;
    ?>
    <div class="row">
        <a href="<?php echo $href; ?>" target="_blank"><?php echo $theLink; ?></a>
    </div>
    <?php
    }
?>

However, using parse_url() would mean any old string would be displayed (while the first solution would not display any links that didn't have either http:// or www.) but since your pulling from a table called 'links' it's probably safe to assume everything is a valid path.

First i want to advice that use PDO or mysqli instead of mysql. as it is vulnerable to sql injection and its depreciated.

"I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys."

for that i would say Php is a server side language whereas javascript is a client side language. and Ajax is the way to manipulate client side from server vice versa, without refreshing the whole page.

below is just a demonstration that i edited little bit from your code to show the separation of server side and client side code and to just give an idea how it works.I don't know whether the code will work or not. haven't tested. php code (server side) will be executed first but could control the display of it using javascript(client side) functions inside document.ready() or window.load() to apply the affects as soon as possible.Through this we could bring changes to the links that we want before its being shown to the client . For each of the link retrieved and displayed you could use a specific class and jquery .each() function to apply certain fix to the selected link as Lyes BEN mentioned above or all the elements with a specific class could be manipulated as a whole without using .each.

<?php
    $querylink = "SELECT * from links";
    $resultlink = mysql_query($querylink);

    while ($rowlink = mysql_fetch_array($resultlink))
    { 
     $thelink = $rowlink['a_link'];
     echo '<div class = "row">
                <span id = "linkhere">
                    <a href="'.$thelink.'"></a>
                 </span> 
           </div>';
    }
?>
     <script>
        $("#linkhere a").html(urlify(link));

        function urlify(text) {
           var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
           //var urlRegex = /(https?:\/\/[^\s]+)/g;
           return text.replace(urlRegex, function(url,b,c) {
               var url2 = (c == 'www.') ?  'http://' +url : url;
              // return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
              return '<a href="' +url2+ '" target="_blank">' + url + '</a>';
          }) 
        }

     </script>

You can implement this using php with parse_url function ( http://php.net/manual/en/function.parse-url.php ) to get different components.

In parse_url, there is 'scheme' key for http or https.

Then to do this with php, just call formatUrl function to make the url

<?php 
 function formatUrl($url)
 {
    $urlData = parse_url($url);

    if(!isset($urlData['scheme'])) {
        $url = 'http://' . $url;
    }

    return '<a href="' . $url . '" target="_blank">' . $url . '</a>';
 }
?>

<?php
 $querylink = "SELECT * from links";
 $resultlink = mysql_query($querylink);

 while ($rowlink = mysql_fetch_array($resultlink))
 { 
  $thelink = $rowlink['a_link'];
 ?>

 <div class = "row">
     <span id="linkhere"><?php echo formatUrl($thelink)?></span> 
 </div>
 <?php
 }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM