How to implement a jQuery script to move links

Ok, let’s start with the <div> sortable thing.

What is the PHP code you are using to generate the page?

Thank you. This is the entire code i use in the index.php file: If you like you can download all the files i use for this script here: https://dl.dropboxusercontent.com/u/3182310/list_sort/temp.rar

&lt;?php
require("../config.php");
if ($enablegzip == "1")
{
ob_start("ob_gzhandler");
header("Content-Encoding: gzip");
}
session_start();
?&gt;
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;meta name="viewport" content="width=device-width, target-densitydpi=high-dpi"&gt;
&lt;title&gt;Web links - List (&lt;?php echo basename(dirname(__FILE__));?&gt;)&lt;/title&gt;
&lt;link rel=StyleSheet href="style.css" type="text/css"&gt;
&lt;script type="text/javascript" src="../collapse_expand_single_item.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="../jquery-1.11.1.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;br&gt;
&lt;div class="link_back"&gt;
&lt;a href="../index.php"&gt;Back to Index&lt;/a&gt;&lt;/div&gt;
&lt;br&gt;
&lt;div class="add_link"&gt;
&lt;a href="#first" onClick="shoh('first');"&gt;Add new link +&lt;/a&gt;&lt;/div&gt;
&lt;br&gt;
&lt;div class="index_letter"&gt;&lt;?php echo basename(dirname(__FILE__));?&gt;&lt;/div&gt;
&lt;div class="add_links" style="display: none;" id="first"&gt;
&lt;div class="box"&gt;
&lt;br&gt;
&lt;form action=addurl.php method=POST name="addurlform"&gt;
&lt;div class="box_title"&gt;Title:&lt;/div&gt;&lt;input type=text name=text size="56"  placeholder="Enter your title"&gt;
&lt;div class="box_link"&gt;Drag & Drop Link:&lt;/div&gt;&lt;input type=text value="" name=link size="56" placeholder="http://"&gt;
&lt;div&gt;
&lt;br&gt;&lt;br&gt;
&lt;input type=submit class="add_button" value="Add"&gt;&lt;/div&gt;
&lt;/form&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;
&lt;?php
$gbfile='links.txt';
$separator= '|';
//====================================
//This function will add one line to 
//the end of file
//====================================
function add($str){
global $gbfile;
      $tmp = trim($str);
      $fp=fopen($gbfile,'a+'); 
           flock($fp, LOCK_EX); 
                fwrite($fp, $tmp. "\
"); 
           flock($fp, LOCK_UN); 
      fclose($fp); 
}
//====================================
//Function below gets specified number
//of lines and returns an array
//====================================
function get($start, $end){
global $gbfile;
      $records=array(); 
      $filename="links.txt"; 
	  $fp=fopen($gbfile,'r'); 
           flock($fp, LOCK_SH); 
           $i=1; 
           $tmp=TRUE;
           while($i&lt;$start && !feof($fp)) {
                $tmp=fgets($fp);
                $i++;
           }
           while($i&lt;=$end && !feof($fp)) {
                $tmp=trim(fgets($fp));
                if ($tmp) { array_push($records, $tmp); }
                $i++;
           }
           flock($fp, LOCK_UN); 
      fclose($fp); 
      return($records);
}
//Listing part
$start=$_GET['start'];
$end=$_GET['end'];
if (!$end || $start&lt;=0) { $start=1; }
if (!$end) { $end=$linkspage; }
if ($end&lt;$start) { $end=$start+1; }
$show=$end - $start;

//Get records from file into array
      $records = get($start, $end);
	  sort($records);

//For each record get each field
      foreach ($records as $rec) {
           $tmp = explode($separator, $rec);
$title = $tmp[0];
$link = $tmp[1];
//=================================
//Outputting
?&gt;
&lt;div id="sortable"&gt;
&lt;div class="wraper"&gt;
&lt;a href="&lt;?=$link?&gt;"&gt;
&lt;p class="title"&gt;&lt;?php echo ("$title");?&gt;
&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;
&lt;?php
}
{
      $start+=$show;
	  $end+=$show;
	  $start++;
	  $end++;
	  $start--;
	  $end--;
}

