How to communicate with the controller using AJAX in Laravel? - php

I'm using CodeIgniter for over a year now (and got pretty used to it) then found out that it is getting outdated and support has been taken off by ellislab. I want to try using Laravel as an alternative though CodeIgniter still works just fine but for Future purposes, I don't want to get left behind. Now, with Laravel's MVC framework it was easy for me to migrate some of my projects from CI. I'm having a problem with Laravel's routing though as I'm not able to communicate with my controller. Here's a bit of my code:
controller.php:
public function connect() {
$this->load->model('home_model');
if ($DBconnect=$this->home_model->checkConnection()) {
echo json_encode(array(
"success" => true,
"db_connect" => $DBconnect
));
} else {
echo json_encode(array(
"success" => false,
"db_connect" => $DBconnect
));
}
}
view.js:
$("#connection").click(function(e) {
e.preventDefault();
show_loading();
$.get('./home/connect', function(data) {
hide_loading();
Materialize.toast(data.db_connect, 4000, 'rounded green');
}, "json");
});
PS: Am I doing the Laravel way or I'm still very CI minded?

This is my way to connect with the controller
First set up the routes.php :
Route::controller('/','MyController');
On the controller app/controller/MyController.php (You need to create one) :
<?php
class MyController extends BaseController {
public function getJustASampleText(){
echo "Hello World";
}
public function getJustASampleSmile(){
echo ":D";
}
public function getConnect(){
$var_value = "Hello world";
return Response::json(array('var_name' => $var_value));
}
}
Then you can call that function like this
domain.com/just-a-sample-text or
domain.com/just-a-sample-smileor in you case
$.get(`http://127.0.0.1/laravel/public/connect`,function(data){
alert(data.var_name);
})
That how we use Route::controller approach.

Related

How to convert to laravel from express js?

I have a few lines of code which is written in express js, I want to convert into the laravel code,
app.get('/*', function(req, res) {
var jsonResponse = [];
jsonResponse.push({ "text": "Hi. 3 is a lucky number..." });
res.send(jsonResponse);
});
Is there anyway? Please guide me.
Here is my tried , don't know correct or not.
public function json_test(){
$message =["text" => "Hi. is a lucky number..."];
return $message;
}
Long story short
I think everything is correct. You just have to change your return value to be a json response.
A bit more detailed
You must first define a route in api.php:
Route::get('/some/url', 'ExampleController#jsonTest');
Next you must define a controller and inside the controller the functions that you need:
<?php
namespace App\Http\Controllers;
class ExampleController extends Controller
{
public function jsonTest(){
$message =["text" => "Hi. is a lucky number..."];
return response()->json($message);
}
}
In case you don't need an entire controller for this you can simply place the functionality in the api.php file like so:
Route::get('/some/url', function () {
$message =["text" => "Hi. is a lucky number..."];
return response()->json($message);
});
Hope this helps.

I can't create a view in Laravel

I'm new in Laravel and I'm trying to create a View in Acelle (app based on Laravel). I read a lot of tutorials, but I've not been luck with this problem.
I created the view "lol.blade.php" on /resources/views folder with this code:
HELLO (just hello)
The Route:
Route::get('lol', function()
{
if (view()->exists('lol')) {
//return 'helloooo'; <--- it works
return view('lol');
} else {
return 'not exists';
}
});
The code knows the view exists, but the url (localhost/acelle/public/lol) prints this message:
"Whoops, looks like something went wrong."
I can't solve the problem with tutorials. I followed all the steps about creating views in Laravel, but I don't know why the view prints that message.
Please help!
PS: Laravel version: 5.2.45
EDIT:
In console [network] shows Error 500. and laravel.log prints 59 lines. but the first line show:
[2017-07-14 14:08:20] production.ERROR: ErrorException: Undefined index:controller in /home/acelle/public_html/acelle/app/Providers/AppServiceProv‌​ider.php:20
You posted this in the comments:
app('view')->composer('*', function ($view) {
$action = app('request')->route()->getAction();
$controller = class_basename($action['controller']);
list($controller, $action) = explode('#', $controller);
$view->with(compact('controller', 'action'));
});
Your issue is that this route uses a closure, and has no controller:
Route::get('lol', function() {});
Therefore, $action['controller'] doesn't exist and throws a warning as a result. You'll want to check isset($action['controller']) before doing the rest of your code that uses the controller variable.
Already solved!!
SOLUTION:
creating a controller : MiwebController.php
<?
namespace Acelle\Http\Controllers;
class MiwebController extends Controller
{
public function __construct()
{
parent::__construct();
$this->middleware('auth');
}
public function index()
{
return view('lol');
}
}
?>
routes.php:
Route::get('lol', 'MiwebController#index');
It works fine. Thank you!

Unable to access function in codeigniter library

