Jquery Ajax and PHP MVC Model - php

I´m building a small application with Jquery and PHP. Jquery (index.html) adds Form Fields for the User and sends those to a PHP Script (pdo.php). The PHP Script fetches Values from the Database and does some calculations with the User given Values and the Values from the DB. The sum is returned to the Form Page.
index.html <-> pdo.php
Thus I am trying to understand the PHP MVC pattern my question is if
a.) this would make sense in this case.
b.) if so, which part would be what. index.html --> view; pdo.php --> model; controller --> ?
thanks for your help,
tony
Cut-out
jquery ... index.html
$(document).ready(function(){
$("#buttonAjax").click(function(){
var name = encodeURI($("#name").val());
$.ajax({
type: "POST",
url: "pdo.php",
data: "name="+name,
success: function(data){
var json = $.parseJSON(data);
$("#output").html(json.summe);
talk(json.say);
}
});
});
function talk (say){
jQuery.noticeAdd({text: say,stay: false});
}
});
pdo.php
/* DB Connection */
$strDbLocation = 'mysql:dbname=test;host=localhost';
$strDbUser = 'root';
$strDbPassword = 'root';
try{
$objDb = new PDO($strDbLocation, $strDbUser, $strDbPassword);
}
catch (PDOException $e){
echo 'Failure: ' . $e->getMessage();
}
/* Fetch POST Data */
$id = $_POST['name'];
/* Build query */
$dbSelect = $objDb->prepare("SELECT Age,Name FROM Benutzer WHERE id = :id");
$dbSelect -> setFetchMode(PDO::FETCH_ASSOC);
$dbSelect -> bindParam('id', $id);
$dbSelect -> execute();
/* Output + Calculate */
while($row = $dbSelect->fetch()) {
$total = $row['Age'] / 100 . "<br />";
}
/* Return to User */
if(!empty($total)){
$ret = Array("summe" => "Summe: " . $total, "say" => "all right");
echo json_encode($ret); }
else{
$ret = Array("summe" => "Nothing for you", "say" => "nothing for you");
echo json_encode($ret);
}

In a standard MVC webapp, routes are matched to controller actions. These controller actions may interface with the Model [which in turn interfaced with the database] or performs some other Model-agnostic calculations, and renders a view. It is obvious that the index.html is the view. And I think you have the controller and the model bundled up in pdo.php.
I really recommend PeeHaa's link in the comments. That answer is well written.
That been said, there are many architectural patterns to making a webapp. Yours may not be MVC. Some prominent frameworks that aren't MVC are SproutCore (View-based controllers) and JSP pages (single controller).

Use of controller is to controll the form elements in html using php . For eg:
/ * Fetch POST Data */
$id = $_POST['name'];
the use of model is only for db use (insert,select,..)

Related

Accessing already set property from the same class returns null

