Kohana with AJAX get request - php

I am new to the world of Kohana/php and am having some issues understanding how to get the result of an ajax request. This request is being called from a click action and is invoking the following method.
function addClickHandlerAjax(marker, l){
google.maps.event.addListener(marker, "click",function(){
console.log(l.facilityId);
removeInfoWindow();
//get content via ajax
$.ajax({
url: 'map/getInfoWindow',
type: 'get',
data: {'facilityID': l.facilityId },
success: function(data, status) {
if(data == "ok") {
console.log('ok');
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
}
Inside of my controller I have a method
public function action_getInfoWindow(){
if ($this->request->current()->method() === HTTP_Request::GET) {
$data = array(
'facility' => 'derp',
);
// JSON response
$this->auto_render = false;
$this->request->response = json_encode($data);
}
}
I see an HTTP request in fiddler and it passed the correct facilityID parameter. However I am having some disconnect about how to connect all the pieces together.

To send a response to the browser, you should user Controller::response instead of Controller::request::response. So your code should look like this:
public function action_getInfoWindow() {
// retrieve data
$this->response->body(json_encode($data));
}
That should give you some output.
Checkout the Documentation for more detailed info.
Edit
What you could do, to make your life a bit easier, especially if you gonna use ajax requests a lot, is to create an Ajax controller. You can stuff all checks and transforms in it, and never worry about it anymore. An example controller could look like below. Also checkout the Controller_Template which is shipped as an example by Kohana.
class Controller_Ajax extends Controller {
function before() {
if( ! $this->request->is_ajax() ) {
throw Kohana_Exception::factory(500, 'Expecting an Ajax request');
}
}
private $_content;
function content($content = null) {
if( is_null( $content ) ) {
return $this->_content;
}
$this->_content = $content;
}
function after() {
$this->response->body( json_encode( $this->_content ) );
}
}
// example usage
class Controller_Home extends Controller_Ajax {
public function action_getInfoWindow() {
// retrieve the data
$this->content( $data );
}
}

Related

store php response in angularjs service, then get them in controller

So, I am new to angularjs. I want to use MVC structure. So, I was thinking that storing the response from php in my service, then use them in my controller.
Service:
(function () {
angular.module('dataService').service("incidentService", function ($http) {
var Data = [];
return ({
getData: __getData
});
function __getData() {
return Data;
}
function __setData($http, $q) {
var defer = $q.defer();
$http.get('PHP/NAME.php',{cache : 'true'}).
success(function(data){
Data = data;
console.log(Data);
defer.resolve(data);
defer.promise.then(function(data){
Data = data;
console.log(Data);
});
});
}
})})();
Controller:
(function () {
angular.module('app')
.controller('Ctrl', Ctrl);
/** #ngInject */
function Ctrl($scope, $http, $q,baConfig, incidentService) {
incidentService.setData($http,$q)
var DataSet = incidentService.getData();
console.log(DataSet);
}
})();
By doing this way, the problem is my dataSet does not get updated when the data array in my service is updated. I know that we can return a defer promise to controller to get the data, but can we set the data first in service, then use get method to use them?
OK, I think the biggest issue with why this doesn't work is because you're assigned the data returned by the $http call to nData rather than just Data.
The next issue is that there's not a getMonthlyData method defined on the service.
That being said, this looks overly complicated.
Your service should look more like this:
(function () {
angular.module('dataService').service("incidentService", function ($http,$q) {
var service
service.getData = __getData()
return service
function __getData() {
if (!service.Data) {
return $http.get('PHP/NAME.php',{cache : 'true'}).then( function(data) {
service.Data = data
return $q.when(service.Data)
})}
else {
return $q.when(service.Data)
}
}
})})();
Then in your controller you just get the data via incidentService.getData()

How to send/return data/value from CI_Controller to AJAX

As the title, i want to CI_Controller return value/data back to AJAX which give request before.
The_Controller.php
class The_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
function postSomething()
{
$isHungry = true;
if(isHunry){
return true;
}else{
return false;
}
}
}
AJAX
$(document).ready(function()
{
$('#form').on('submit', function (e)
{
e.preventDefault(); // prevent page reload
$.ajax ({
type : 'POST', // hide URL
url : '/index.php/The_Controller/postSomething',
data : $('#form').serialize (),
success : function (data)
{
if(data == true)
{
alert ('He is hungry');
}
else
{
alert ('He is not hungry');
}
}
, error: function(xhr, status, error)
{
alert(status+" "+error);
}
});
e.preventDefault();
return true;
});
});
The Problem :
The AJAX code above always get FALSE for variable data. It's not get return value from postSomething function inside CI_Controller.
The Question :
I want to if(data == true) result alert ('He is hungry');. But cause data not fill by return value of postSomething function inside CI_Controller so it always false. How to get return value/data from CI_Controller to AJAX?
Thank you
you need to change your code a little bit. no need to return data, just echo true or echo false from your controller. Hope you will get your desired result.
You have a typo in the PHP code
if(isHunry){
should be
if($isHungry){
Also, returning data to an AJAX request, you really should be sending the correct content type in the header. Ex.
header('Content-Type: application/json');
And print or echo the data, not return it, as well as json_encode it:
echo json_encode($data);
So your postSomething php function should look something like this:
$isHungry = true;
header('Content-Type: application/json');
echo json_encode($isHungry);

Cannot send POST data by JQuery to controler MVC writted in PHP

I would like to send data by POST method , which will be send by $.ajax metod on JQuery from formulage. I am trying to send this data to controler writted in PHP. I dont know much about MVC but I have read that controller is responsible for collecting data from user for example by completing formulage.
Here is the code :
`$.ajax({
type: 'POST',
url: 'http://www.somepage.pl/index.php?strona=uzytkownicy',
data: {
login: hLogin_u,
nazwaOddzialu: hNazwaOddzialu,
haslo: hPassword,
nazwa: hNazwa_u,
tylkozip: hTylkoIP,
uprawnienia: myDataCheck
},
timeout: 5000,
cache: false,
success: function(msg){
alert('Zapytanie zakonczylo sie sukcesem! Zwrócone dane to '+msg);
},
beforeSend: function() {
$('#errorDiv').show();
//alert('zaraz wysle sie ajax');
},
error: function(){
$('#errorDiv').html('<p>Przepraszamy wystąpił błąd!</p>').show();
//alert('error nastapil');
}
});
I know that only wrong is URL address but I don't know how to send this data to controller. How is correct url.
For example controller name is controler.php and is in directory /contr/controler.php
How is correct url for this configuration.
Am I doing something incorrect sending this data to controller?
I am giving you the code of controller : Maybe this will help to solve the problem.
class Controller // kontroler
{
// składowe
private $strona;
private $model;
private $widok;
// konstruktor
public function __construct()
{
$this->loadModel();
$this->takeData();
$this->loadView();
$this->runView();
}
// załadowanie odpowiedniego modelu
private function loadModel()
{
if (Autoryzacja::czyZalogowany() == false)
{
$this->strona = "logowanie";
}
else
{
if (!isset($_GET['strona']))
{
$this->strona = "glowna";
}
else
{
$this->strona = Narzedzia::security_get($_GET[strona]);
global $baza;
$baza->execute("SELECT 1 FROM wiadomosci WHERE
wiadomosci.pracownik in (1,8) AND
NOT EXISTS
(SELECT 1 FROM wiadomosci_przeczytania WHERE
wiadomosc=id_wiadomosci AND
pracownik=$_SESSION[zalogowany_id_c9])");
if ($baza->count() > 0)
{
$this->strona = "glowna";
}
}
}
$dane=array("logowanie","glowna","dodajw","kalkulator","hasla","zarzadzaj","edycja","chat"," skan",
"logi","ajax_logi","kalendarz","ajaxkalendarz","uzytkownicy");
if (!in_array($this->strona,$dane))
{
$this->strona = "glowna";
}
$this->model = new $this->strona();
}
// załadowanie danych przez model
private function takeData()
{
$this->model->loadData();
}
// załadowanie odpowiedniego widoku
private function loadView()
{
$w = $this->strona."_widok";
$this->widok = new $w($this->model);
}
// uruchomienie widoku
private function runView()
{
$this->widok->show();
}
}`

Calling php class function in javascript (ajax)

I was wondering if is there any good practices to call method from php class with Javascript, by the way of Ajax.
This is my current "style" to execute it.
(The method in the class are only here for example)
PHP side :
<?php
if(isset($_POST['action']) && $_POST['action'] != null)
{
extract($_POST);
if($action)
{
$ajaxCommand = new EleveUpdate();
if(method_exists($ajaxCommand, $action))
{
$reponse = call_user_func(array($ajaxCommand, $action),$_POST);
echo $reponse;
exit(0);
}
else
{
throw new Exception("Cette méthode n'existe pas");
}
}
}
else
{
echo 'Cette action n\'est pas autorisée';
return false;
}
class EleveUpdate
{
public function __construct()
{
}
public function testfunct($data)
{
echo $data['eleve'];
}
}
Javascript side:
$(document).ready(function() {
$.ajax({
url: 'eleveupdate.php',
type: 'POST',
data: {
action: "testfunct",
eleve: 1
},
beforeSend: function()
{
loading(true);
},
error: function()
{
console.log('error');
},
success: function(data)
{
loading(false);
console.log(data);
}
});
});
The problem is that the isset $_POST is always in my class, I'm pretty sure this is not the right way to do it so, I'm here to found help about it.
Thanks you in advance
Simon
The problem is it's not easy to call scope-namings based on a string-request.
You can use something called LAMBDA, or anonymous functions. This way you can store an array of strings with a LAMBDA attached to them. Like this:
<?php
class EleveUpdate {
private $funcs = array();
function __construct($which_function) {
$funcs['testfunct'] = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
$funcs[$which_function];
}
}
?>
See more info here: http://www.php.net/manual/en/function.create-function.php
You probably won't even need the Class anymore with this method, but just showing.

codeigniter and ajax cannot access the post

On my website I am using ajax post request to show content around my site, this is done using this code,
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
var data = "calltype=full&url="+url;
$.ajax({
url:url,
type: "POST",
data: data,
success : function (html) {
$('#left-content-holder').html(html);
}
})
});
as you can see I am passing the url into the `$_POST' and I can access this in the method the javascript calls, this method is called get_content_abstract and looks like this,
public function get_content_abstract() {
$this->load->model('content_model');
if($this->input->post('calltype') == "abstract"){
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
elseif($this->input->post('calltype') == "full") {
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['full'] = $query;
}
$this->load->view('template/full-content', $data);
}
}
How ever I have no added a new function that will allow the user to save the content to 'bookmarking system', however in my method I cannot access the post using codeigniters $this->input-post('url') (where URL is the one of peices of data passed in the javascript), it says that the post is empty when I var dump it, this is done using this method,
public function love_this() {
die(var_dump($this->post->input('url')));
}
can anyone help as to why the post is empty in this love_this method?
Shouldn't:
public function love_this() {
die(var_dump($this->post->input('url')));
}
Actually be
public function love_this() {
die(var_dump($this->input->post('url')));
}
See:
http://codeigniter.com/user_guide/libraries/input.html

Categories