Get data using jQuery ajax method in codeigniter - php

Below is my view:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.min.css"); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="<?php echo base_url("plugins/jQuery/jQuery-2.2.0.min.js"); ?>"></script>
<script type="text/javascript" charset="utf-8">
function waitForMsg1() {
$.ajax({//Ajax method to get data from Message Controller
type: "GET",
url: "<?php echo base_url('index.php/message/messageCount'); ?>",
async: true,
cache: false,
timeout: 50000,
success: function (data) {
addmsg("new", data);
setTimeout(waitForMsg1, 1000);
},
});
};
$(document).ready(function () {
waitForMsg1();
});
function addmsg(type, count) {
$('#badge').html(count); //selecting the element to display inside the badge
}
</script>
</head>
<header>
<a href="#"><span><div id="bounce"><i class="fa fa-envelope ">
<span class="badge" id="badge" style="background-color:red;margin:-25px 0 0 -5px;">
</span></i></div></span></a>
</header>
Below is the Controller:
<?php
class Message extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('MessageDb');
$this->load->model('UserDb');
$this->load->model('EmployeeDb');
}
public function messageCount()
{
echo '12345'; //This is the dummy value.
}
}
?>
I want to display the count from Message controller into the view, it is not working. I tried a lot but not able to rectify the problem. How this can be done?

Related

Why does loading a codeigniter view using ajax corrupts the css and js functions

So I have a main page named index.php, this contains the whole html page and the css and js assets as well.
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/main.css';?>">
<!-- this contains my other css -->
<head>
<body>
<div id="wrapper">
<div class="main-section">
<?= $home ?>
<!-- this is the section i want to replace using ajax -->
<!-- $home is a codeigniter view of the section for home -->
</div>
</div>
<script>
var BASE = "<?php echo site_url(); ?>";
</script>
<script src="<?php echo base_url().'assets/js/jquery.js';?>" type="text/javascript"></script>
<script src="<?php echo base_url().'assets/js/jquery.touchSwipe.min.js';?>" type="text/javascript"></script>
<!-- other js files -->
</body>
</html>
so when it is loaded like that, everything works fine. but when i use ajax function to change the content of main section like this,
JQ("#btnshop").on('click', function(e) {
e.preventDefault();
JQ.ajax({
url: BASE + "bhs/main/shop",
method: 'GET',
dataType: 'html',
data: {},
success: function(response) {
$(".bhs-main-section").empty().html(response);
}
});
});
and this is the code of the controller i'm getting my content
public function shop()
{
$data['tenants'] = $this->tenant->getTenants();
$data['tenants_categories'] = $this->tenant_category->find(1);
$this->load->view('bhs/shop', $data);
}
Any ideas why some of the css, and js are breaking? Thanks in advance
Ajax will never load the view
you need to echo the content in controller instead of loading view
public function shop()
{
$data['tenants'] = $this->tenant->getTenants();
$data['tenants_categories'] = $this->tenant_category->find(1);
$echo $this->load->view('bhs/shop', $data);
}
when your view content ge that time you give third parameter in $
$this->load->view('view name',$data,true);
true mean retrun content.
public function shop()
{
$data['tenants'] = $this->tenant->getTenants();
$data['tenants_categories'] = $this->tenant_category->find(1);
$content= $this->load->view('bhs/shop', $data,TRUE);
echo $content;
}

Session preservation

I read all other question but nothing really helped.
I have one page with display and other php files supporting it but when I pass a POST and make a $_SESSION['view'] out of it with another POST request but not same one the $_SESSION['view'] is gone.
So in practic when user change view from four months (default) to one month and then click NEXT view gets back to four months.
Display Page
<?php
session_start();
$dateb = (new DateTime())->getTimestamp();
$_SESSION['usrdate'] = $dateb;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="site.css" type="text/css" rel="stylesheet">
<script>
$(document).ready(function () {
$("#four").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
view: "four"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
$("#one").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
view: "one"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
$("#next").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
toggle: "next"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
});
</script>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="nav"></div>
<div id="loginform"><?php
/*require "navigation.php";*/
if (!isset($_SESSION['id'])) {
include "logon.php";
} else {
echo "<a href='logoff.php'>Logout</a>";
}
?>
</div>
<div id="loadplace">
<?php
if (isset($_SESSION['id'])) {
include "switcher.php";
}
?>
</div>
<div id="tog"><button type="button" id="prev">Prev</button>
<button type="button" id="next">Next</button></div><br/><br/>
<div id="view"><button type="button" id="four">Four</button>
<button type="button" id="one">One</button></div>
</body>
</html>
Script
<?php
session_start();
$_SESSION['view'] = $_POST["view"];
$_SESSION['toggle']= $_POST["toggle"];
$tog = $_SESSION["toggle"];
if ($_SESSION['view'] == "four") {
include_once "four_m.php";
} elseif ($_SESSION['view'] == "one") {
include "calendar.php";
} elseif ($_SESSION['view'] == "week") {
include "week.php";
} elseif ($_SESSION['view'] == "day") {
include "day.php";
} else {
include "four_m.php";
}
?>