I am trying to display records from query in a table and on button clicked to make an ajax call to download the information in an xml format. The query is executed from method inside a class and the ajax request makes call to a different method inside the same class. The first method fills two private properties inside the class and the second property(the one called through the ajax request) must read the properties and fill the data inside table and make the file downloadable. When I try to read the properties from the same class though I get nulls and the foreach returns an error.
This is my ajax request(downloaderScript.js):
;
$("#downloadBtn").click(function (event) {
event.preventDefault();
event.stopPropagation();
$.ajax({
url: 'allClients.php',
type: 'post',
data: {action: 'downloader'},
complete: function (result) {
console.log(result);
},
error: function () {
console.log('Error');
}
});
});
This is the class from which I call the first and the second methods:
class HttpHandlerClient extends HttpHandlerAbstract
{
private $clientsService;
public $storedClientsHeadings;
public $storedClientsData;
public function viewAllClients()
{
$data = $this->clientsService->getAllClients(clientEntity::class);
if(isset($data)) {
$this->storedClientsHeadings = ["Client Names:", "Delivery Address:", "Phone number:"];
$this->storedClientsData = $data;
$this->render('allClientsView', $data);
}
else
{
$this->redirect('clientAdd');
}
}
public function downloader()
{
header("Content-Type: text/plain");
var_dump($this->storedClientsHeadings);
foreach ($this->storedClientsHeadings as $arrayName)
{
echo implode("\t", $arrayName)."\r\n";
}
/**
* #var clientEntity $clientData
*/
foreach ($this->storedClientsData as $clientData)
{
echo implode("\t", $clientData->getClientName())."\r\n";
echo implode("\t", $clientData->getAddressForDelivery())."\r\n";
echo implode("\t", $clientData->getPhone())."\r\n";
}
$filename = "clients_".date("Y-m-d").".xls";
header("Content-Disposition:attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
}
And this is the php file that i use between my ajax request and the php class(The file name is: allClients.php, in common.php I make an instance of the class HttpHandlerClient):
require_once 'common.php';
if(isset($_POST['action'])){
$myHttpHandlerClient->downloader();
} elseif (isset($_GET['typer'])) {
$myHttpHandlerClient->viewClientByNumber($_GET['typer']);
} else {
$myHttpHandlerClient->viewAllClients();
}
Sorry if my question is trivial, I even started doubting that after require_once I re-run the code in common.php, making a new instance of HttpHandlerClient and because of this I get nulls in the properties. But when I was reading the documentation in php's site I did not read such a thing. Any help will be appreciated, thanks.
It sounds like what may be happening is that there is a disconnect between the javascript initially loading and then more markup being added to the DOM.
The page loads up which runs your javascript. At this point the JS only knows what is currently on the page.
Your make the first call which changes the DOM. Your javascript does not know about these changes.
You try to reference something that has not been recognized by your initial load of the Javascript.
After you make the call that changes the DOM, you may have to reinitialize your JS to recognize the changes.
Good luck

PHP PDO Query - Exception performing SQLSTATE[IMSSP] This function is not implemented by this driver

Hoping someone can provide some insight to this - wasn't able to find much on Google referencing the error I'm getting.
I have a simple PHP page that has some links on it that should open up Skype For Business chat windows with members that are in the group of the link that is clicked. (IE: a link is clicked for a specific team and a database query finds the users and launches Skype window like
<a href=”sip:person#website.com″></a>
Application flow is as follows :
index.php -- navbar link
<li><a href="#" id="Team1" onclick="return
loadChatGroup(this.id)">Team1</a></li>
calls this
function loadChatGroup(t) {
console.log(t);
$.ajax({
url: 'components/chat/chatLoader.php',
type: 'post',
dataType: "text",
data: 'team=' + t
});
return false;
}
chatLoader.php
//Load all our project classes here
<?php include_once $_SERVER['DOCUMENT_ROOT']."/myApp/includes/app.php";
if (isset($_POST['team'])){
$conn = new Connection();
$pdo = $conn->DBH;
$chats = new Chat($pdo);
$team = $_POST['team'];
$getMembers = $chats->getChatMembers($team);
foreach ($getMembers as $member){
echo "<a href='$member'></a>";
}
}
?>
chat.php
<?php
class Chat
{
private $conn;
public function __construct($pdo)
{
$this->conn = $pdo;
}
public function getChatMembers($data)
{
$stmt = $this->conn->prepare("SELECT SIP FROM test.chats WHERE
Group_Name = ?");
$stmt->bind_param(1, $data);
$stmt->execute();
$members = $stmt->fetchAll();
return $members;
}
}
I am able to verify the connection is established by and class instantiated fine by print_r on my $pdo and $chat variables.
When the query is called it returns " Exception performing SQLSTATE[IMSSP] This function is not implemented by this driver "
I have other classes and queries that run fine and this error seems to come up regardless of the sql statement I try to run from my chat class.
Not sure where to go from here...

Not able to call a method of PHP using $http.get in Angular JS

I'm new to Angular JS. I'm able to call a php file and get the data. But, now the scenario is that I need to call a particular method from a php and get the data using "$http.get". Take a look at my code, whether I'm calling the method in the correct way or not?
Angular Code
// Ajax call for listing countries.
var countryPromise = $http.get("ListData.php/getCountries()");
// Create global users array.
$scope.countriesArray = [];
countryPromise.success(function(data, status, headers, config) {
for(index in data) {
alert(data[index].name);
$scope.countriesArray.push({
id:data[index].id,
name:data[index].name
});
}
});
countryPromise.error(function(data, status, headers, config) {
alert("Loading countries failed!");
});
PHP
<?php
class ListData
{
function __construct() {
// credentials of MySql database.
$username = "root";
$password = "admin";
$hostname = "localhost";
$countryData = array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("Angular",$dbhandle)
or die("Could not select Angular");
}
public function getCountries() {
//execute the SQL query and return records
$result = mysql_query("SELECT id,name FROM Country");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
$id = $row{'id'};
$name = $row{'name'};
$countryData[] = array('id' => $id, 'name' => $name);
}
echo json_encode($countryData);
}
}
?>
You need to know what is the route of the php function getContries and then call this route from the $http.get function.
Do you hard coded your php server or are you using a framework ?
I think that you are misunderstanding the way that PHP works. Actually you are trying to call a method from a class with an HTTP Request. Thats is not possible atleast not without a routing class.
The routing class its just a class that intercepts all the HTTP Request to analyze the URI, and based on a pattern, it match to a preexisting class, instantiate (create) it and call the wanted method from that class.
For example, our routing class have a pattern like this:
Class/Method
an intercept a Http Request like this:
www.oursite.com/ListData/getCountries
Where ListData is our class, and getCountries is our method or action.
So, the routing class just do this:
$Class->Method();
Of course we can achieve to pass parameters, and intercept and routing specific http request type's like: post, get, update, delete, etc.
There's a lot of frameworks who make that for you, but if you only want to use the Routing, here's a couple
https://github.com/dannyvankooten/PHP-Router
http://www.php.net/manual/en/class.yaf-router.php
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
PHP Frameworks that I recommend (because I worked with them):
http://laravel.com/
http://ellislab.com/codeigniter
In anycase, if you don't want nothing of that, you could just create a folder called ListData and inside it create a file called getCountries.php. On that file just put the code to instantiate your class and call your method.
<?php
include('../ListData.php');
$cIns = new ListData();
$cIns->getCountries();
?>
In that way, it gonna work in the way you are calling the url (don't forget to add the .php extension at the end (: )

Creating a PHP registration class + templating system?

As of right now I've created a template class, and I've created a registration class. But I'm having trouble getting the two to work properly together so that I can display my variables in my template files.
Here are the basics of my template class:
class siteTemplate {
function getTemplate($file, $varesc=false) {
if (file_exists("templates/" . $file)) {
$data = file_get_contents("templates/" . $file);
$data = str_replace("\"","\\\"", $data);
$data = str_replace("\'","\\\'", $data);
$data = str_replace("\\n","\\\n", $data);
if($varesc)
$data = str_replace("\$","$", $data);
return $data;
} else {
die("Error.<br />Could not find <strong>" . $file . "</strong>.");
}
}
function createGlobal() {
global $siteName, $siteUrl;
global $content;
eval("\$main = \"".$this->getTemplate("main.html")."\";");
echo $main;
}
}
$tp = new siteTemplate();
A function from my registration class:
public function get_username($uid) {
$result = mysql_query("SELECT username FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['username'];
}
I can echo out data from my registration class in index.php
echo $user->get_username($uid);
BUT I can't do the same thing within my template files. What adjustments do I need to make to make this work together. Live example: http://www.aarongoff.com/i
Username: test
Password: test
If you look I'm echoing out "Logged in as: test"
But when I try to call for that variable within my template file it just displays "Logged in as:"
(I know there are SQL vulnerabilities, I'm just testing to get my classes to work)
The true answer to this is that PHP IS a template! Use pure PHP code as your templates. Then you don't have to keep reimplementing every one of PHP's features in your ad hock template class.
This is called the http://en.wikipedia.org/wiki/Inner-platform_effect and you should avoid it. Just use PHP directly, it's what it was made for.
What you should do is be disciplined about naming the PHP files, and separating concepts logically. But don't try to reimplement PHP in PHP.

Is there a php framework that makes working with jquery & ajax easier?

I've been using Codeigniter for the past two years and really have become a big fan, but over the past year I've found myself writing more and more javascript than PHP.
In the begining, I would write everything with PHP, but now I find myself using $.ajax all the time. And I sort of feel like Im repeating myself between javascript and php.
I know that CI does give you some good control over ajax, but Im still having two write a ton of javascript and I'd like to consolidate if at all possible.
I guess what I am looking for is a php framework that integrates tightly with jQuery's $.ajax.
I use this piece of code in Javascript. Backend wise things are organized in a MVC type of organisation, so things affecting one module are usually grouped together. In general I also create a sperate module for a seperate model, but in some cases you may deviate from this principle.
My setup is with symfony at the back and plain jquery at the front. There are some approaches that automatize this part, like http://javascriptmvc.com/, I find it too restricting in many parts. Here is my workflow for integrating php and jquery.
PHP
Execute a piece of code and wrap it inside a try/catch block. This way error messages may be propagated to the frontend. This method helps in that regard to convert exceptions to a readable error. (to debug from json).
try {
//... execute code .. go about your buisness..
$this->result = "Moved " . count($files) . " files ";
// result can be anything that can be serialized by json_encode()
} catch (Exception $e) {
$this->error = $e->getMessage() . ' l: ' . $e->getLine() . ' f:' . $e->getFile();
// return an error message if there is an exception. Also throw exceptions yourself to make your life easier.
}
// json response basically does something like echo json_encode(array("error" => $this->error, "result" => $this->result))
return $this->jsonResponse();
For error handling I often use this to parse errors.
public function parseException($e) {
$result = 'Exception: "';
$result .= $e->getMessage();
$trace = $e->getTrace();
foreach (range(0, 10) as $i) {
$result .= '" # ';
if (!isset($trace[$i])) {
break;
}
if (isset($trace[$i]['class'])) {
$result .= $trace[$i]['class'];
$result .= '->';
}
$result .= $trace[$i]['function'];
$result .= '(); ';
$result .= $e->getFile() . ':' . $e->getLine() . "\n\n";
}
return $result;
}
Javascript side
/**
* doRequest in an ajax development tool to quickly execute data posts.
* #requires jQuery.log
* #param action (string): url for the action to be called. in config.action the prefix for the url can be set
* #param data (object): data to be send. eg. {'id':5, 'attr':'value'}
* #param successCallback (function): callback function to be executed when response is success
* #param errorCallback (function): callback function to be executed when response is success
*/
jQuery.doRequest = function (action, data, successCallback, errorCallback) {
if (typeof(successCallback) == "undefined") {
successCallback = function(){};
}
if (typeof(errorCallback) == "undefined") {
errorCallback = function(data ){
alert(data.error);
};
}
jQuery.log(action);
jQuery.post(action, data, function (data, status)
{
jQuery.log(data);
jQuery.log(status);
if (data.error !== null || status != 'success') {
// error handler
errorCallback(data);
} else {
successCallback(data);
}
},'json');
};
Note: the error callbacks are very nice if you combine them with something like pNotify
Look into Agile Toolkit, which is a PHP UI Framework. UI means it takes care of HTML, JavaScript, CSS and AJAX while allowing you to develop in plain, object-oriented PHP language.
http://agiletoolkit.org/intro/javascript
There is also a blog post comparing it with CodeIgniter: http://agiletoolkit.org/blog/agile-toolkit-for-codeigniter-developer/
p.s. I'm co-author for Agile Toolkit.

Categories