my question is give it a way to parse a view file (.ctp) into a variable ?
I want to create a ajax function that gives a ctp file or better says the content of this back.
The call from the javascript to cakephp's controller work but now i doesnt now how i can get my specified ctp file in the template folder parse it into a variable and send it back to the javascript function.
Lets say, you are using the controller sites and the view is index.
app/Controller/SitesController.php:
public function index() {
if($this->request->is('ajax') {
// prepare output for ajax. best way to do is to prevent styled output
$this->render('TestView/index');
}
}
In your TestView/index.ctp you can now prepare your output for ajax and just call the controller/action URL by AJAX:
$.ajax({
url: "/sites/index",
success: function(reponse) {
console.log(response); // here comes the output from /sites/index
}
});
Related
I'm working with CodeIgniter 3 and I would have some advices about where storing scripts. I want to call with jQuery a php script that will send JSON datas to my Javascript function.
How to do a connection with my database inside this script using CodeIgniter database config file?
Here is my jQuery callback structure :
<?php
session_start();
header('Content-Type: text/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
$callback = array();
echo json_encode($callback);
I've stored this script in app/callback folder that I have made, but I don't know if I should store it outside app folder or not... How do you structure your CodeIgniter's projects?
Thanks for your advices :)
setup;
in your application/config/database.php configure your database connection
in your application/config/autoload.php ensure that the database library is enabled
here for more info for database setup
model;
in application/models/ create your thing_model.php which functions for accessing your database. for this example public function get_data() this function would produce your database JSON data output when called
here for more info to query your database
controller;
in your application/controllers/thing.php create an ajax function;
public function ajax()
{
if ($this->session->loggedin && $this->input->is_ajax_request()){
$action = $this->uri->segment(3);
if ($action === "pull"){
$forms = $this->thing_model->get_data();
//actions here
}
if ($action === "test"){
//actions here
echo "hello world!";
}
} else {
redirect('/homepage');
}
}
whats happening;
if ($this->session->loggedin && $this->input->is_ajax_request()){
here you are checking for security and that the request is ajax in nature
$action = $this->uri->segment(3); is grabbing a segment from the URI for actioning. eg. http://example.org/controller/ajaxmethod/this_action
if ($action === "pull"){ is returning data if your ajax was invoked to http://example.org/thing/ajax/pull
ajax;
in the jquery JSON ajax in your .js file (load the .js file in the footer of your view)
$('#buttonAction').click(function() {
//Jquery Ajax code here
$.ajax({
method: "POST",
dataType: "json",
url: global_path + "thing/ajax/pull",
data: { user_id: "1", data: "ABC" }
})
.done(function( data ) {
//process your JSON data here
});
});
whats happening;
jquery ajax datatype see here
url: global_path + "thing/ajax/pull", calls your controller ajax() method with the pull action.
notes;
in your __construct for the controller i would recommend putting in some testing here to secure only ajax requests to your function, and not the others for strict operations and unwanted unknowns.
you could put ajax to another controller if it suits your application. but this can create security headaches with duplicating checks etc.
If you want to call backend functions from jQuery you have to go with AJAX. Check docs here. See a simple example below.
$.ajax({
method: "POST",
url: "PATH_TO_YOUR_CONTROLLER_FUNCTION",
data: { field_name1: "Field value 1", field_name2: "Field value 2" }
}).done(function( msg ) {
console.log(msg);
});
If you have this script in your view (which is a php file), you'll be able to use php functions to set the path. For example:
url: "<?php echo base_url('your_controller/your_function')?>"
The db connection and all logic stays in the controller and is implemented as usual.
I've been doing some research on calling a PHP function within a file from jQuery and can't seem to find a proper way of doing this without it failing on me. I'm trying to create an intermediary (kind of) CMS with MVVM to create a single-page website with a WordPress base.
At the moment I'm stuck on a bit where I'm trying to access PHP functions in allocated files, I've seen examples here, here and here on how to do it with a function per file, but I'd like to be able to call a function in a file as it gives me a clearer overview.
I've checked the link and it's correct, the PHP file is called posts.php and its in the location defined by window.MODELS, however the function fetch_all doesn't get executed.
JavaScript
//call php function
var requestURL = window.MODELS + 'posts/fetch_all';
$.get(requestURL, function(data){
console.log('checking data: ', data);
}, 'json')
.done(function(passed){
console.log('it worked!');
})
.fail(function(failed){
console.log('it failed :( ');
});
PHP
public function fetch_all(){
return json_encode("this is fetch_all..."); //replace text to get all posts with get_posts()
}
The console shows the JavaScript fail: "it failed :( ". How do I get 'fetch_all' to be executed and return data?
The URL you're calling from jQuery must match the location of the .php file on your server, for instance the correct URL to call is:
var requestURL = window.MODELS + 'posts.php?action=fetch_all';
Then, inside your PHP file you have to select which function to call according to query parameters. You can add this code after your function declaration, in order to call the proper function depending on the 'action' query parameter:
if ($_REQUEST['action'] == 'fetch_all')
echo fetch_all();
else
echo json_encode( array( 'status' => 'error') );
Also remember that your output should be echoed in order to generate output and not simply returned.
Hope it helps,
A.
I'm developing a web app using Kohana PHP framework and I got stuck. I set a PHP variable in my Controller to use it in a View. I would like to update this variable in the View continuously without refreshing the page. What I'd like to do is show a chart in real time using data from an SQL database where the curves' data is stored in this PHP variable. How can I do this? Is it possible to update this variable directly in the View (using my function in the Model)?
You can create an AJAX request with Javascript to your application without reloading the page. What happens is that the request is made to your controller/action, there you can query your database and you can pass back whatever your like. The AJAX request can retrieve the returning data and do something with it (in our case, replace some content with the new content).
You have to include this Javascript code on your page. In this example I use jQuery to make the AJAX request:
$.ajax({
url: /do/something /* URL of your controller/action */
success: function(data) { /* the data variable will receive the new content from the controller/action */
$('#the_id_of_your_html_tag').html(data); /* replace the html content with the new data */
},
});
In your Kohana controller you have something like this:
class Controller_Do extends Controller_Template
{
public function action_something()
{
$this->auto_render = false;
// make some call to your database, use your model whatever
echo 'some string or variable';
return;
}
}
Your Html of your view will be like this (according to the example):
<div id="the_id_of_your_html_tag">something</div>
I have a PHP function
function ExportExcel()
{
// code
}
and a link on the page Download in Excel
<a>Download in Excel</a>
So what I want is when users clicks on that link, PHP function would be called and data will be downloaded in excel.
I may need to Ajax for that. How do I go about doing that ?
You could possibly just use a GET statement, so it would look something like this...
HTML
Download in Excel
PHP
function ExportExcel()
{
// code
}
if($_GET['init'])
{
ExportExcel();
}
here is the function i implemeted recently:
$('#toexcel').live("click",function() {
$.ajax({
url: "toExcel.php",
data: "sql="+encodeURIComponent(sql),
beforeSend: function(){
$("#wait").show();
},
complete: function(){
$("#wait").hide();
},
success: function(response){
window.location.href = response.url;
}
});
});
where sql variable actually stores sql query to the server,
and then toExcel.php if getting passed sql, submitting it to the server and outputs the result using PHPExcel() object.
EDIT
i think i understood what you trying to achieve. your ExporExcel() function already outputs the results you need, right? is so, then you can do it as follow:
$('#toexcel').click(function() {
$.ajax({
url: "toExcel.php", // should contain and _call_ you ExportExcel() function
beforeSend: function(){
$("#wait").show(); // this is loading img to show
},
complete: function(){
$("#wait").hide(); ;// this is loading img to hide once complete
},
success: function(response){
window.location.href = response.url;
}
});
});
first let me make sure you know php is only parsed when the page is first being distributed. If you click a link on the page, it has no idea the php function on the same page exists because the function only existed server-side while the code was being parsed. That being said, you can easily make a separate page called download.php and call your function on that page. Then your link can just link to that page.
If you want your custom download page to return to the user as an excel file, you can use custom php headers to convince the browser that it is downloading an excel file. (you'd have to specify the MIME type for excel files)
edit:
this would cause a download to start of an excel file created by your function call and activated by your link click. You don't need any JS or JQuery for this.
edit2:
here's example code for the download file to get you started
<?php
header("Content-type: application/excel");
print($data); /* print out the contents of the excel file here */
exit();
?>
If you do it like this, your php page will not redirect from your original page, but will bring up a download box from the browser instead. If your using csv files instead of xls files, you'll need to change the mime type.
you can handle the request in your js scrpit file
$("a").click(function(){
jQuery.ajax({
url: "path/to/controller",
type: "POST",
dataType: 'json',
data: {'mentod':'ExportExcel'},
success: successCallback,
error:failureCallback
});
});
Just provide link of that excel file in href of anchor , browser will download automatically
If your file form DB then providelink of excel.php , and in excel.php do processing of getting excel file and creation of it .
read this artical..do like that
I am building an application with codeigniter and I want to post some data using jQuery but for some reason it doesn't work. Here is the code what am I doing wrong ?
$.ajax({
url: "<?=site_url('requests/save')?>",
type: "POST",
data: data,
success:function(msg){
alert(msg)
}
});
I haven't written any code in the controller yet, just something simple to test it. Also as long as javascript is concerned that's about it. The ajax is trigered when the user clicks a button.
function save()
{
if($this->input->is_ajax_request()) {
echo 'ajax';
}
else
{
echo'sdfs';
}
}
Dante,
First make sure you load your helper:
$this->load->helper('url');
Also post the JAVASCRIPT for us, not the PHP. The Javascript is what is failing, not the CI PHP. You might have a PHP issue also on your controller for 'requests/save', have you checked that?
I believe you need to pass a cross site request forgery token.
If you set XSS to true in your config, then your form helper creates a hidden field that is required to be passed to your server.
Make sure you are properly collecting your form data. Easiest to use jquery the .serialize() function.
Load the url helper in the autoload.php. Your url in the ajax call should just be 'requests/save'.
Also php shorthand echo tags are a bad practice stick to
<?php echo ?>
for better code portability
Moved my comment to an answer
EDIT : to test the ajax, use the relative url instead use a php tag inline in your js, to your controller, which will work in any condition (in CI) whether you already removed the index.php from your url (using htaccess) or not by include the index.php in your url.
$.post('/index.php/request/save', { foo: 'bar' }, function (html) {
alert(html);
});
At targeted controller
function save()
{
if($this->input->is_ajax_request())
{
echo $this->input->post('foo') ? $this->input->post('foo') : 'Not Bar';
}
else
{
echo'Not from AJAX';
}
}
EDIT :
also make sure you have already load the url helper before using its function
$this->load->helper('url');