php function call with ajax

I am trying to call a php function when an HTML button is clicked.i have done some searching and found that its impossible to do this directly and i should use ajax.
so this is my attempt so far which is not working.this is my test.php and the function is also in this page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.NextPage').on('click', function() {
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
alert(response);
}
});
});
});
</script>
</head>
<body>
<button type="button" class="NextPage">go to nextpage</button>
<?php
if (isset($_POST['x'])) {
if ($_POST['x'] == 1) {
$data = function1();
echo json_encode($data);
exit;
}
}
function function1() {
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>
get the value of the x from ajax call.
$x = $_POST['x'];
then use it.
EDIT
First you have to check weather your variable is set or not..
if(isset($_POST[x]))
{
$x = $_POST['x'];
}
try this
I've practically used your code and got it working. Your PHP is just fine, as for your AJAX call, it must have success or done to benefit the returned data.
The code for reference is here
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<link rel="shortcut icon" sizes="196x196" href="">
<link rel="stylesheet" type="text/css" href="" />
</head>
<body>
<div id="abc"></div>
<button type="submit" class="NextPage">go to nextpage</button>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
JavaScript
$(document).ready(function() {
$('.NextPage').click(function() {
$.ajax({
type:'post',
url:'service.php',
data:{x:1}
}).done(function(data) {
$("#abc").text(data);
});
});
});
PHP
<?php
$x = $_POST['x'];
if ($x == 1) {
function1();
}
function function1() {
echo "This is function 1";
}
function function2() {
echo "This is function 2";
}
First off, you need to set your button to type="button", then, make an AJAX request, then the missing part on your code is the backend part which processes the request. Then the backend responds to that call. After that you can just do what you please on that response. Consider this example:
<?php
// this part handles the AJAX request
if(isset($_POST['x'])) {
if($_POST['x'] == 1) {
$data = function1();
// a call has made, then give a response
echo json_encode($data);
exit;
}
}
function function1() {
// do some processing
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>
<!-- make its type "button" -->
<button type="button" class="NextPage">go to nextpage</button>
<div id="notification"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.NextPage').click(function(){
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
$('#notification').html('Your ajax call has been successful<br/> and this is a notification').css({background: 'yellow'});
}
});
});
});
</script>
What makes you think it is impossible to call a php function directly. This is exactly what is done in CodeIgniter PHP MVC framework. You can call a php function with arguments inside a php class directly in CodeIgniter and that is actually what is done always.

Error in displaying the ajax result using Codeigniter and Mysql

