Call External Javascript function using Codeigniter - codeigniter

I need to call a javascript function from my controller in codeigniter.It is possible in codeigniter ?
Problem Details
My javascript file contains
function debugOutput(msg) {
alert (msg);
}
and also I need to call it from my controller.
I done it as follows.
<?php
function check()
{
header('Content-type: application/x-javascript');
// body here
}
?>
function execute() {
debugOutput("<?php echo 'test'; ?>");
}
execute();
But it is not working.Please help me to solve it.

Finally I got the answer.Here I am sharing that answer;
<?php function check(){
{header('Content-type: application/x-javascript');?>
function execute() {
showName(<?php echo 'ajithperuva';?>);
}
execute();
<?php
}
This script will invoke an external javascript function showName().
Thanks for all help me in my trouble.

For one, you would need to surround the call with <script> tags:
<script type="text/javascript">
function execute() {
...
}
</script>

Related

Json Data print after insert a record using Jquery Ajax in CodeIgniter

I am using Jquery Ajax in Codeigniter, after register a user via bootstrap modal I got JSON data as below instead of fetching the data from table. Where I am wrong? please help!
{"success":true,"type":"add"}
Here is my Jquery function
```
<script>
$(function(){
display();
//add new
function display(){
$.ajax({
type:'ajax',
url:'<?php echo base_url()?>frame_cont/display',
async: false,
dataType:'json',
success:function(data){
var html='';
var i;
for(i=0;i<data.length;i++){
html +='<tr>'+
'<td>'+data[i].id+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].email+'</td>'+
'<td>'+data[i].password+'</td>'+
'<tr>';
}
$('#showdata').html(html);
},
error:function(){
alert('Could not get Data from Database');
}
});
};
});
</script>```
and here is controller class
<?php
class Frame_cont extends CI_Controller{
public function index(){
$this->load->view('index');
}
public function register(){
$this->load->model('frame');
$result=$this->frame->insert();
$msg['success']=false;
$msg['type']='add';
if($result){
$msg['success']=true;
}
echo json_encode($msg);
}
public function display(){
$this->load->model('frame');
$result=$this->frame->display();
echo json_encode($result);
}
}
This is all about the code and sorry for the english
in your register function you doing echo json_encode($msg); at the end. you should echo inserted value inside if condition
The issue occur because of I am using type="submit" instead of type="button" in my form button.

call to codeigniters controller function is not working

i am using $.post() to call a controllers function from view(though i know its bad practice) and in that function i am loading a view and its not working.
this is HTML code : <li id='files' class="active" >My Files</a></li>
this is JS Code :
$("#files").click(function()
{
alert('hi2'); //just for checking
var loadUrl = "/Fast-Docs/index.php/Docs/updatefiles";
$.post(
loadUrl,
{un:"<?php echo $username?>"});
});
this is function in controller:
public function updatefiles()
{
$this->load->model('DocsModel');
$un=$this->input->post('un');
$files=$this->DocsModel->getAllFiles($un);
$data['files']=$files;
$this->load->view('files',$data);
}
You need to actually display your code after the ajax call, ie
$.post(
loadUrl,
{un:"<?php echo $username?>"}
});
Becomes
$.post(
loadUrl,
{un:"<?php echo $username?>"},
function(data) {
$("#yourDiv").html(data);
}
});

IF Statement For Session - Formatting Q

So I have this IF statement in my view. it works and all, but wondering if there's a better way to write this. Having both session calls seem unneccessary...
if($this->session->userdata('campaign_name')){
echo $this->session->userdata('campaign_name');
}
else {
echo 'this';
}
Note this function will be used inline on a text input. So I'm looking for as minimal code as possible.
Note that CI's Session class's userdata method will return false if no campaign_name exists. So assign a variable to the potentially undefined array key (campaign_name)
$campaign_name = $this->session->userdata('campaign_name');
if($campaign_name)
{
echo $campaign_name;
}
else
{
echo 'this';
}
OR
if($campaign_name = $this->session->userdata('campaign_name'))
{
echo $campaign_name;
}
Controller Method (/application/controllers/test_controller.php)
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Test_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function myFunction()
{
$data['campaign_name'] = $this->session->userdata('campaign_name');
$this->load->view('test_view',$data);
}
}
View (/application/view/test_view.php)
<html>
<head></head>
<body>
<input type="text" value="<?php echo $campaign_name; ?>">
</body>
</html>
In your controller, you can store the value of that session data into a variable and pass that along to the view. In the view, you can then have your if else statements that just look at the variable. I would advise against setting a variable in the view as RPM did. While it works, it breaks the separation of concerns you have going.
Also, look into using the alternative PHP syntax for views in CodeIgniter. It'll make your code neater and more maintainable.
Edit: I see now that RPM has updated his answer to set the variable in the controller. That's a good example to follow.

CodeIgniter Ajax form - submitting form