?&gt;
&lt;/div&gt;
&lt;script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"&gt;&lt;/script&gt; 
&lt;script&gt;
$("a[href^='http']").each(function() {
    $(this).css({
		background:"url(http://g.etfv.co/"+ this.href +") left center no-repeat",
		"-webkit-background-size": "20px",
		"-moz-background-size": "20px",
		"-o-background-size": "20px",
		"background-size": "20px",
		"padding-left": "20px",
		"margin-left": "56px"
	});
});
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

This is the code in addurl.php, as you can see this is the file that is set in action in the Add new link form:

&lt;?php
session_start();
require("../config.php");
$gbfile='links.txt';
$separator= '|';

//====================================
//This function will add one line to 
//the end of file
//====================================
function add($str){
global $gbfile;
      $tmp = trim($str);
      $fp=fopen($gbfile,'a+'); 
           flock($fp, LOCK_EX); 
                fwrite($fp, $tmp. "\
"); 
           flock($fp, LOCK_UN); 
      fclose($fp); 
}

//====================================
//Function below gets specified number
//of lines and returns an array
//====================================
function get($start, $end){
global $gbfile;
      $records=array();
      $filename="links.txt"; 
      $fp=fopen($gbfile,'r'); 
           flock($fp, LOCK_SH); 
           $i=1; 
           $tmp=TRUE;
           while($i&lt;$start && !feof($fp)) {
                $tmp=fgets($fp);
                $i++;
           }
           while($i&lt;=$end && !feof($fp)) {
                $tmp=trim(fgets($fp));
                if ($tmp) { array_push($records, $tmp); }
                $i++;
           }

           flock($fp, LOCK_UN); 
      fclose($fp); 
      return($records);
}

//=============================================
//Start of the script 
//=============================================
//If the method is post then add new message 
//to the guestbook file
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$title = ($_POST['text']);
$link = ($_POST['link']);
$desc = ($_POST['desc']);
$name = ($_POST['name']);
$rating = ($_POST['rating']);
$country = ($_POST['country']);
$email = strtolower($_POST['email']);

// Spam protection
$email = str_replace('@', '[AT]', $email);
// Now start writing
$tmp = implode($separator, array($title, $link, $desc, $name, $email, $country, $rating));
add($tmp);
// Now redirect
header("Location: index.php");
exit();
}
?&gt;

Hi,
Just move the <div id=“sortable”></div> out of the loop.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, target-densitydpi=high-dpi">
<title>Web links - List (<?php echo basename(dirname(__FILE__));?>)</title>
<link rel=StyleSheet href="style.css" type="text/css">
<script type="text/javascript" src="../collapse_expand_single_item.js"></script>
<script type="text/javascript" src="../jquery-1.11.1.js"></script>
</head>
<body>
<br>
<div class="link_back">
<a href="../index.php">Back to Index</a></div>
<br>
<div class="add_link">
<a href="#first" onClick="shoh('first');">Add new link +</a></div>
<br>
<div class="index_letter"><?php echo basename(dirname(__FILE__));?></div>
<div class="add_links" style="display: none;" id="first">
<div class="box">
<br>
<form action=addurl.php method=POST name="addurlform">
<div class="box_title">Title:</div><input type=text name=text size="56"  placeholder="Enter your title">
<div class="box_link">Drag & Drop Link:</div><input type=text value="" name=link size="56" placeholder="http://">
<div>
<br><br>
<input type=submit class="add_button" value="Add"></div>
</form>
<br>
</div>
</div>
<br>
[COLOR="#FF0000"][B]<div id="sortable">[/B][/COLOR]
<?php
$gbfile='links.txt';
$separator= '|';
//====================================
//This function will add one line to 
//the end of file
//====================================
function add($str){
global $gbfile;
      $tmp = trim($str);
      $fp=fopen($gbfile,'a+'); 
           flock($fp, LOCK_EX); 
                fwrite($fp, $tmp. "\
"); 
           flock($fp, LOCK_UN); 
      fclose($fp); 
}
//====================================
//Function below gets specified number
//of lines and returns an array
//====================================
function get($start, $end){
global $gbfile;
      $records=array(); 
      $filename="links.txt"; 
	  $fp=fopen($gbfile,'r'); 
           flock($fp, LOCK_SH); 
           $i=1; 
           $tmp=TRUE;
           while($i<$start && !feof($fp)) {
                $tmp=fgets($fp);
                $i++;
           }
           while($i<=$end && !feof($fp)) {
                $tmp=trim(fgets($fp));
                if ($tmp) { array_push($records, $tmp); }
                $i++;
           }
           flock($fp, LOCK_UN); 
      fclose($fp); 
      return($records);
}
//Listing part
$start=$_GET['start'];
$end=$_GET['end'];
if (!$end || $start<=0) { $start=1; }
if (!$end) { $end=$linkspage; }
if ($end<$start) { $end=$start+1; }
$show=$end - $start;