I just need a little help here about displaying my table query result. When i checked the response from my ajax I shows. But when passing to the views it doesn't shows. Here's my code:
Controller/user.php
<?php
class User extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('user_model');
}
public function index(){
$this->load->view( 'index' );
}
public function read() {
echo json_encode( $this->user_model->getAll() );
}
}
?>
Model/user_model.php
<?php
class User_Model extends CI_Model{
public function __construct(){
parent::__construct();
}
public function getAll(){
$qGetAllData = $this->db->get('user');
if($qGetAllData->num_rows() > 0){
return $qGetAllData->result();
}else{
return array();
}
}
}
?>
View/index.php
<html>
<head>
<title><?php echo $title; ?></title>
<base href="<?php echo base_url(); ?>" />
<link type="text/css" rel="stylesheet" href="css/smoothness/jquery-ui-1.8.2.custom.css" />
<link type="text/css" rel="stylesheet" href="css/styles.css" />
</head>
<body>
<table id="records"></table>
<div id="tabs">
<ul>
<li>Read</li>
<li>Create</li>
</ul>
<div id="read">
<table id="records"></table>
</div>
<div id="create"></div>
</div>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery-templ.js"></script>
<script type="text/template" id="readTemplate">
<tr>
<td>${id}</td> //doesn't display ID
<td>${name}</td> //doesn't display Name
<td>${email}</td> //doesn't display EMial
</tr>
</script>
<script type="text/javascript" src="js/myjs.js"></script>
</body>
</html>
Javascript/myjs.js
$(document).ready(function(){
$( '#tabs' ).tabs({
fx: { height: 'toggle', opacity: 'toggle' }
});
$.ajax({
url: 'index.php/user/read',
datatype: 'json',
success: function(response){
$('#readTemplate').render(response).appendTo('#records');
}
});
});
That's all guys. I just don't know where's my error.
I think you have issue with just render data.
please review this link for reference.
Please try below code.
Your html : View/index.php
<html>
<head>
<title><?php echo $title; ?></title>
<base href="<?php echo base_url(); ?>" />
<link type="text/css" rel="stylesheet" href="css/smoothness/jquery-ui-1.8.2.custom.css" />
<link type="text/css" rel="stylesheet" href="css/styles.css" />
</head>
<body>
<table id="records"></table>
<div id="tabs">
<ul>
<li>Read</li>
<li>Create</li>
</ul>
<div id="read">
<table id="records"></table>
</div>
<div id="create"></div>
</div>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery-templ.js"></script>
<script type="text/javascript" src="js/myjs.js"></script>
</body>
</html>
Your JS : js/myjs.js
var readtpl = "<tr><td>${id}</td><td>${name}</td><td>${email}</td></tr>";
$.template( "readTemplate", readtpl );
$(document).ready(function(){
$( '#tabs' ).tabs({
fx: { height: 'toggle', opacity: 'toggle' }
});
$.ajax({
url: 'index.php/user/read',
datatype: 'json',
success: function(response){
$.tmpl( "readTemplate", response ).appendTo( "#records" );
}
});
});

Ajax load via jquery, content not shown

hi i have a html file which use ajax for loading contents from other html files in the same server. for some reason it does not work?? i have no clue as i am new to ajax.
here is the index.html(default home page)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<script type="text/javascript" src="../jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head><body><div id="rounded">
<img src="img/top_bg.gif" alt="top" /><div id="main" class="container">
<h1>ajax example</h1>
<h2>ajax jquery</h2>
<ul id="navigation">
<li>Page_1</li>
<li>Page2</li>
<li>Page_3</li>
<li>Page_4</li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
<div class="clear"></div>
<div id="pageContent">
it is a test</div>
</div><div class="clear"></div>
<img src="img/bottom_bg.gif" alt="bottom" /></div>
</body>
</html>
script.js(for adding hash in the url and enable back button and also loading content)
ar default_content = "";
$(document).ready(function () {
checkURL();
$('ul li a').click(function (e) {
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()", 250);
});
var lasturl = "";
function checkURL(hash) {
if (!hash) hash = window.location.hash;
if (hash != lasturl) {
lasturl = hash;
if (hash == "")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url) {
var datastring = url.replace('#', '');
$('#loading').css('visibility', 'visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'datastring=' + datastring,
dataType: "html",
async: false,
success: function (msg) {
if (parseInt(msg) != 0) {
$('#content').html(msg);
$('#loading').css('visibility', 'hidden');
}
}
});
}
and load_page.php
<?php
$url = $_REQUEST['datastring'];
echo $url;
if(file_exists(''.$url.'.html')){
echo file_get_contents(''.$url.'.html');
}
else{
echo 'There is no such page!';
}
?>
need help! as you can see when the ajax calls the "pagecontent" div loads the content from the requested page, but nothing happens here! what am i doing wrong?
Looks like you have "#content' in the ajax response handler... should be '#pageContent' to match the div id. That is:
success: function (msg) {
if (parseInt(msg) != 0) {
$('#pageContent').html(msg);
$('#loading').css('visibility', 'hidden');
}
}

Categories