I'm new to stackoverflow and to CodeIgniter and I'm currently experimenting on some simple code examples I have found on the Internet in order to get a start. The one I'm working on right now is a form which uses CI and Ajax (jQuery) along with saving the inputs of the form in a database and then display the most recent of them on the same page as the form.
If I confused you it's the 4.7 application example from here. The initial source code lies here but I have modified it in order to work with the latest release of CI and I quote all my MVC files just below.
Controller:
<?php
class Message extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Message_model');
}
function view()
{
//get data from database
$data['messages'] = $this->Message_model->get();
if ( $this->input->is_ajax_request() ) // load inline view for call from ajax
$this->load->view('messages_list', $data);
else // load the default view
$this->load->view('default', $data);
}
//when we pres the submit button from the form
function add()
{
if ($_POST && $_POST['message'] != NULL)
{
$message['message'] = $this->security->xss_clean($_POST['message']);
$this->Message_model->add($message);
}
else
{
redirect('message/view');
}
}
}
?>
Model:
<?php
class Message_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function add($data)
{
$this->db->insert('messages', $data);
}
function get($limit=5, $offset=0)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $offset);
return $this->db->get('messages')->result();
}
}
?>
Views
default.php:
<!-- called using message/view -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<?php echo base_url('js/jquery-1.8.1.min.js'); ?>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
</script>
</head>
<body>
<?php echo form_open("message/add"); ?>
<input type="text" name="message" id="message">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
<div id="content"></div>
</body>
</html>
messages_list.php:
<!-- called from ajax call -->
<ol>
<?php foreach ($messages as $cur): ?>
<li><?php echo $cur->message; ?></li>
<?php endforeach; ?>
</ol>
The problem mainly lies in the 1st of the views (default.php). That is, if I omit the e.preventDefault(); line from the javascript code then the form loads a different page (message/add as the form action parameter implies) which is a blank page, also cancelling the ajax behavior of my application that way.
On the other hand, if I actually add this line then the add method of my message controller isn' t called, thus not adding what I've typed into the database.
Finally, I tried the following js code instead of the other above:
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
but that way it seems as the $.post() crashes because nothing is executed in the function which is supposed to run on a successful post() call.
Any help appreciated and sorry for the big post. :)
You are correct that you must call e.PreventDefault();, but you must also deal with the response from the callback function, which you are not. The callback takes a few arguments but the first one is what you're interested in, it is the response from your server. I've denoted it as r below:
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function(r) {
//do something with r... log it for example.
console.log(r);
});
});
});
I've also removed $.("#content").load(...);. This would actually perform another AJAX request when the first one is complete.
Now, inspecting your controller...please refrain from using $_POST. CodeIgniter provides you with $this->input->post() as part of the Input Library. If you turn on Global XSS filtering in config/config.php you won't have to xss clean it either. You can clean on a post-by-post basis by using $this->input->post('name', true);
I recommend this instead:
function add(){
$m = $this->input->post('message', true);
if($m){
$this->Message_model->add($m);
}
}
The problem doesn't lie with the CI, its the JS that is wrong,
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("<?php echo base_url(); ?>/message/view");
$('#message').val('');
});
});
});
The e.preventDefault() is used to stop the default behaviour of the submit button (which will take you to message/add), which we don't want. You are correct in adding the URl paramter to the $.post() function later, but in the callback function, the .load loads the URL that is passed to it into the #content, so without passing any url, of course there won't be anything to load.

CodeIgniter's url segmentation not working with my JSON

It's my first post in here and I haven't yet figured out to format my post properly yet, but here it goes.
So basically I can only get my code to work if i point directly to a php-file. If I try to call a method within my controller, nothing seems to happen.
My JavaScript:
$(document).ready(function() {
$(".guide_button").click(function(){
var id = $(this).text();
var data = {};
data.id = id;
$.getJSON("/guides/hehelol", data, function(response){
$('#test').text(response.id);
});
return false;
});
});
My markup:
<div id="content_pane">
<ul>
<li>RL</li>
<li>LG</li>
<li>RG</li>
<li>SG</li>
<li>GL</li>
<li>MG</li>
</ul>
</div>
<div class="description">
<h3>Description</h3>
<p id="test">This text area will contain a bit of text about the content on this section</p>
</div>
My Controller:
<?php
class Guides extends CI_Controller {
public function Guides()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
}
public function index()
{
$this->load->view('guides_view');
$title = 'Some title';
}
public function hehelol() //The controller I am desperatly trying to call
{
$id = $_GET['id'];
$arr = array ('id'=>$id);
echo json_encode($arr);
}
}
It might be my controller I have done something wrong with. As it is the code only works if create a hehelol.php file and refer to it directly like this.
$.getJSON("hehelol.php", data, function(response){
$('#test').text(response.id);
});
Anyone who knows what I need to do to make my controller work properly? Help please! :)
i just put your exact code in its entirety in my codeigniter app and it worked for me. Meaning I used this: ...$.getJSON("/guides/hehelol",...
Because you are making a $_GET request, you have to enable query strings.
In your config.php file, make sure this line is set to TRUE:
$config['allow_get_array']= TRUE;

Resources