• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 113
  • Last Modified:

Could you point how to put a button at the right side of the links by using jQuery?

Hi Experts

Could you point how to put a functional button at the right side of the links by using jQuery?

Plus - this button needs to call, by Ajax, a PHP Codeigniter's controller to perform a deletion (Excluir means deletion).

Accordingly to:
img001
jQuery code used:
if(field ==="anexo_v"){
	if(value !==null){
		$(".anexo_v").show();
		var link = "";
		$.each(value,function(id, valor){
			var anexo = valor.anexo;
			anexo = anexo.split("/");
			anexo = $(anexo).get(-1);
			//console.log(valor.anexo);
			link = link+"<p><a href=\'"+valor.anexo+ "\' target=\'_blank\'>"+anexo+"</a></p>";                                             ;
		});
		$("#anexo").html(link);
	}else{
		$(".anexo").hide();
	}
}

Open in new window


Thanks in advance!
0
Eduardo Fuerte
Asked:
Eduardo Fuerte
  • 11
  • 5
1 Solution
 
Julian HansenCommented:
Something like this
HTML
    <button class="btn btn-primary add-button">Add buttons</button>
    <div><a href="#link1" class="decorate"> Link 1</a></div>
    <div><a href="#link2" > Link 2</a></div>
    <div><a href="#link3" class="decorate"> Link 3</a></div>
    <div><a href="#link4" > Link 4</a></div>
    <ul id="result"></ul>

Open in new window

jQuery
<script>
$(function() {
  // Create a button to use to add to links
  var button = $('<button/>', {class: 'btn btn-success call-ajax'}).html('Excluir');

  // Add the buttons
  $('.add-button').click(function() {

    // Add to all links with the .decorate class
    $('.decorate').each(function(i, el) {
      // Clone the template button and set the data-link custom attribute
      // to the href of the associated link
      $(el).after(button.clone().data('link', $(el).attr('href')));
    });
  });

  // Click handler for dynamically added buttons
  $('body').on('click', '.call-ajax', function() {
    // Get the data associated with the clicked button
    data = {
      link: $(this).data('link')
    };

    // AJAX it to the server
    $.ajax({
      url: 't1822.php',
      data: data,
      type: 'POST'
    }).done(function(resp) {
      // Display the resposne
      $('#result').append($('<li/>').html(resp));
    });
  });
});
</script>

Open in new window

Working sample here
0
 
Eduardo FuerteAuthor Commented:
Hi Julian

The "complicator" in this case is the controller send data to jQuery accordingly to:

 public function get($id)
{
	try
	{
		if (empty($id))
			throw new Exception('ID não existe', 1);
		if (!$this->input->is_ajax_request())
			throw new Exception('Erro de requisição', 1);


	   
		$result = (array )current($this->reclamacao_model->new_get(array('where' => array('id_reclamacao' => $id), 'fields' => array(
				'id_reclamacao',
				//'data',
				'DATE_FORMAT(data,"%d/%m/%Y %H:%m:%i") as data',
				'interna_externa',
				'enviado_por',
				'nome_reclamante',
				'genero',
				...
				'created_by', //EF 2016/Out - 08 Obtém o nome do usuário que criou o formulário
				'updated_at',
				'updated_by'))));

		$query_arquivos = array('fields' => array(
				'id_anexo',
				'id_reclamacao',
				'anexo'), 'where' => array('id_reclamacao' => $result['id_reclamacao']));
		$result_anexo = $this->anexo_model_reclamacao->new_get($query_arquivos);
		//print_r($result_anexo);
		if (!empty($result_anexo))
		{
			//$result_anexo = $result_anexo[0];
			$result['anexo'] = $result_anexo;
		}

	}
	catch (exception $e)
	{
		bootbox_alert($e->getMessage());
	}


	// Send data to jQuery
        //-------------------------------
	$this->output->set_content_type('application/json')->set_output(json_encode($result));
         //------------------------------------
}

Open in new window


