I am currently using zend framework and working with jquery and php. Trying to implement an autocheck username availability.
For the following code, I need to call my user_availability.php which is in my controller folder. I did /controllers/user_availability, ../user_availability but it doesnt call that page. Can anyone help?
$.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
if you truely want to call a plain php file with zend framework, then you need to put it inside your public folder and call it as /user_availability.php but it should almost certainly be better to make user-availability an action of one of your controllers
Look into Action and View Helpers (depending on where you want to call the script from). Action Helpers can be called from controllers and may be kept in a .../project/library.
From a view you can call a custom View Helper you've written and stored in .../projectname/application/view/helpers.
You may want to restructure your code to fit better within the framework but simply creating a helper that requires (includes) your .php script should work.
View helpers (Survive the Deep End)
Action helpers (from the manual):
It appears you're making a page request to a non-controller item. Anytime you make a request in Zend Framework, it will attempt to match the URL of the request to a route in the system, which corresponds to a controller action. All of this is handled via your application's index.php file - the only way to serve a different php file directly would be through your public folder.
My suggestion is to create a controller action that checks for an Ajax request and returns something in your format of choice (XML, json) (rather than rendering an HTML template).
public function userAvailableAction()
{
if ($this->getRequest()->isXmlHttpRequest()) {
// check user availability
$this->_helper->json($data);
}
}
Thanks everyone. I found the solution to it.
You just need to put the function in the controller page and call the function name.
e.g:
$.post("check",{ user_name:$(this).val() } ,function(data)
Then in your controller file checkusername availability make sure you add the check function.
my controller page is as follows the code:
class RegisterController extends Zend_Controller_Action {
public function checkAction(){
$users = new Users();
$username = $_POST['username'];
if($users->checkUnique($_POST['username'])){
echo "fail";
}
}
In this case, the checkUnique is just an sql statement in my model controller to check if the username exist.
For my jquery code it is:
$("#username").blur(function(){
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("check",{ user_name:$(this).val() } ,function(data){
if(data=='no'){ //if username not avaiable
$("#msgbox").fadeTo(200,0.1,function(){ //start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
}else {
$("#msgbox").fadeTo(200,0.1,function(){ //start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
I got this example from this link:
http://roshanbh.com.np/2008/04/check-username-available-ajax-php-jquery.html. Do take a look at it. I hope it helps. =)
Related
I've got two buttons on my page, which each have different behaviours when clicked. Currently I've got my routes and controllers set up like this...
routes/web.php
Route::post('/users/button1clicked', 'UsersController#button1clicked');
Route::post('/users/button2clicked', 'UsersController#button2clicked');
app/http/controllers/UsersController.php
class UsersController extends Controller
{
public function button1clicked(Request $request){
//Do something
}
public function button2clicked(Request $request){
//Do something else
}
}
It works ... but I don't think I'm following the correct convention for my controller, because controllers should just have the standard actions (index, create, store, show, edit, update, destroy).
What would be a better way for me to structure this code?
What does each button do? For example, if the button submits a form to 'save' an entity (say a 'Post' in a Blog app) then the form action can direct to the PostController#store. If the button click is intended to show a html form to create an Post, then the it can lead to PostController#show. The table below from the Laravel docs will help you.
Route definitions conventions
Please also see https://laravel.com/docs/7.x/controllers#restful-naming-resource-route-parameters.
If you are using ajax or axios to make async calls then you can call a function using button events (on-click for example) and that function can make a post (or any other async call to the relevant controller method ( PostController#store). Please let me know if you'd like an example.
I am trying to learn a PHP framework. But I'm having some difficulties understanding some of the concepts of routing.
I've chosen to use Flight. Their homepage shows:
require 'flight/Flight.php';
Flight::route('/', function(){
echo 'hello world!';
});
Flight::start();
And I don't understand what they're using Flight::route... for. What am I missing? This question isn't even related to Flight. It's related to just routing in general.
Routing basically maps HTTP requests to your methods/functions.
To put it simply, say you have the route:
Flight::route('/page1', function() {
echo 'page1!';
});
This is was basically happens:
Client requests example.com/page1
Server sends query to PHP
Your PHP framework parses the request URL
Picks the correct route, in our case, page1/
And finally calls the function you passed in, so basically echo 'page1';
What seems to be happening in your file (I'm not familiar with Flight)
the require 'flight/Flight.php'; is more than likely defining a class for all the routing.
Then Flight::route(); Is simply using the route() method from the class Flight without an instance of the class.
Flight::route('/', function(){
echo 'hello world!';
});
What happens here is when a route is matched (by matched means the URI of the user matches the URI on your route, in this case www.yourdomain.com/ will match the '/' route) And then the code inside the function() callback gets executed.
If you add another route
Flight::route('/about', function(){
echo 'About Us';
});
When the user visits www.yourdomain.com/about He will get whats inside that route.
Flightphp has a rather comprehensive explanation on how to set up routes here.
You should see routes as definitions of how to handle different request patterns.
The example on Flight's home page says that if you hit your site root (i.e. /) it will simply return "hello world!" as a response.
If you read further on the Flightphp install page you will notice that all requests are handled by the index.php page. And thus depending on the routes you define it replies with the relevant response defined for that url request pattern.
Flight::route('/', function(){
echo 'hello world!';
});
This snippet is heart of your project.
This will accept two parameters.
Route
Method to call on this route call
Consider below code snippet, If you are having your project directory http://localhost/flight_project/, when anyone requests this directory, function defined as 'function_here' will be called.
Flight::route('/', 'function_here');
If you have defined route like below,
Flight::route('/user/', function(){
// do something here
});
when someone access http://localhost/flight_project/user/, the above in-line function gets called.
More info HERE
route() is a static function it seems, that means it's not specific to the object, i.e. you can't create an object such as
$flight = new Flight();
and then call
$flight->route(...)
but rather you call it via the class (not an object, which is a specific implementation of the class). You call static functions of a class by using ::, in this case
Flight::route(...)
The content of the route just says, when you encounter '/', do 'X'... and in your case 'X' is
function(){
echo 'hello world!';
}
in later stages you get to match stuff like
'/' (homepage, i.e. "mywebsite.com/")
'/about-us' (About Us page, i.e. "mywebsite.com/about-us")
'/user/{id}' (User page, i.e. you can pass a parameter such as "mywebsite.com/user/taylor" and then get the user data)
or whatever you want. And instead of just writing the function into the routing file, you can tell the router to go to a specific function (usually a Controller function) and you can do more stuff there.
I hope this helps!
Can I get the controller action from given URL?
In my project, I will have different layout used for admin and normal users. i.e.
something.com/content/list - will show layout 1.
something.com/admin/content/list - will show layout 2.
(But these need to be generated by the same controller)
I have added filter to detect the pattern 'admin/*' for this purpose. Now I need to call the action required by the rest of the URL ('content/list' or anything that will appear there). Meaning, there could be anything after admin/ it could be foo/1/edit (in which case foo controller should be called) or it could be bar/1/edit (in which case bar controller should be called). That is why the controller name should be generated dynamically from the url that the filter captures,
So, I want to get the controller action from the URL (content/list) and then call that controller action from inside the filter.
Can this be done?
Thanks to everyone who participated.
I just found the solution to my problem in another thread. HERE
This is what I did.
if(Request::is('admin/*')) {
$my_route = str_replace(URL::to('admin'),"",Request::url());
$request = Request::create($my_route);
return Route::dispatch($request)->getContent();
}
I could not find these methods in the documentation. So I hope, this will help others too.
You can use Request::segment(index) to get part/segment of the url
// http://www.somedomain.com/somecontroller/someaction/param1/param2
$controller = Request::segment(1); // somecontroller
$action = Request::segment(2); // someaction
$param1 = Request::segment(3); // param1
$param2 = Request::segment(3); // param2
Use this in your controller function -
if (Request::is('admin/*'))
{
//layout for admin (layout 2)
}else{
//normal layout (layout 1)
}
You can use RESTful Controller
Route:controller('/', 'Namespace\yourController');
But the method have to be prefixed by HTTP verb and I am not sure whether it can contain more url segment, in your case, I suggest just use:
Route::group(array('prefix' => 'admin'), function()
{
//map certain path to certain controller, and just throw 404 if no matching route
//it's good practice
Route::('content/list', 'yourController#yourMethod');
});
I'm developing a web application with Zend Framework 1.12, which is something new to me, and I'm not sure about the way to do something I want to.
EDIT: When I talk about Module, I mean Controller, sorry for that, I still mistake the terms ...
On my home page, the module Index, I made what I wanted to do with it, created several actions and all the stuff, but I'd like to add a search engine I'll make myself.
The problem is that I'd like to create the search engine as a separate module named Search, for example, but put the SearchForm in the home page. Hitting submit would send the datas from the form to the Search module.
I don't quite understand how to do that without having to go to /search to access my form and every associated actions.
Do I have to use a View Helper ?
Also, the searchForm in the front page would be some sort of QuicKSearch and accessing /search would show a more elaborated form for the research.
Can someone explain me how to access the searchForm from the Index module or redirect me to the part of the documentation talking about that ? My research are unsuccessful and Google doesn't help me either.
EDIT: When I talk about Module, I mean Controller, sorry for that, I still mistake the terms ...
First of all, build the searchform as viewHelper, then you can reuse it in several views.
The action attribute in form snippet set to searchModule/controller/action.
Additionaly make research about viewHelpers and Forms in Zend Documentation.
I actually prefer to do this as a an action helper and then just use a standard placeholder view helper to present the search form.
let me demonstrate:
the actual action helper just initiates a form and prepares it for display. I'll leave the form structure to you.
//the action helper
//Just fill in the args for the form to be displayed
class NameSpace_Controller_Action_Helper_Search extends Zend_Controller_Action_Helper_Abstract
{
public function direct($action, $label = null, $placeHolder = null)
{
$form = new Application_Form_Search();
//set the action
$form->setAction($action);
//set the submit button text
$form->search->setLabel($label);
//set the hint text displayed in the form window
$form->query->setAttribs(array('placeholder' => $placeHolder,
'size' => 27,
));
return $form;
}
}
I put the helper in the predispatch method of the controller so that each action in the controller can use the search form with having to build it in every page.
//to use the helper in your controller
class IndexController extends Zend_Controller_Action
{
public function preDispatch()
{
//setup action helper and assign it to a placeholder
$this->_helper->layout()->search = $this->_helper->search(
'/index/display', 'Search Collection!', 'Title');
}
//in your view script
<?php echo $this->layout()->search ?>
I like to put the placeholder in my master layout.phtml so that any time I populate the placeholder it will display. Now all you have to do is style it however you want.
Remember: As with any html form the action parameter is just a url so any valid url can be assigned to the form action. In this example I used the /controller/action parameters, but there are many other ways to pass a url to the form. The url helper comes to mind as good way to do it.
url($urlOptions, $name, $reset, $encode): Creates a URL string based
on a named route. $urlOptions should be an associative array of
key/value pairs used by the particular route.
Ok so Ive got this Javascript file, simply:
$(document).ready(function() {
$('.status').prepend("<div class='score_this'>(<a href='#'>score this item</a>)</div>");
$('.score_this').click(function(){
$(this).slideUp();
return false;
});
$('.score a').click(function() {
$(this).parent().parent().parent().addClass('scored');
$.get("/js/Rating.php" + $(this).attr("href") +"&update=true", {}, function(data){
$('.scored').fadeOut("normal",function() {
$(this).html(data);
$(this).fadeIn();
$(this).removeClass('scored');
});
});
return false;
});
});
Where it says /js/Rating.php, that file is in application/modules/recipes/models/Rating.php, this is because it contains some Zend logic that cant be accessed outside the application.
Through the Controller. That is the only reasonable way.
Remember JavaScript is executed on the client side, not the server. You placed your models outside the publicly accessible webroot, because your users are supposed to access your MVC app (e.g. the domain logic in the Rating model) through your app's FrontController and not on the Model directly.
In other words, since .get() issues an Ajax Request, you should direct this request to the Ratings controller in your app and make the Ratings controller call the appropriate model in your application. The model returns something to the controller and the controller then returns this result to the client.
Example:
$.get("/rating/update/someParamId/someParamValue");
This assumes you are using the default rewrite rules. In your controller you could then do $this->getRequest()->getParam('someParamId') and it would contain 'someParamValue'. The controller will return the ViewScript usually rendered by the action back to the client, so you might want to disable the layout to just return the HTML fragment.