I'm creating site using MVC architecture and get stunned when I came to AJAX. I create simple feedback form with AJAX. When user submit it there is called PHP file that inserts given values into the database using 'database' class.
Where to put that PHP file (so it would be somehow hierarchic)?
I tried to put it in /models/ajax/file.php, but it seems to me stupid and, of course, 'database' class wasn't found.
It's no different than how you do any other page of your site. That this page's output goes to an AJAX request instead of directly to a web browser is irrelevant. Its logic goes in the controller, the database code goes in the model layer, its response goes in a view.
You should call controller from AJAX request. And response will probably use different (for example JSON) view
Related
Okay, I'm learning all about MVC, Bootstrap, Ajax and Smarty and I understand the basic principles of MVC. I am having one major issue however and I just cannot wrap my head around it, no matter how much I try and no matter how much reading I do.
At it's very core the thing I cannot seem to get my head around is how to pass variables from view to controller from controller to view.
If I want to assign a variable, I can simply $view->assign('variableName', 'variableValue') No issues there, then in the view if I want to call it, it's as simple as $variableName and it's in the view.
My issue is, I want to be able to minipulate data, for example let's say I want to have a list of items, numbers for the example, a list of 1-10, the user chooses 6, I want a way to be able to "POST" that back to the controller without actually having use POST/GET, I want to be able to essentially let it call an Ajax to send the users selection but I do not know the best way to do so.
If I was doing this without MVC, or Smarty it would be as simple as form, action post, I know that but unfortunately that isnt something I can use in this instance.
Any help you can offer would be appreciated.
I will begin with the normal workflow, e.g. without the MVC approach.
Let's say, in a certain moment you are seeing a web page in the browser and let's call it MAIN PAGE.
When you are submitting a form from main page without using ajax,
the whole page refreshes, no matter if the form action points to the
main page or to another one.
When you are submitting values using an ajax call (as part of the
main page code), then the main page will not be reloaded. E.g. an
ajax call targets ANOTHER PAGE to fetch some data in some format
(html, json, etc) and prints the data on screen, in a specified
container inside the main page.
Now, let's see what happens in a web MVC architecture.
You must understand, that an MVC application consists of only one page: index.php. This page serves as the MAIN PAGE, but ALSO as the ANOTHER PAGE, targeted when using ajax calls. The index.php page is therefore processed each time when you are sending a request to the web server - be it through manually changing the url in the address bar of the browser, through posting a html form, or through starting an ajax script.
All other components of the MVC structure (classes, template files, etc) are serving only one purpose: to build the structure of the index.php page - as main page or as ajax response page.
So, in principle, in the index.php page you'll have something like this:
Read the URL, e.g the url components: controller name, action name, action parameters (HTTP GET query string). For this you can use an instance of a Router class.
Create an object of type Request, passing and saving the url components into it. Here are read and saved the other server request variables too, e.g. HTTP POST, HTTP cookies, etc.
Create an instance of the View class.
Based on the url's controller name instantiate the corresponding Controller class, passing the Request object and the View instance to it. Here you'd give the model layer constructs (like a model factory object) as constructor parameter(s) too.
Based on the url's action name call the corresponding controller method, e.g. the controller "action". Exactly here, inside the controller action, are taking place the processing of the server request variables (saved in the Request object), the loading of the template files and their rendering, including transferring the processed server request variables into them.
In the last step, the rendered template files will be directly printed or further passed to an object of type Response, which in turn prints them.
In the end, you'll have a fully "constructed" index.php page, which will be either printed on screen by the browser (if index.php has the role of a main page) or processed by the browser as the result of an ajax request.
Note that I used the description of the steps found in the classical MVC approach. There are also other... types of this concept, best presented in Architecture more suitable for web apps than MVC?
Other very good resources:
MVC for advanced PHP developers (contains a list of great resources)
How should a model be structured in MVC?
Understanding MVC Views in PHP
Understanding MVC
MVC (Model-View-Controller) in PHP tutorial (Part I...IV)
Model-View-Confusion (Part I+II)
James Mallison - Dependency Injection and Dependency Inversion in PHP
Good luck.
I have a question related to form submission done in PHP application that's built in MVC architecture (self-written framework).
All examples that I've seen so far (including existing back-end frameworks) work this way that once form for adding record to database is submitted then certain method of controller is executed [say i.e. addRecord()], which triggers method of appropriate model. If everything goes OK then record is added and controller's method [addRecord() in this example] renders view of "index" page that displays table with records from database.
What I would like to achieve is to render view with form used to add records (the same that I used to add first record) instead of "index". Obviously I can do it easily by just rendering appropriate view from addRecord() (view with the form).
But the tricky point is when you check url you'll see the following:
The first time you enter it will be i.e.
http://project_name/my_controller/create
Once first form was submietted and you return to the view from addRecord() method then url will be:
http://project_name/my_controller/addRecord
What I would like to see is return to the original url, that is http://project_name/my_controller/create
Not sure if this is clear?
PS. Of course I could use AJAX call for form submission (that way I will stay at the same page) but perhaps it's possible to achieve the same without AJAX.
Thanks in advance,
On the controller you will want to submit to the addRecord route and do the processing. Have a check to make sure it was successful and on successful submission you can redirect back to the create route.
It is hard to give an example since you are using a custom made framework. I use slim which has a redirect method for a route. If what you have made does not have something like that then using should do the trick.
header('Location: '.$createUrl);
die(); //or exit
I currently have a site I built using jquery/php/PDO/mysql.
I use classes for most functions, including database, logins, content, etc...
I am wanting to change my forms over to jquery's ajax calls. But there's where my problems start. With the ajax call, I can't call a php function in the ajax post url. Heres the heirarchy Im using;
->content.php (form resides in a function named content.)
->process.php (post checks and then a call to add content from class)
->class.content.php (insert vars into db)
Once form is submitted, it goes to process.php which contains checks and then a class call to add content.
While this hierarchy seems to be the most used for ajax, it causes path issues. It breaks my db connection, my config connection, etc...
All I really want is to add ajax forms. But I don't want to rewrite my whole site. Any suggestions?
It sounds like process.php was previously included in content.php but now you're trying to submit to it directly. However, process.php was dependant upon the configuration variables, database connection etc. which was included in content.php and accessible by being included within that page.
I think you need to make a new page which includes the same other files and has the same initialisation code as content.php, except it doesn't output the form and instead just includes process.php, then submit to the new page.
Hard to say for sure without code though.
Well, I've read this tutorial if I could say: http://www.symfony-project.org/book/1_1/02-Exploring-Symfony-s-Code
And, actually, I write my code very similiary. But my question, where should I insert my jQuery code? I am sure it should be in the part of the View, but are there any good examples on how should I combine it to make "live" websites?
Edit: By saying live, I mean, for example, send POST request through Ajax and get information and similar. So, no refreshes for people.
Thank you.
jQuery as a part of javascript resources should be included in html.head or in-place, depending on what should jquery do and if the code is reusable for more views.
So it has to be part of View and you're choice is to set it up in layout or action view itself
If you need the javascript on every page then add it to your master view if not then just include it to the particular view files.
In context to codeigniter:
I extend the controller with MY_Controller and initialize a property as array which would hold the scripts that are added dynamically to the view.
eg.
var $templateData['scripts'] = array();
The controllers then pass $this->templateData to the views
And the views load the extra scripts( available as $scripts) as directed by the controllers in the head tag
This way you can even avoid loading the main jquery file when not needed.
Loading jquery.js only for the controller that need it.
im designing a way the form posts its data.
e.g if we have a login.php, if the user submit we normally post it back to login.php and process it. which means if we have other pages like register.php, editprofile.php, we have to redo the process again. so normally we would do something like this in each page:
if($_POST["btnsubmit"]) {
//do smth
}
Im thinking of doing a common postForm.php which accepts all post requests, pass the data to the respective library and process it.
is this a good idea??
It is definitely a good idea! What you're describing is called a controller, from the Model View Controller pattern. I recommend checking out Symfony, which is a great MVC web framework for PHP.
A single Symfony controller (with a name like actions.class.php) can handle all of the posts and gets, plus the routing to get you there. By Symfony convention, a call to http://mywebsite.mydomain.com/home will run the executeHome function in the main controller. A form on that page could, for instance, post to /attemptLogin, and (again, by convention) Symfony would run the executeAttemptLogin function in this same controller file.