Solved

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

Posted on 2016-11-03
16
51 Views
Last Modified: 2016-11-03
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
Comment
Question by:Eduardo Fuerte
  • 11
  • 5
16 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41872187
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
 

Author Comment

by:Eduardo Fuerte
ID: 41872266
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
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41872298
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
 

Author Comment

by:Eduardo Fuerte
ID: 41872446
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
 

Author Comment

by:Eduardo Fuerte
ID: 41872491
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
 

Author Comment

by:Eduardo Fuerte
ID: 41872561
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41872592
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
 

Author Comment

by:Eduardo Fuerte
ID: 41872602
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Eduardo Fuerte
ID: 41872635
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41872769
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
 

Author Comment

by:Eduardo Fuerte
ID: 41872833
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
 

Author Comment

by:Eduardo Fuerte
ID: 41872850
0
 

Author Closing Comment

by:Eduardo Fuerte
ID: 41872854
Thanks for the assistance!

(Could you please follow the continuation?)
0
 

Author Comment

by:Eduardo Fuerte
ID: 41872897
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41872952
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
 

Author Comment

by:Eduardo Fuerte
ID: 41872966
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now