call cakePHP element via Ajax - ajax

just a quick question, Is it possible to call a cakePHP element via jQuery Ajax? I know the standard way to call an element in cakePHP is:
<?php echo $this->element('path_to_element', 'data_to_send_to_element'); ?>
But what if I wanna call my element inside the $.ajax or .load() function? How do I achieve this?
Thank you

To call anything in Cake, by Ajax or otherwise, you need to define an action in a controller. You could create a view too, but you can also have the action render an element directly by setting the viewPath. Example:
class MyController extends AppController {
// Apply Ajax layout automatically
var $components = array('RequestHandler');
function doSomething() {
$this->autoRender = false;
... // set parameters needed by the element...
// render an element
$this->viewPath = 'elements';
$this->render('path_to_element');
}
}

Related

Insert a view using JS?

Is it possible to insert a view using javascript?
I wish to perform an ajax call, get the data, then insert a view in to a page and provide the data from the ajax call to that view?
Is this possible?
Yes you can use the render method on a view. Like so;
$view = View::make('your.view')->render();
And then return the html (which is the output) from your controller method by returning the data stored in $view.
If you need to add any data to the view just add the second parameter to the view make.
alternatively you can do this,
set the route for pages you want to call.
e.g.,
Route::get('callajax','PagesController#showAjax');
and then in PagesController#showAjax you return the view.
e.g.,
public function showAjax()
{
return View::make('ajaxpages');
}
and then in ajax call you code this
$.ajax({
url:'callajax',
});

Serialize Laravel Query Builder

I would like to be able to construct a query using laravel, and serialize it into a url string.
This would allow me to create routes which would unserialize a query builder, run the query, and make a view which displays the database results.
For example, to implement a button which refreshes a list of posts made by kryo:
http://example.com/ajax/posts.php?name=kryo&order_by=created_at&order_type=desc
Posts.php would simply be a route which unserializes, validates, and runs the query in the url params, and provides the results to a view.
Perhaps this is not useful in general, but I would personally find it handy specifically for ajax requests. If anyone knows how to implement this as a laravel plugin of some nature, that would be fantastic.
I'll try to give you a basic idea:
In Laravel you have to create a route to make a request to a function/method, so at first you need to create a route which will be listening for the ajax request, for example:
Route::get('/ajax/posts', array('uses' => 'PostController#index', 'as' => 'showPosts'));
Now, create a link in the view which points to this route, to create a link you may try this:
$url = to_route('showPosts');
If you use something like this:
<a class='ajaxPost' href="{{ $url }}?name=kryo&order_by=created_at&order_type=desc">Get Posts</a>
It'll create a ink to that route. So, make sure you are able to pass that $url to your JavaScript or manually you can write the url using /ajax/posts?name=.... Once you done creating the link then you need to create your JavaScript handler for this link (maybe using click event) then handle the click event from your handler, make ajax request, if it's jQuery then it could be something like this:
$('.ajaxPost').on('clcik', function(e){
e.preventDefault();
var url = $(this).attar('href');
$.getJSON(url, function(response){
$.each(response, function(key, value){
// loop... you may use $(this) or value
});
});
});
In your PostController controller class, create the index method:
class PostController extends BaseController {
public function index()
{
$name = Input::get('name');
$order_by = Input::get('order_by');
$created_at = Input::get('created_at');
$order_type = Input::get('order_type');
$posts = Post::whereName($name)->orderBy($order_by, $order_type)->get();
if(Request::ajax()) {
return Response::json($posts);
}
else {
// return a view for non ajax
}
}
}
If you want to send a rendered view from the server side to your JavaScript handler as HTML then change the getJson to get and instead of return Response::json($posts); use
return View::make('viewname')->with('posts', $posts);
In this case make sure that, your view doesn't extends the master layout. This may not be what you need but it gives you the idea how you can implement it.

Cakephp : add another view page link on the view page

