controller: welcome.php
public function lookup()
{
$keyword = trim($_GET['term']);
$data['response'] = 'false';
$query = $this->Main_tutorial->lookup($keyword);
print_r($query);
if( ! empty($query) )
{
$data['response'] = 'true';
$data['message'] = array();
$data['auto_com'] = array();
foreach( $query as $row )
{
$data['message'][] = array('tutorial_name' => $row['tutorial_name']);
$data['auto_com'][] = $row['tutorial_name'];
}
}
if('IS_AJAX')
{
echo json_encode($data['auto_com']);
}
else
{
$this->load->view('index',$data);
}
}
view: index.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>resource/css/jquery-ui.css">
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />
</head>
<body>
<input type="text" class="search-bg__text" name="tutorial_name" id="tutorial_name">
<script src="<?php echo base_url(); ?>resource/js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#tutorial_name").autocomplete({
source:"<?php echo base_url(); ?>welcome/lookup",
minLength:1,
select:function(b,c)
{
var a=c.item.value;
a=encodeURIComponent(a);
location.href=a+"-tutorial";
return false
}
});
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
</body>
</html>
model: Main_tutorial.php
public function lookup($keyword)
{
$this->db->select('tutorial_name')->from('tutorial');
$this->db->like('tutorial_name',$keyword,'after');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
In this code I want to create an autocomplete suggestion box using codeigniter. Now what happen when I write something inside the tutorial_name input field and inspect the element then select network and click on link it show me the output but can't see on display I don't know why ?. So how can I fix this issue ?Please help me.
Thank You
In autocomplete() you need output as json format. Here you are printing json data with echo json_encode($data['auto_com']); But before it you are also displaying data print_r($query);. Which create invalid json output. so you have to remove it. Also note that your if('IS_AJAX') will always become true
public function lookup()
{
$keyword = trim($_GET['term']);
$data['response'] = 'false';
$query = $this->Main_tutorial->lookup($keyword);
if( ! empty($query) )
{
$data['response'] = 'true';
$data['message'] = array();
$data['auto_com'] = array();
foreach( $query as $row )
{
$data['message'][] = array('tutorial_name' => $row['tutorial_name']);
$data['auto_com'][] = $row['tutorial_name'];
}
}
if('IS_AJAX') //This condition always become true
{
echo json_encode($data['auto_com']);
}
else
{
$this->load->view('index',$data);
}
}
Related
I want to convert Bootstrap Treeview plugin into CodeIgniter, it runs normally on core PHP but when I convert it into CodeIgniter, it shows only array result.
Result: My code output
Source: Bootstrap Treeview source I want to convert it into CodeIgniter
fetch.php - controller
<?php
class Fetch extends MY_Controller {
public function index() {
$this->load->view('dashboard');
// $query (= " SELECT * FROM country_state_city ";
$query = $this->db->query("SELECT * FROM country_state_city ");
// (" SELECT * FROM country_state_city ")->result_array() ;
//$output = array();
foreach ($query->result_array() as $row) {
$sub_data["id"] = $row["id"];
$sub_data["name"] = $row["name"];
$sub_data["text"] = $row["name"];
$sub_data["parent_id"] = $row["parent_id"];
$data[] = $sub_data;
}
foreach ($data as $key => &$value) {
$output[$value["id"]] = &$value;
}
foreach ($data as $key => &$value) {
if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
$output[$value["parent_id"]]["nodes"][] = &$value;
}
}
foreach ($data as $key => &$value) {
if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
unset($data[$key]);
}
}
echo json_encode($data);
}
}
?>
dashboard.php - view
<!DOCTYPE html>
<html>
<head>
<title>ajax jaquey tree grid</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script type="text/javascript" charset="utf8"
src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css"/>
<style>
</style>
</head>
<body>
<br/><br/>
<div class="container" style="width:500px;">
<h2 align="center">Make Treeview using Bootstrap Treeview Ajax JQuery with PHP</h2>
<br/><br/>
<div id="treeview"></div>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$.ajax({
url: "<?php echo base_url();?>fetch",
method: "POST",
dataType: "json",
success: function (data) {
$('#treeview').treeview({data: data});
}
});
});
</script>
If you want to load data using ajax request then no need to load it in index() function.
You have to load the only view in an index() and make another function for tree view like this:
You load all data on page load then also make ajax call which is not correct.
Controller:
<?php
class Test_c extends CI_Controller {
public function index() {
$this->load->view('test');
}
function tree() {
// $query (= " SELECT * FROM country_state_city ";
$query = $this->db->query("SELECT * FROM country_state_city ");
// (" SELECT * FROM country_state_city ")->result_array() ;
//$output = array();
foreach ($query->result_array() as $row) {
$sub_data["id"] = $row["id"];
$sub_data["name"] = $row["name"];
$sub_data["text"] = $row["name"];
$sub_data["parent_id"] = $row["parent_id"];
$data[] = $sub_data;
}
foreach ($data as $key => &$value) {
$output[$value["id"]] = &$value;
}
foreach ($data as $key => &$value) {
if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
$output[$value["parent_id"]]["nodes"][] = &$value;
}
}
foreach ($data as $key => &$value) {
if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
unset($data[$key]);
}
}
echo json_encode($data);
}
}
?>
Try like this. It works.
Rest of things is correct.
Hope you solve your error using my solution.
Greetings....
I have this code in my view file (searchV.php):
<html>
<head>
<title>Search Domains</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function noTextVal(){
$("#domaintxt").val("");
}
function searchDom(){
var searchTxt = $("#searchTxt").val();
var sUrl = $("#url").val();
$.ajax({
url : sUrl + "/searchC",
type : "POST",
dataType : "json",
data : { action : "searchDomain", searchTxt : searchTxt },
success : function(dataresponse){
if(dataresponse == "found"){
alert("found");
}
else{
alert("none");
}
}
});
}
</script>
</head>
<body>
<form id="searchForm">
<input type="text" id="searchTxt" name="searchTxt" onclick="noTextVal()" >
<input type="submit" id="searchBtn" name="searchBtn" value="Search" onclick="searchDom()" />
<input type="hidden" id="url" name="url" value="<?php echo site_url(); ?>" />
</form>
<?php
var_dump($domains);
if($domains!= NULL){
foreach ($domains->result_array() as $row){
echo $row['domain'] . " " . $row['phrase1'];
echo "<br/>";
}
}
?>
</body>
</html>
and below is my controller (searchC.php):
<?php
class SearchC extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('searchM');
}
public function index()
{
$data['domains'] = $this->searchM->getDomains();
$this->load->view('pages/searchV', $data);
switch(#$_POST['action']){
case "searchDomain":
echo "test";
$this->searchDomains($_POST['searchTxt']);
break;
default:
echo "test2";
echo "<br/>action:" . ($_POST['action']);
echo "<br/>text:" . $_POST['searchTxt'];
}
}
public function searchDomains($searchInput)
{
$data['domains'] = $this->searchM->getDomains($searchInput);
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo json_encode($res);
}
} //end of class SearchC
?>
Now I've done a test on the controller using switch to check if the json data passed was successful but it's always showing undefined.. What's wrong here? Can someone explain why the data is not recognized in the controller??
You aren't passing the data in via the url, so you need to use $this->input->post() to retrieve the data.
For example,
public function searchDomains()
{
$data['domains'] = $this->searchM->getDomains($this->input->post('searchTxt'));
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo $res;
}
I believe that the data is being correctly returned, but the problem is with your code check. The $.ajax function parses the JSON and transforms it into a JavaScript object. Therefore you would need to modify your code as follows:
if(dataresponse.res == "found"){ // Changed from dataresponse to dataresponse.res
alert("found");
}
else{
alert("none");
}
This should work for you.
I am facing one problem, I want to do something like this:
I want to toggle the EXTERNAL CSS when user is click on toggle button.
There are 5 different pages; there are:
Header
Footer
Main page
Contact us
About us
and I have 2 external style sheets:
style.css
style1.css
By default style.css is loaded.
Now when I click on toggle button then style1.css has to load, and when again click on toggle button style.css has to load and visa verse. I want to do something like this.
Is there anyone have an Idea regarding this. Please help me out!
CSS is loaded on header so when I click on toggle button I want to apply new style.css.
the problem i am facing is that when i am clicking on any other page at that time the default css is set but in my case i don't want that By default style.css is loaded now when user click on button style1.css is loaded now when user again click on button style.css is loaded when click again style1.css loaded and again style.css loaded i want to do something like this and this changes should be there for whole website of main! thnx for your valuable reply and wait for more accurate –
By doing something like this:
$("a").click(function () {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
See Applying stylesheets dynamically with jQuery
DEMO
See Stylesheet Switcher jQuery
<script src="script/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
if ($.cookie("css")) {
$("link").attr("href", $.cookie("css"));
}
$(document).ready(function () {
$("#nav li a").click(function () {
$("link").attr("href", $(this).attr('rel'));
$.cookie("css", $(this).attr('rel'), { expires: 365, path: '/' });
return false;
});
});
</script>
<ul id="nav">
<li>Original CSS</li>
<li>Larger Text</li>
<li>Something Different</li>
</ul>
try this
$("#btntoggle").click(function(){
if($("LINK[href*='style.css']").lenght() > 0){
$("LINK[href*='style.css']").remove();
addCss(path + "style1.css");
}else{
$("LINK[href*='style1.css']").remove();
addCss(path + "style.css");
}
});
function addCss(path){
var headID = $("head").get(0);
var newCss = document.createElement('LINK');
newCss.rel = 'StyleSheet';
newCss.type = 'text/css';
newCss.href= path;
newCss.media = 'screen';
headID.appendChild(newCss);
}
Note that i've added the default style sheet in the markup, in case the user got JS disabled. So you get some kind of a fallback.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style1.css">
<script type="text/javascript" src="../jquery-1.8.0.min.js"></script>
<script>
$(function(){
$("#change").click(function(){
$('head link').each(function(){
if($(this).attr('rel') == "stylesheet"){
if($(this).attr('href') == "style1.css"){
$(this).attr("href","style2.css");
} else {
$(this).attr("href","style1.css");
}
}
});
});
});
</script>
</head>
<body>
<button id="change">Change</button>
</body>
</html>
$url = Mage::helper("core/url")->getCurrentUrl(); // $url contain your current url
if(!isset($_SESSION['cssfile']) and !isset($_GET['l']))
{
/*$urlArr = explode("?",$url);
$tmpUrl = $urlArr[0];
$tmpUrl .= "?";
$andP = '';
$i=1;
for(;$i<count($urlArr);$i++)
{
$tmpUrl .= $andP.$urlArr[$i];
$andP = '&';
}
if($i>1)
$tmpUrl .= '&l=1';
else
$tmpUrl .= 'l=1';*/
//$urlGet = $tmpUrl;//$url."?l=0";
$_SESSION['cssfile'] = '1';
}
if(isset($_GET['l']) and $_GET['l']==0)
{
// $urlGet = $url."?l=1";
$_SESSION['cssfile'] = '0';
}
else if(isset($_GET['l']) and $_GET['l']==1)
{
// $urlGet = $url."?l=1";
$_SESSION['cssfile'] = '1';
}
if(isset($_SESSION['cssfile']))
{
$urlArr = explode("?",$url);
$tmpUrl = $urlArr[0];
$tmpUrl .= "?";
$andP = '';
$found = 0;
//for($i=1;$i<count($urlArr);$i++)
foreach($_GET as $key => $val)
{
if($key == 'l')
{
$found = 1;
if($val == 1)
$val = 0;
else
$val = 1;
}
$tmpUrl .= $andP.$key.'='.$val;
$andP = '&';
}
if($found == 0 && count($_GET)>0)
if($_SESSION['cssfile'] ==1)
$tmpUrl .= '&l=0';
else
$tmpUrl .= '&l=1';
else if($found == 0 && count($_GET)==0)
if($_SESSION['cssfile'] ==1)
$tmpUrl .= 'l=0';
else
$tmpUrl .= 'l=1';
$urlGet = $tmpUrl;
}
/*if(isset($_SESSION['cssfile']) and $_SESSION['cssfile'] == 'styles1.css' )
{
$_SESSION['cssfile'] = 'styles.css';
$_SESSION['cssfile']
}
else
{
$_SESSION['cssfile'] = 'styles1.css';
}*/
//echo '--'.$_SESSION['cssfile'];
if($_SESSION['cssfile'] ==1){
?>
<link href="<?php echo $this->getSkinUrl()?>css/styles1.css" rel="stylesheet" type="text/css" id="style" />
<?php }else{ ?>
<link href="<?php echo $this->getSkinUrl()?>css/styles.css" rel="stylesheet" type="text/css" id="style" />
<?php } ?>
I am currently learning jQuery and php.
So I have this php file that gets called with a jQuery function (there is another call somewhere else in the script where a=chkPw):
$.get("checkName.php?a=chkUser&user=" + rqUser, function(data) { ... });
My problem is that the php script doesn't seem to get in the if(isset($_GET)) { } block. I have debugged the value that it returns (1), so I don't understand what's wrong! I have also debugged the value for $_GET['a'] and it is indeed 'chkUser'.
Any help would be greatly appreciated.
<?php
$users = array('bill' => 'ore', 'ted' => 'wood');
if (isset($_GET)) {
if ($_GET['a'] == 'chkUser') {
if (!array_key_exists($_GET['user'], $users)) {
echo 'okay';
} else {
echo 'denied';
}
} elseif ($_GET['a'] == 'checkPw') {
$user = $_GET['user'];
$pw = $_GET['pw'];
$i = 0;
// get username id
foreach (array_keys($users) as $value) {
if ($value == $user) {
$user = $users[i];
}
i++;
}
// match pw
if ($pw == $user) {
echo 'okay';
} else {
echo 'denied'
}
}
}
?>
Hey it seems to me that this is working:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$.get("checkNames.php?a=chkUser&user=bill", function(data) { console.log(data) });
$.get("checkNames.php?a=chkPass&user=bill&pw=ore", function(data) { console.log(data) });
</script>
<?php
$users = array('bill' => 'ore', 'ted' => 'wood');
if (isset($_GET["a"])) {
if ($_GET["a"] == 'chkUser') {
if (!array_key_exists($_GET['user'], $users)) {
echo 'okay';
} else {
echo 'denied';
}
} elseif ($_GET["a"] == 'chkPass') {
$user = $_GET['user'];
$pw = $_GET['pw'];
if(array_key_exists($user, $users))
{
if($users[$user] == $pw)
{
echo "okay";
}
else
{
echo "denied";
}
}
else
{
echo "denied";
}
}
}
?>
Try this if statement instead of current
if (count($_GET) > 0) {
// existing code
}
Hope this will help you.
With a url like www.something.com/index.html?a=1 This code does in fact work on testing:
$users = array('bill' => 'ore', 'ted' => 'wood');
if (isset($_GET)) {
echo 'something';
}
Try commenting it down further to let us know if it is the whole whole elseif or just a part of it
You could try this:
<?php
if(!empty($_GET)){
...
}
?>
To be sure about the GET payload use var_dump($_GET)
I have a problem with dynamic loading of javascript function from Ajax.
I want to update some part of HTML with Ajax. Let's say I want to place a button and to attach a javascript function to that button dynamically.
For example:
...
<head>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function f_OnLoadMain()
{
fParseBrowserInfo();
getJSFromServer();
getHTMLFromServer();
}
</script>
</head>
<body onload="f_OnLoadMain()">
<div id="AjaxArea" width="100%" height="100%" align="left" valign="top" >
<!-- Updated with ajax -->
</div>
</body>
</html>
----- getJSFromServer() - calls to php code:
<?php
$somesource = '
function Clicked(){
alert("Clicked");
}
';
class TestObject{
public $source = "";
function TestObject()
{
$this->source = "";
}
function setSource($source){
$this->source = $source;
}
}
$ti = new TestObject();
$ti->setSource($somesource);
echo(json_encode($ti));
?>
the script is inserted with:
var oHead = document.getElementsByTagName('HEAD').item(0);
if (oScript){
oHead.removeChild(oScript);
}
oScript = document.createElement("SCRIPT");
oScript.type = 'text/javascript';
oScript.text = oScript.source;
oHead.appendChild( oScript);
And getHTMLFromServer() - call php :
<?php
$error = 0;
$someText = '
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
';
class TestObject{
public $src = "";
public $error = 0;
function TestObject()
{
$this->error = 0;
$this->src = "";
}
function setSrcString($sample){
$this->src = $sample;
}
}
$ti = new TestObject();
$ti->error = $error;
$ti->setSrcString($someText);
echo(json_encode($ti));
?>
Then the content is updated with:
var dynamicArea = document.getElementById("AjaxArea");
if(dynamicArea != null)
{
dynamicArea.innerHTML = obj.src;
}
And that works fine!
So, when the page loads the button is displayed ok, BUT pressing button doesn't call function Clicked().
Someone knows how to fix it?
Regards!
i guess you have to escape your apostrophe:
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
you see: onclick="Clicked()"
Together with: function Clicked(){ alert("Clicked"); }
It renders to: onclick="alert("clicked")"
Try to escape your apostrophe :)
Regards