//Get records from file into array
      $records = get($start, $end);
	  sort($records);

//For each record get each field
      foreach ($records as $rec) {
           $tmp = explode($separator, $rec);
$title = $tmp[0];
$link = $tmp[1];
//=================================
//Outputting
?>
[s][COLOR="#FF0000"][B]<div id="sortable">[/B][/COLOR][/s]
<div class="wraper">
<a href="<?=$link?>">
<p class="title"><?php echo ("$title");?>
</p></a></div>
<?php
}
{
      $start+=$show;
	  $end+=$show;
	  $start++;
	  $end++;
	  $start--;
	  $end--;
}

?>
</div>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script> 
<script>
$("a[href^='http']").each(function() {
    $(this).css({
		background:"url(http://g.etfv.co/"+ this.href +") left center no-repeat",
		"-webkit-background-size": "20px",
		"-moz-background-size": "20px",
		"-o-background-size": "20px",
		"background-size": "20px",
		"padding-left": "20px",
		"margin-left": "56px"
	});
});
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
</script>
</body>
</html>

Also, why do you have that large lump of PHP in the middle of your HTML output?

Ooohh, how simple whas that:blush: Thank you for this. Regarding the large lump of PHP in the middle of HTML output: Well i’m not relay sure, this is just where it ended up. Where would you put the PHP? Thank you.
Do you have any idea regarding the save position function?

No probs :slight_smile:

What does it do?
This looks a bit superfluous to me:

$start+=$show;
$end+=$show;
[COLOR="#FF0000"]$start++;
$end++;
$start--;
$end--;[/COLOR]

Sure.

The next thing would be to convert the <div> tags to <li> tags and add an unique id to them.

Well the php code gets all the links from links.txt, this is the only Place i could find to put it to make this work. if i put heiger i get only one link. If i put it lower i cant change position on the links. I’l get started on converting <div> tags to <li>. How can i giv the links a unique id, should i do this in the PHP code?

I think i got the unique id now as well as the replace <div> with <li> tags. Take look.

Thank you.

Now how about the save new position function?

Thank’s

Hi,

I actually meant to add the ids to the <li> elements, e.g.: &lt;li id="link_1"&gt;...&lt;/li&gt;

However, as you seem to be saving the links in a file (as opposed to a database), then maybe there is an easier way to do this.

Your text file seems to be in the format:

Title|Link|||||

e.g.

Klart|http://www.klart.se/|||||
Translate|https://translate.google.com/|||||
Hitta|http://www.hitta.se/|||||

So if we can get a string containing something similar assembled whenever the update event fires, we can send this to the server via AJAX and have the links.txt file update automatically.

Try changing your sortable() initialisation method to this:

$( "#sortable" ).sortable({ 
  opacity: 0.5, 
  update: function( event, ui ) {
    console.log(event, ui);
    var res = ""
    $("ul#sortable&gt;li").each(function(){
      res += $(this).find("p.title").text();
      res += "|";
      res += $(this).find("a").attr("href");
      res += "|||||";
      res += "\
";
    });
    console.log(res);
  }
});

Does that log the correct result to the console whenever the links are rearranged?

Actualy the Title|Link||||| now looks like this Title|Link, but this new sortable code did not make any differens. It still works as before and i tryed to remove the res += “|||||”; part, no better.
The new position of the link is not saved to links.txt file. I am thinking maybe the id part is wrong, because the id is not created when a link is saved to links.txt (i think) because if you look in the links.txt file there is no id only the url and tilte. What do you think?

Hi,

The code isn’t meant to do anything, other than log a string (representing the contents of the new text file) to the console.

