I'm having an issue with getting data from Controller, I have tried all the solutions here but it's the same..
when I click on the button it says 404 not found, if I change the URL to completed URL included the controller class name + function name, it says 403
Here is my view code :
<h2>Quiz</h2>
<script type="text/javascript">
$(document).ready(function(){
var BASE_URL = '<?php echo base_url(); ?>';
$('#show').click(function(e){
console.log(BASE_URL);
$.ajax({
url: BASE_URL + "Quiz/get_item",
dataType:'text',
type:"POST",
success: function(result){
var obj = $.parseJSON(result);
console.log(obj);
}
})
})
});
</script>
<button id="show">Show Cutomers</button>
<div id="customers-list"></div>
<p>Our first multi-page CodeIgniter application! Each page has its own controller and view!</p>
Here is my Controller code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Quiz extends CI_Controller {
var $TPL;
public function __construct()
{
parent::__construct();
$this->load->model('Quiz_data');
// Your own constructor code
}
function show_customers()
{
$query = $this->db-> query("SELECT * FROM quiz ORDER BY id;");
$this->TPL['listing'] = $query->result_array();
$this->template->show('quiz', $this->TPL);
}
public function index()
{
$this->template->show('quiz', $this->TPL);
}
public function get_item(){
$data = $this ->Quiz_data->get_data();
echo json_encode($data);
}
}
Here is my Model code :
<?php
class Quiz_data extends CI_Model {
public function get_data()
{
$query = $this->db->get('quiz');
return $query -> result_array();
}
}
What is the output of
console.log(BASE_URL);
Didnt mess with CI for quite a while, but it used to need /index.php/ in the URL. Try:
url: BASE_URL + "/index.php/quiz/get_item",
Although the controller-name needs to start with a capital, it doesnt need to be called that way in the URL.
Make sure url: BASE_URL + "Quiz/get_item" provides the correct URL.
var BASE_URL = '<?php echo base_url(); ?>'; May not provide trailing slash and you won't get correct url.
Try updating your call with following:
url: BASE_URL + "/Quiz/get_item",
Related
Visit here and the search bar in front is the autocomplete
it is working fine when I use on localhost and appends results in the li under but when I have uploaded on live server it shows 404.
This is the link to custom.js on which browser shows 404();
Main: Custom.js:
$(document).ready(function () {
$("#CompanyName").keyup(function () {
$.ajax({
type: "POST",
url: "http://www.sonnify.de/reviewotter/autocomplete/GetCompanyName",
data: {
keyword: $("#CompanyName").val()
},
dataType: "json",
success: function (data) {
if (data.length > 0) {
$('#Dropdowncompany').empty();
$('#CompanyName').attr("data-toggle", "dropdown");
$('#Dropdowncompany').dropdown('toggle');
alert("i am here");
}
else if (data.length == 0) {
$('#CompanyName').attr("data-toggle", "");
}
$.each(data, function (key,value) {
if (data.length >= 0)
$('#Dropdowncompany').append('<li role="displayCompanies"
id="displayCompanies" ><a role="menuitem
dropdowncompanyli" class="dropdownlivalue">' +
value['CompanyName'] + '</a></li>');
});
}
});
});
$('ul.txtcompany').on('click', 'li a', function () {
$('#CompanyName').val($(this).text());
var CompanyName = $(this).text();
alert(CompanyName);
window.location.href = "http://localhost/reviewotter/company2?
company="+CompanyName+"";
//window.location.href = "http://localhost/reviewotter/company2?
lat="+elemA+"&lon="+elemB+"&setLatLon=Set";
});});
Model: datacomplete.php:
<?php
class Datacomplete extends CI_Model{
public function GetRow($keyword) {
$this->db->order_by('Id', 'DESC');
$this->db->like("CountryName", $keyword);
return $this->db->get('company')->result_array();
}}
Controller: autocomplete.php
<?php
class Autocomplete extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('datacomplete');
}
public function index(){
//$this->load->view('view_demo');
$this->load->view('home');
}
public function GetCompanyName(){
$keyword=$this->input->post('keyword');
$data=$this->datacomplete->GetRow($keyword);
echo json_encode($data);
}
}
?>
Let me guess, localhost is on a Windows machine but the live server is Linux? Then it is probably a case sensitivity problem. Linux is a case-sensitive OS.
The model file datacomplete.php should be Datacomplete.php (Notice the uppercase first character?) and the controller autocomplete.php should be Autocomplete.php.
You will be able to get this resolved by adding a custom route. Please add below line to application/config/routes.php file.
$route['autocomplete/get-company-name'] = 'Autocomplete/GetCompanyName';
You will have to adjust your JQuery AJAX function according to the new URL. Also can remove the index.php from the URL. Please refer below link.
https://www.codeigniter.com/userguide3/general/urls.html#removing-the-index-php-file
I have a view inside which I have a button on which after a click I would like to retrieve some data from the controller.
This is inside the view:
<script>
$('.ajaxBtn').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/ajaxController',
data: "",
dataType:'json',
success : function(response){ console.log(response); alert(response)}
});
});
</script>
My controller looks like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ajaxController extends MY_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
echo json_encode("datafromajax");
}
}
And I have a route defined like this:
$route['ajaxControl'] = "ajaxController/index";
However I have no response data even though the response is 200.
Thanks for any help
EDIT2// Loading a JSON from for an online source works fine
EDIT// Response:
XHR Loaded (index - 200 OK - 39.48300000047311ms - 35.38KB) VM3852:3
http://davids-macbook-pro.local:5757/ajaxController/index VM3853:3
Object {startedDateTime: "2016-04-09T08:45:16.133Z", time:
39.48300000047311, request: Object, response: Object, cache: Object…}cache: Object__proto__: Object__defineGetter__:
defineGetter()defineSetter: defineSetter()lookupGetter: lookupGetter()lookupSetter: lookupSetter()constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf:
isPrototypeOf()propertyIsEnumerable:
propertyIsEnumerable()toLocaleString: toLocaleString()toString:
toString()valueOf: valueOf()get proto: get proto()set
proto: set proto()connection: "122019"pageref: "page_7"request: ObjectbodySize: 0cookies: Array[2]headers:
Array[11]headersSize: 1099httpVersion: "HTTP/1.1"method:
"POST"queryString: Array[0]url:
"http://davids-macbook-pro.local:5757/ajaxController/index"proto:
Objectresponse: Object_transferSize: 35380bodySize: 34973content:
Objectcookies: Array[0]headers: Array[10]headersSize: 407httpVersion:
"HTTP/1.1"redirectURL: ""status: 200statusText: "OK"proto:
ObjectstartedDateTime: "2016-04-09T08:45:16.133Z"time:
39.48300000047311timings: Object__proto__: Object
Chnage the string to array in json_encode()
From echo json_encode("datafromajax"); To echo json_encode(['data'=>"datafromajax"]);
You need to define base_url()
eg.
$arr = array("str"=>"datafromajax");
echo json_encode($arr);
And in the ajax function
url: <?php echo base_url();?> +'ajaxController'
success : function(response){ console.log(response.str); alert(response.str)}
Ajax Auto-complete search with Code-igniter from my database. I am trying to search my database and Ajax completes the search from items saved on my database. I believe I am missing a simple trick. Maybe I am writing my controller or maybe everything all wrong... Code below
// View Page
Location path: application/views/template/header
<form class="navbar-form" >
<input type="text" id="mysearch" placeholder="search" onkeyup="doSearch();">
<br />
<script>
// This is the jQuery Ajax call
function doSearch()
{
$.ajax({
type: "GET",
url:"localhost/codeigniter/index.php/ajax/getdata/" + $("#mysearch").val(),
success:function(result){
$("#searchresults").html(result);
}});
}
//class example
</script>
Note: My form or search box is inside my header... So my view page is located in template/header
// Controller Page
Location path: codeigniter/application/controller/ajax.php
class Ajax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('ajax_model');
//$this->load->helper('url_helper');
}
public function form ()
{
$data['title'] = 'Ajax search';
$this->load->view('template/header');
}
// function ends
public function getdata($param = '')
{
// Get data from db
$data['ajaxdata'] = $this->ajax_model->search($param);
// Pass data to view
$this->load->view('template/header', $data);
}
}
?>
// My Model
Location path: application/model/Ajax_model.php
<?php if (! defined('BASEPATH')) exit('No direct script access');
class Ajax_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function search ($title){
$this->db->select('title');
$this->db->select('text');
$this->db->like('title', $title, 'both');
return $this->db->get('news');
}
}
?>
Please be aware I am new to CodeIgniter. It explains my rather obvious ignorance
$data['ajaxdata'] = $this->ajax_model->search($param);
$data['ajaxdata'] = json_encode($data['ajaxdata']);
echo $data['ajaxdata'];
Ajax method expects data in form of (JSON) string. So you don't need to load header again. Instead, just pass needed data from DB and jQuery will put it in designated place. In this case into element with id of searchresults.
Try changing this
$this->load->view('template/header', $data);
to
$content = $this->load->view('template/header', $data,TRUE);
// load view to a variable.
echo $content;
if i am clear what you need try:
first define ajax request type:
function doSearch()
{
$.ajax({
type: "GET",
dataType:"html",
url:"localhost/codeigniter/index.php/ajax/getdata/" + $("#mysearch").val(),
success:function(result){
$("#searchresults").html(result);
}});
}
Then in controller :
just echo your view:
$auto_complete_html = $this->load->view('template/header', $data,TRUE);
echo $auto_complete_html;
//good practice always die(); after ajax called
die();
Try using POST in AJAX instead of GET:
<script>
// This is the jQuery Ajax call
function doSearch()
{
var search = $("#mysearch").val()
$.ajax({
type: "POST",
url:"localhost/codeigniter/ajax/getdata/",
data:'search=' + search,
success:function(data){
$("#searchresults").html(data);
}});
}
//class example
</script>
Then in your controller Get THE POSTED data from AJAX
public function getdata()
{
$param= $this->input->post('search');
// Get data from db
$result = $this->ajax_model->search($param);
// Pass data to view
echo $result;
}
I'm trying to send a POST value inside a PHP class by Ajax, to change my SQL query.
PHP Page
//Link page with Classes
require_once('mPortfolio.php');
$mPortfolio = new Portfolio();
$all = $mPortfolio->getAll();
//Echo sql results here
//AJAX to send filter value to PHP with Classes
$('#filters a').on('click', function(e){
var filter = $(this).data('filter');
$.ajax({
type: 'POST',
url: 'models/mPortfolio.php',
data: {filter: filter},
success: function(data){
alert(data);
}
});
PHP Classes mPortfolio.php
echo $_POST['filter']; //This works !
require_once $_SERVER["DOCUMENT_ROOT"].'/models/db/db.php';
class Portfolio{
private $_db;
public function Portfolio()
{
$this->_db = new db();
$this->_db->SQLRequest("SET NAMES utf8");
}
public function getAll()
{
if(isset($_POST['filter'])) :
$query = "SELECT * FROM portfolio WHERE category='".$_POST['filter']."' AND online = 1 ORDER BY category,pos ASC";
else :
$query = "SELECT * FROM portfolio WHERE online = 1 ORDER BY category,pos ASC";
endif;
return $this->_db->SQLRequest($query);
}
}
The mPortfolio.php page can actually read the $_POST['filter'] outside the Class, but the public function getAll() cannot.
Can you help me please make it work.
Thanks
Somewhere, you must be creating an object of Portfolio class, and calling getAll(). From there, pass the $_POST['filter'] to getAll like
$portfolioObj = new Portfolio();
$portfolioObj->getAll($_POST['filter']);
The below 2 lines must be inside another PHP, which will include the mPortfolio.php
Add following code:
$portfolio = new Portfolio();
$returnData = $portfolio->getAll();
echo $returnData;
below the class declaration.
This is because of class and functions cann't call directly. You need to call them for class you need to create the instance and then call the function inside the class. Without calling the class or function you cann't execute them.
use
$('#filters a').on('click', function(e){
var filter = $(this).data('filter');
$.ajax({
type: 'POST',
url: 'models/mPortfolio.php/getAll/filter/$_POST['filter']',
data: {filter: filter},
success: function(data){
alert(data);
}
});
and get value in getAll function
OR
$filter = $_POST['filter'];
$portfolio = new Portfolio();
$return = $portfolio->getAll($filter);
echo $return;
in one of my front end PHP files im doing this in my Jquery :
var name = $('#core_name').val();
var param = {};
param['name'] = name;
$.ajax({
url:'../back_end/user.php/verify_name',
data:param,
type:'POST',
success:function(result){
alert(result);
}
});
In my back_end/user.php im doing this :
<?php
class User{
function index(){
//for now do nothing
}
function verify_name(){
echo "here";
}
}
?>
Why cant i alert "here", what is it that iam doing wrong ?
Firebug detects no error , so the file user.php has correct path (no 404 error) why cant i reach the function verify_name ?
You need to instantiate the User class and call verify_name() on back_end/user.php.
You can do this adding the following to back_end/user.php:
$user = new User;
$user->verify_name();