sorry for asking this question ..i am working on a Cakephp 2.x ... i have a view page in my controller name folder e.g Controller/index.ctp ... and i have ajaxfiles are stored in app/webroot/ajax/ajaxfile.html
now on my index.php file i am acessing the ajax page like this
<a href="ajax-demo/ajaxfile.html" class="file-link">
<span class="icon file-png"></span>
Simple gallery</a>
Controller
public function index(){
}
now the problem is i want to send the variables to both of my pages ... index.ctp and ajaxfile ... how can i do this ??what is the best approach to tackle these things ....
do i have to move the ajaxfiles from webroot and paste under the controller name folder?
if is it so then how can i send variables to ajax files which has no model and controller
please if any one know the solution then please advice me. and give an example too
There are different way to achieve this, here I'm writing the simplest one
First you need to move your "index.ctp" file to your "View/YOUR CONTROLLER NAME/" folder.
1) To access the variable in view you need to set it from your controller's method like this
public index(){
$this->set('yourVariable', 'Your Value');
}
2) To access the value in your view file (index.ctp), you need to call this variable like this
$yourVariable;//If you want to print this then you can write like this
echo $yourVariable;
3) To call a ajax file from your index.ctp the simplest method is to call a onclick event on this anchor, the onclick event will call a JAVASCRIPT method which will further make a ajax call and will place the output in an element in your index.ctp, The ajax call will further call your controller method (implement your html related logic here)
For example,
<span class="icon file-png"></span>Simple gallery
<div id="yourAjaxFileOutputReplaceMentDiv"></div>
4) create a javascript method in your JS file, this JS file must be loaded in your layout file.
function yourAjaxCallMethod(BaseURL,yourVarible)
{
//Initialize Ajax Method
var req = getXMLHTTP();//Let's this method Initialize your Ajax
if (req)
{
req.onreadystatechange = function() {
if (req.readyState == 4)
{
if (req.status == 200)
{
document.getElementById('yourAjaxFileOutputReplaceMentDiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
var URL = BaseURL+yourVarible+'/'+Math.random();
req.open("GET", URL, true);
req.send(null);
}
}
5) Your AJAX file related method in your controller "yourController". Set autoRender to False
public function ajaxMethod(){
$this->autoRender = false;
//Check $this->request['pass'] for arguments send from ajax call
$retreivedVariable = $this->request['pass'][0];
echo 'I retrieved variable'.$retreivedVariable;
}
However instead of writing core javascript and ajax method you can call the inbuild Ajax Helper for same.

Grails call ajax function before redirect?

I have a controller that has an ajax function and a seperate action that redirects the page. I want to know is it possible to make the ajax call when the link is clicked, but wait for the function to finish before the redirect action is called?
E.g.
<g:link controller="myController" action="myRedirectAction" before="saveData">link</g:link>
EDIT Added code
controller
def ajx_saveServiceGroup = {
//Code to save data to object
return
}
def saveConfigToRoLo = {
//code to save object to DB
redirect(action:"displayPDFSummary", id:orderId, params: [origSessionId: params.origSessionId, theSession: tempSession])
}
gsp
<g:link class="buttonSend" action="saveConfigToRoLo" id="${orderDataInstance.id}" params="[origSessionId: origSessionId, orderId: orderDataInstance.id, submitToBT: true]" before="ajx_saveServiceGroup">Submit</g:link>
you can have a remoteLink and then onSuccess callback you can change the windows.location to whatever you want !
A details description of what you are trying to achieve will help us provide better answers.

add iframe while calling controller to view in codeigniter

call controller to view i use this code..
i want to add "template/home/home" page in to iframe tag while calling controller to view.
how can i do?
class main_con extends Controller
{
function main_con()
{
parent::Controller();
// $this->freakauth_light->check('user');
$this->_container = $this->config->item('FAL_template_dir') . 'template/container';
$this->load->library('FAL_front', 'fal_front');
}
function index()
{
$data['redirect_page'] = 'template/home/home';
$this->load->vars($data);
$this->load->view($this->_container);
}
}
thank you in advance...
I'm not quite sure if I understand your problem but:
The iframe is in your view template right? So what you need to do is just print the content of your variable in the src attrib of the iframe.

Resources