Jump to content

Remove line with Ajax from .txt after link click.


graat90

Recommended Posts

Hi there,

 

My head is stuck at this moment.

I've got a textfile with words. Each word starts at a new line.

I want to let the user delete a word(line) from this textfile after a button click.

I managed to add the "add word to the list" function, but now i want a delete button variant.

 

post-167077-0-86915800-1389803265_thumb.png

 

There are four files. myscript.js, vulwoorden.txt, word_filter.php and delete.word.php.

 

This is the code for myscript.js:

	//User can add word to wordfilter
	$("body").on("click", ".hide_word", function(e){
		e.preventDefault();
		var word = $(this).data("word");

		$.ajax({ 
			 url: 'includes/set.word.php',
			 type: 'POST',
			 data: 'word=' + word,
			 success: function (){
	
			 },
			 error: function (xhr, ajaxOptions, thrownError) {
			  alert(xhr.status);
			  alert(thrownError);
			 }
		 });	
		 $(this).parent().parent().hide('slow', function(){ 
		 	$(this).remove(); 
		 });
	});
	
	//User can delete word from wordfilter
	$("body").on("click", ".delete_word", function(e){
		e.preventDefault();
		var word = $(this).data("word");

		$.ajax({ 
			 url: 'includes/delete.word.php',
			 type: 'POST',
			 data: 'word=' + word,
			 success: function (){
	
			 },
			 error: function (xhr, ajaxOptions, thrownError) {
			  alert(xhr.status);
			  alert(thrownError);
			 }
		 });	
		 $(this).parent().parent().hide('slow', function(){ 
		 	$(this).remove(); 
		 });
	});

This is the code for the word_filter page

<?php 
		$lines = file('./includes/vulwoorden.txt');
		$i=1;
		echo '<table id="wordlist" class="table">';
		foreach ($lines as $line_num) {
		   echo '<tr>' . "<td>" . $line_num . '</td><td>';
		   echo '<a data-word="' . $line_num . '" class="btn-danger btn-sm delete_word">Verwijder woord</a></td></tr>';
				$i++;
					
		echo '</table>';
?>

And this is the code for delete.word.php (this code is just a copy from the set.word.php, so this is code to add a word to the textfile. 

<?php 

$fn = "vulwoorden.txt";
$file = fopen($fn, "a+");

if(isset($_POST['word']) && trim($_POST['word']) != "" && !is_null($_POST['word'])) {
	$word = $_POST['word'] . "\r\n";
	fwrite($file, $word);
}
?>

I know how to do it with a form, but i want to do it combined with Ajax, so the users won't have to refresh the page.

 

Thanks in advance!!

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.