Solved

Could you point how to make a  Codeigniter view  to obtain a value from the correspondent controller?

Posted on 2016-10-04
9
78 Views
Last Modified: 2016-10-07
Hi Experts

Could you point how to make a  Codeigniter view  to obtain a value from the correspondent controller?

The controller method in reclamacao.php
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','nome_reclamante',
                    'genero', 'procedencia', 'anexo', 'fk_seguradora', 'created_at',
                    'created_by', 'updated_at', 'updated_by')               
                    )));
           
        }
        catch (exception $e) {
            bootbox_alert($e->getMessage());
        }
        $this->output->set_content_type('application/json')->set_output(json_encode($result));
    }

Open in new window


The  column "anexo" is the needed value.

The view code:

<!-- Existing value -->	
<input type="hidden" id="id_reclamacao" name="id_reclamacao" value="">	
...
	
<!----------------------------------------------------------------------------------------------------->
I guess an ajax code is needed to receive the value in the view, isn't it? 
Something like that:
<!----------------------------------------------------------------------------------------------------->
<script type="text/javascript">

		$(function () {
			
				var serv = $('#id_reclamacao').val();
	
				$.ajax({
					url: base_url('reclamacao/get/' + serv),
					type: 'post',
					cache: false,
					contentType: false,
					processData: false,
					dataType: 'json',
					data: serv,
					success: function (data) {
						// THE WAY TO OBTAIN THE RESULT HERE IS CORRECT?
						$('#anexo').val(data);
					},
					error: function(jqXHR) {
						bootbox.alert(jqXHR.responseText);
					}
				});

			});
		});
</script>



<div class="col-xs-4 mb20">
	<label for="tempo_resposta" class="field-label text-muted mb10">Download do PDF'</label>
	<div class="input-group">
		<span class="input-group-addon">
			<i class="fa fa-clock-o c-gray"></i>
		</span>
		<span class="validar">
			
			// WHERE THE RECEIVED VALUE MUST BE USED, THIS GENERATES AN ERROR:
			<b><a href="<?php echo base_url($result['anexo'])?>" target="_blank">Upload do PDF relacionado</a></b></li>
		</span>
	</div>
</div>

Open in new window


Could you check and possibly give me some directions?

Thanks in advance.
0
Comment
Question by:Eduardo Fuerte
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 41828285
See if I have understood: in your view you are usinh jquery to perform an Ajax call to your controller function which returns data in json format. If this is the case, then the code
$('#anexo').val(data);

Open in new window

is wrong: it would be correct to get the value from a DOM element with id='anexo'. Here you have no DOM element but json data, so you have to parse data array to get the required value:
success: function (data) {
     var anexo = data['anexo'];
     console.log(anexo);
},

Open in new window

This should do the trick. I'm not sure (I can't put this in my head, don't know why!) but if this doesn't work you probably have to use JSON.parse:
success: function (data) {
     var result = JSON.parse(data);
     var anexo = result['anexo'];
     console.log(anexo);
},

Open in new window

0
 

Author Comment

by:Eduardo Fuerte
ID: 41828516
The first option you gave worked out.
But just another issue related I found:

When coding a jQuery event to obtain a value from textbox:

The textbox exists in the page context and was made visible:

<!--input type="hidden" id="id_reclamacao" name="id_reclamacao" value=""-->
<input type="text" id="id_reclamacao" name="id_reclamacao" value="">

Open in new window


img004
A button that when is  clicked fires de jQuery

<div class="col-xs-4 mb20">
<label for="download" class="mb10">Download do PDF</label>
<div class="input-group">
	<input type="button" id="download" name="download">
</div>
</div>

Open in new window


But when the jQuery is fired it couldn't capture the #id_reclamacao - visible to the view, as showed - and generates an error...
<script type="text/javascript">                                 
$(function () {

	$("#download").click(function(){

		var serv = $('#id_reclamacao').val();
		
		//console.log($(serv);
	
		//var serv = 2; // forcing this value it runs Ok

		$.ajax({
			url: base_url('reclamacao/get/' + serv),
			type: 'post',
			cache: false,
			contentType: false,
			processData: false,
			dataType: 'json',
			data: serv,
			success: function (data) {
			var anexo = data['anexo'];
			alert(anexo);
			},
			error: function(jqXHR) {
				bootbox.alert(jqXHR.responseText);
			}
		});
	});
   });
</script>

Open in new window


Could you check it and possibly give a workaround?
0
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 500 total points
ID: 41828633
and generates an error
Eduardo, you're a veteran here at EE: why do you want I guess the error instead of kindly tell me everything about it? ;-)

Anyway, I see in your Ajax call you are using the CodeIgniter function base_url(): you can't. To solve the issue follow these steps:
1 - open the footer view you include in your files
2 -  at the bottom, immediately before the body closig tag, add this:
<script type="text/javascript">
	var baseurl = "<?php print base_url(); ?>";
</script>

Open in new window

3 - use variable baseurl in your javascripts this way:
<script type="text/javascript">                                 
$(function () {

	$("#download").click(function(){

		var serv = $('#id_reclamacao').val();
		
		//console.log($(serv);
	
		//var serv = 2; // forcing this value it runs Ok

		$.ajax({
			url: baseurl+'reclamacao/get/' + serv,
			type: 'post',
			cache: false,
			contentType: false,
			processData: false,
			dataType: 'json',
			data: serv,
			success: function (data) {
			var anexo = data['anexo'];
			alert(anexo);
			},
			error: function(jqXHR) {
				bootbox.alert(jqXHR.responseText);
			}
		});
	});
   });
</script>

Open in new window

Everything should work now :)
0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

Author Comment

by:Eduardo Fuerte
ID: 41828771
Sorry, Marco.

The error was  caused by the absence of the parameter  #id_reclamacao when calling the get() controller.

After applying your solution... runs fine!
0
 

Author Comment

by:Eduardo Fuerte
ID: 41828790
Too late but here it is:

 img_EE_002_061016.png
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 41828817
Ah ah, the funny thing is that the error couldn't help to fix the Ajax url issue: seeing the error message I would have investigate about the serv variable value and maybe I didn't notice the wrong use of the base_url() function... so the fact you had not posted the error message has been positive :)
0
 

Author Closing Comment

by:Eduardo Fuerte
ID: 41828848
Marco

Thank you for your dedication and competence in help!
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 41829241
Glad to help you, Eduardo :)
0
 

Author Comment

by:Eduardo Fuerte
ID: 41830048
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JSON Error in ASP Page 3 38
SQL Function 4 38
jQuery Tree with Draggable items 11 22
How do I correctly structure this insert statement 3 31
This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
This article discusses how to implement server side field validation and display customized error messages to the client.
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)

734 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