Here’s instructions on how to access your browser console?

I just had a look at your site and it looks good to me :slight_smile:

The next step is to send the new contents of the text file to the server (via AJAX), then have a PHP script overwrite the original.

I’ll have a look at this in the next day or so.

OK, Thats sounds great. Thank so much for your help. I realy appreciate it.

Hi there,

Change your JS to this (all in script tags of course):

$("a[href^='http']").each(function() {
    $(this).css({
    background:"url(http://g.etfv.co/"+ this.href +") left center no-repeat",
    "-webkit-background-size": "20px",
    "-moz-background-size": "20px",
    "-o-background-size": "20px",
    "background-size": "20px",
    "padding-left": "20px",
    "margin-left": "56px"
  });
});

function getLinkList(){
  var list = ""
  $("ul#sortable>li").each(function(){
    list += $(this).find("p.title").text();
    list += "|";
    list += $(this).find("a").attr("href");
    list += "|||||";
    list += "\
";
  });

  return {linkList: list}
}

$( "#sortable" ).sortable({ 
  opacity: 0.5, 
  update: function( event, ui ) {

    $.ajax({
      type: "POST",
      url: "process.php",
      data: getLinkList(),
      dataType: "text",
      success: function(res){
        console.log(res)
      },
    });
  }
});
$( "#sortable" ).disableSelection();
$('#sortable').mousedown(function(){ $(this).css('cursor', 'move');});
$('#sortable').mouseup(function(){ $(this).css('cursor', 'pointer');});
$('.title').mousedown(function(){ $(this).css('cursor', 'move');});
$('.title').mouseup(function(){ $(this).css('cursor', 'pointer');});

Then create a file called process.php, make sure it’s in the same directory (or adjust the path) and add the following:

<?php 
  $linkList = $_POST['linkList'];
  echo $linkList;
?>

Now when you re-order the links in your browser, an AJAX request will fire when the update event is triggered and send the current order of the links to the PHP script.

For this example I am just echoing them back to the JS from the PHP (you can see them in the console), but in real life you would overwrite your file.

HTH

Hello and thank again. I’v added your code and the process.php file in the same directory, but still the order wont change after update?

Yeah, you have to write the PHP code to save the links to the file :slight_smile:

OK, any idea how this php should look like, can i use some part of the addurl.php file or some of the php code in the index.php file?
Thank you.

OK, i got this code on the process.php file:

&lt;?php

$linkList = $_POST['linkList'];

//the data

$data = "$linkList\
";

//open the file and choose the mode

$fh = fopen("links.txt", "w");

fwrite($fh, $data);

//close the file

fclose($fh);

?&gt;

and it works if i remove this: sort($records); from the index.php file. But if i move a link and update the page the link url has changed from eg, https://www.google.se/?id=2 to https://www.google.se/?id=2?id=1 so every time i move this link the process.php will add an ?id=what ever to the url. What do you think, is it sepose to behave like this?

Thank you.

Ahha, i removed the ?id=<?php echo $start++;?> part from <li><a href=“<?=$link?>”> and now it seems to work, have a look. Thank you.

Hi,

Good job!

No, that was just left over from trying to give the <li> elements unique ids.
Just remove the query string (?id=whatever) from your PHP.

OK, so now it works, perfect. Thank you. Now i need a delete link function. i have change the code to this, i have just added an X to the right of the links, when i click this X the link should be deleted, will also need a confimation popup.
Can this be done with a similar Ajax code as the Ajax code you gave me to POST to the process.php file and then make a new PHP file (delete.php)? Thank you.

&lt;li&gt;&lt;a href="&lt;?=$link?&gt;"&gt;
&lt;p class="title"&gt;&lt;?php echo ("$title");?&gt;
&lt;/p&gt;&lt;/a&gt;&lt;li class="delete"&gt;X&lt;/li&gt;

(NO THIS DID NOT WORK AFTER ALL)

The best thing would be to have a little X pop up when you hover over the link, then when you click on the X remove the link (using .remove()).
After that you could just trigger the update event on the list (after the user has confirmed the delete) and the new order of the links would be saved automatically.

So I guess the problem is, how to display the X on hover.
It might be worth asking in the CSS forum.
Or do you have another idea of how to implement this?