I have a problem with AJAX request in PHP MVC framework: I don't know how to call JSON formatted data from controller to the view using, for example, jQuery.
I wasted many hours searching for any useful tip on the internet and trying to resolve this problem by myself but with no success.
I think the problem is where I need to write the URL; I can't write it correctly.
This is the code for the controller:
public function indexAction()
{
$dbh = new PDO('mysql:dbname=myframework;host=localhost', 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare('SELECT variety ,fruit_id FROM fruit limit 10');
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll();
echo json_encode($data);
}
And this is the view code:
<!DOCTYPE html>
<html><head><meta charset="utf-8" /> </head>
<h1>grid ajax</h1> <body> <table id='grid'></table>
<script type="text/javascript" src="<?php echo PROJECT_URL ?>/views/search/jquery.js"></script>
<script type="text/javascript">
$(function(){
$.getJSON( myURL - HERE IS PROBLEM ! , function(json){
for (var i=0;i<json.length;i++) {
$('#grid').append("<tr><td>" + json[i].fruit_id + "</td><td>" + json[i].variety + "</td></tr>")
}
});
});
</script>
</body>
</html>
Here is routing:
getUrlFor($controller = 'index', $action = 'index') { $route = array('controller' => $controller, 'action' => $action); $routes = $this->getRoutes(); $url = array_search($route, $routes); if ($url === false) { $url = $controller . '/' . $action; } $url = PROJECT_URL . '/' . $url; return $url; } }
and public function urlFor():
public function urlFor($controller = 'index', $action = 'index')
{
return Router::getInstance()->getUrlFor($controller, $action);
}
This function works in this framework everywere;
URL form example: http://localhost/myframework/ajax/index,
(var $myURL = "<?php echo $this->urlFor('ajax', 'index'); ?>"; - in jQuery I use it in this form), only not in $.getJSON. I tried to write this URL in many forms, none of them worked. It is simple custom framework.