Then jQuery fills all the views control values - acordingly to:

$("#view")
.on("view", function(e, data) {

	var $form = $(this);

		$.each(data, function(field, value) {
			
			var
				avoid = ' . json_encode($options['edit']['avoid']) . ',
				$field = $form.find(\'[name="\' + field + \'"]\'),
				tag = ($field.length ? $field.prop("tagName").toLowerCase() : undefined)
			;
									if(field ==="anexo"){
									
										if(value !==null){
											$(".anexo").show();
												var link = "";
												$.each(value,function(id, valor){
													var anexo = valor.anexo;
													anexo = anexo.split("/");
													anexo = $(anexo).get(-1);
													//console.log(valor.anexo);
													
													//Where the links are presented:
													link = link+"<p><a href=\'"+valor.anexo+ "\' target=\'_blank\'>"+anexo+"</a></p>";       
													
													//Where the "Excluir buttons" must be presented (just near where the links are presented )
													...



													;
												});
												$("#anexo_view").html(link);
										  }else{
											 $(".anexo").hide();
										}
									}



			$("#"+field).addClass("meeta-view");
			
			if (avoid.indexOf(field) !== -1)
				return;

			switch (field) {

				case "image_path":
				case "logo_path":
					$form.find(".fileupload-preview img").attr("src", value);

					break;

				case "_pass":
					break;

				case "id":
					$field.val(value);
					
					break;
				default:

				if ( !$field.length)
					return;

				switch (tag) {
					case "select":
						$field.find(\'option[value="\' + value + \'"]\').prop("selected", true);

						break;
					case "input":

						switch($field.prop(\'type\')) {
							case \'file\':
							return;
							case \'checkbox\':
								
								$field.prop(\'checked\', isNaN(value) ? value : Number(value));
								break;
							default:
							$field.val(value);
						}
					break;

				default:
					$field && $field.val(value);
			}
		}

	});

}) ;

Open in new window


So I need to embed the code that creates the "Excluir" buttons - at the right side of every link - in jQuery  - no possibility to code HTML....

Any workaround in embeding your code in jQuery ?
0
 
Julian HansenCommented:
I still don't know what the button must do but if I understand the other part of your question then the bit we are interested in is on line 25
link = link+"<p><a href=\'"+valor.anexo+ "\' target=\'_blank\'>"+anexo+"</a></p>"; 

Open in new window

Change to
link = link+"<p><a href=\'"+valor.anexo+ "\' target=\'_blank\'>"+anexo+"</a><button class="call-ajax">Excluir</button></p>"; 

Open in new window


You will need to add some more information about what the button is supposed to do and what it contains

If you do the above then you will only need to add the following to your code

$(function() {
...
  // This handles the click on the dynamically added button
  // change the AJAX to do what you need it to
  $('body').on('click', '.call-ajax', function() {
    // Get the data associated with the clicked button
    data = {
      link: $(this).data('link')
    };

    // AJAX it to the server
    $.ajax({
      url: 't1822.php',
      data: data,
      type: 'POST'
    }).done(function(resp) {
      // Display the resposne
      $('#result').append($('<li/>').html(resp));
    });
  });
});

Open in new window

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Eduardo FuerteAuthor Commented:
First the user uploads files to be attached to the register. Then the links simply shows the files that could be downloaded when it's needed.

When the user decides that a file no longer must to be attatched to the register then clicks the "Excluir" button next to  the correspondent link.
0
 
Eduardo FuerteAuthor Commented:
I applied your code and  don't know what is preventing this to run:

link = link+ "<p><a href=\'"+valor.anexo+ "\' target=\'_blank\'>"+anexo+"</a><button class="call-ajax">Excluir</button></p>";  

Open in new window

0
 
Eduardo FuerteAuthor Commented:
Since the jQuery code is formed by a helper and then outputed to the view - this is needed:

 link = link+ "<p><a href=\'"+valor.anexo+ "\' target=\'_blank\'>"+anexo+"</a><button class=\'call-ajax\'>Excluir</button></p>";  

Open in new window

0
 
Julian HansenCommented:
Well you need to escape the quotes. Personally I prefer to build up the elements rather than use strings but if you use the latter then the quotes need to be escaped - which you have done in your second post but it does not make sense. If you enclose a string in " " (double quotes) there is no need to escape the single questions in the string - and vice versa.

Standard is to enclose attributes in double quotes so use single quotes to enclose string.

You also are including valur.anexo and anexo - is that intentional and correct?

link = link + '<p><a href="' + valor.anexo+ '" target="_blank">'+anexo+'</a><button class="call-ajax">Excluir</button></p>';  

Open in new window

0
 
Eduardo FuerteAuthor Commented:
Yes.
valor.anexo has the logical place where the file remains and anexo only the name of the file.

By using escape quotes it's running I'm going to the second part...
0
 
Eduardo FuerteAuthor Commented:
Julian

This code is perfectly called when "Excluir" button is clicked:
$("body").on("click", ".call-ajax", function() {
	// obtém o valor do link
	console.log("chamada ajax");

	data = {
	  anexo: $(this).data("anexo")
	};

	console.log(data);

	// AJAX para o controller
	$.ajax({
	  url: "reclamacao/delete_anexo",
	  data: data,
	  type: "POST"
	}).done(function(resp) {
	  // Display the resposne
	  $("#result").append($("<li/>").html(resp));
	});
  });

Open in new window


img002
But I guess something must be changed since the "anexo" value that must be deleted in database isn't correctly  received, could you check?
0
 
Julian HansenCommented:
Well the reason is because the button we are creating is not being initialised with the custom attribute data-anexo. In the JQuery code we have this (lines 5-7)

data = {
	  anexo: $(this).data("anexo")
	};

Open in new window

This is defined inside the event handler defined on line 1 like so
$("body").on("click", ".call-ajax", function() {

Open in new window

In other words - the active element here is the <button>

In order for this to work we need to add the data-anexo attribute to the <button> along with the anexo value. In other words something like this

link = link + '<p><a href="' + valor.anexo+ '" target="_blank">'+anexo+'</a><button class="call-ajax" data-anexo="' + anexo + '">Excluir</button></p>';  

Open in new window

0
 
Eduardo FuerteAuthor Commented:
Just to clear -  I had to consider escapes since this  jQuery is a PHP output to the view page, the other manner the variables becames PHP code:
img004
So the jQuery code is:
link = link + "<p><a href=\' + valor.anexo+ "\' target="_blank\'> +anexo+</a><button class="call-ajax" data-anexo=\' + anexo + \'">Excluir</button></p>";  

Open in new window


Still not running
img005
To be fair this question is beeing to extense... I'm opening another to continue!
0
 
Eduardo FuerteAuthor Commented:
0
 
Eduardo FuerteAuthor Commented:
Thanks for the assistance!

(Could you please follow the continuation?)
0
 
Eduardo FuerteAuthor Commented:
Sorry, Julian

It's just a matter of correct the code:

This runs:
 link = link+ "<p><a href=\'"+valor.anexo+ "\' target=\'_blank\' class=\'anexo\' name=\'link\'>"+anexo+"</a><button type=\'button\'  class=\'call-ajax\' data-anexo=\'" + anexo + "\'>Excluir</button></p>";

Open in new window

0
 
Julian HansenCommented:
I had to consider escapes since this  jQuery is a PHP output to the view page
Then use HEREDOC notation - far better and more flexible. HEREDOC allows you to include both single and double quotes in the string without escaping and you can included variables - best of all worlds.

echo <<< LINK
link = link + '<p><a href="' + valor.anexo+ '" target="_blank">'+anexo+'</a><button class="call-ajax" data-anexo="' + anexo + '">Excluir</button></p>'  
LINK;

Open in new window

0
 
Eduardo FuerteAuthor Commented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 11
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now