New to PHP, oop & codeigniter.
My CI version is 3.1.2.
I am trying to load a library that I built, trying to understand Object oriented principles. Probably I'm missing something.
Below is my library.
<?php
class DPS {
private $mode;
public function __construct($params){
//print_r($params);
$this->mode = $params['mode'];
}
public function get_url(){
if($this->$mode == "TEST"){
return "https://uat.paymentexpress.com/pxaccess/pxpay.aspx";
} elseif($this->$mode == "LIVE"){
return "https://sec.paymentexpress.com/pxaccess/pxpay.aspx";
}
}
}
?>
I'm trying to access the get_url method in the controller below.
$params = [ 'mode' => 'TEST'];
$dps = $this->load->library('DPS',$params);
echo $dps->get_url();
Codeigniter is throwing the below error message.
Fatal error: Call to undefined method CI_Loader::get_url()
Being a newbie I'm probably missing some sort of OO fancy thingi. I just can't figure it out. Any help is greatly appreciated.
Thank you in advance
Try this,
$this->load->library('dps',$params);
echo $this->dps->get_url();
Always load libraries in Codeigniter like this
$this->load->library('library_name');
And call to method of library using
$this->library_name->method_name();
SO try like this...
Save your library in application/libraries as Dps.php.Then
$params = [ 'mode' => 'TEST'];
$dps = $this->load->library('dps',$params);
echo $this->dps->get_url();
And In your DPS library. Correct it
public function get_url(){
if($this->mode == "TEST"){
return "https://uat.paymentexpress.com/pxaccess/pxpay.aspx";
} elseif($this->mode == "LIVE"){
return "https://sec.paymentexpress.com/pxaccess/pxpay.aspx";
}
}

MVC pattern with AJAX calls

This is a weird question about a php mvc pattern with ajax calls. The purpose is make a better and dynamically web apps. Let me explain you:
When I learn php, I used this pattern specifically :
model.php
<?php
class myClass {
private $attrOne;
private $attrTwo;
public function getAttrOne() {
return $this->attrOne;
}
public function setAttrOne($attrOne) {
$this->attrOne = $attrOne;
}
public function getAttrTwo() {
return $this->attrTwo;
}
public function setAttrTwo($attrTwo) {
$this->attrTwo = $attrTwo;
}
// ----------------------------------------------------
public function doSelect() {
//some code
}
public function doInsert() {
//some code
}
public function doUpdate() {
//some code
}
public function doDelete() {
//some code
}
}
controller.php
<?php
require "../models/model.php";
if(isset($_POST['action'])) {
$action = $_POST['action'];
if(is_callable($action)) {
$action();
}
}
function registerSomething(){
$model = new myClass();
$model->setAttrOne($_POST['attrOne']);
$model->setAttrTwo($_POST['attrTwo']);
$return = $model->doInsert();
echo $return;
}
function registerSomething2(){
// more app logic code and other stuff
}
view.php -> this is most a pure html file with php extension
<div id="result"></div>
<form id="register" role="form" >
<input type="text" id="attrOne" name="attrOne"/>
<input type="text" id="attrTwo" name="attrTwo"/>
</form>
<script src="script.js" type="text/javascript"></script>
And the script.JS
$('#register').submit(function() {
var action = 'registerSomething';
$.ajax({
data: $(this).serialize() + '&action='+action,
url: '../controlllers/controller.php',
type: 'POST',
success: function(response) {
$('#result').html(response);
}
})
return false;
})
So, what do you think about this pattern? is this pattern efficient?
What is the best way to do ajax calls with a proper mvc pattern in php?
Is this a best practice?
If your goal was to specifically implement something MVC-like, then you have utterly failed. This setup has absolutely nothing to do with MVC. To be honest, it seems that you are way too inexperienced for tackling something like that.
If instead this is your first attempt in applying Separation of Concerns on your code, then it's appropriate. Though, I still wouldn't put that type of code in the production.
My recommendation for you would be: stop trying to "do MVC" for now, and focus instead on improving your general understanding of web development.
You should google the following topics for PHP:
url routing
autoloading and PSR4
difference between active record and data mapper pattern
request abstraction

Yii, Is it good MVC practice to echo in the controller?

It seems like i am not following the MVC design structure.
I'm making an ajax call from my view to a Controller function
Controller
public function actionGetClient()
{
$user = Client::model()->findByAttributes(array('email'=>$_POST['email'], 'password'=>$_POST['pass']));
echo $user->fullname;
}
View (the calling ajax)
CHtml::ajaxLink(
$text = 'get user',
$url = Yii::app()->createUrl('[my controller]/getClient'),
$ajax=array (
'type'=>'POST',
'data' => array('email'=>email, 'pass'=>pass),
'beforeSend' => "function( request )
{
$(\".result\").html(\"fetching...\")
}",
'success'=>"function(data){
$(\".result\").html(\"user is :\"+data)
}
"
));
Is it good to "echo" the $user->fullname inside the controller for the ajax success function to display it? My boss doesn't like it when i print stuff in my controller, how can i approach this
because when i use return instead, the ajax success gets a null value
return $user->fullname;
No,
It's not a good practice.
You need to create a view to use echo.
You can use return $this->renderPartial('VIEW_NAME'); to render a view without Layout.
You should write 'return' instead of 'echo'. 'echo' is not a good practice for ajax response. You don't need to make a new view for just return a name in your case.
public function actionGetClient()
{
$user = Client::model()->findByAttributes(array('email'=>$_POST['email'],'password'=>$_POST['pass']));
return $user->fullname;
}
No. A controller’s supposed to pass its results to a view for rendering.
I would avoid echoing in the controller what we usually do is have a ajax view folder and a json view and render with that so:
public function actionGetClient()
{
$user = Client::model()->findByAttributes(array(
'email'=>$_POST['email'],
'password'=>$_POST['pass']
));
$this->render("json",array("outputData"=>$user));
}
then add this to the controller as well:
public function getViewPath(){
if(Yii::app()->request->isAjaxRequest){
if(($module=$this->getModule())===null)
$module=Yii::app();
return $module->getViewPath().DIRECTORY_SEPARATOR."ajax";
}
return parent::getViewPath();
}
and in the ajax views folder add a json.php file like so
header('Content-Type: application/json');
// output data
echo json_encode($outputData);
please degug the code as I wrote it free hand. You can also set a marker in the controller like $viewPath and set it before the rendering

Categories