1

I want to pass a value from my controller to a .php file which is inside public folder. This is my controller part

<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller {

public function barChart(){

    $barChart= DB::table('clients')
        ->select('clients.ClientName','clients.Price')
        ->get();
    //want to pass this $barChart variable
}

Location of .php file is

/dist/chart/clients.php

I want to have this $barChart variable in clients.php file and perform further operation.

update 1: this is the view part

    <div class="panel-body" id="barChart">

    </div>



    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
        $.ajax({
        //url: "{{URL::asset('/dist/chart/clients.txt')}}", //this works, I saved the json_encode($bar) at client.txt file
        data: [{{$bar}}], //this does not work
        dataType:"JSON",
        success: function(result){
            google.charts.load('current',{
            'packages':['corechart']
            });
            google.charts.setOnLoadCallback(function(){
            drawChart(result);
            });
        }
        });

        function drawChart(result) {server.
            var data = new google.visualization.DataTable();
            data.addColumn('string' , 'ClientName');
            data.addColumn('number', 'Price');
            var dataArray=[];
            $.each(result, function(i, obj){
            dataArray.push([obj.ClientName, parseInt(obj.Price)]);
        });
        data.addRows(dataArray);

            var barChart_options = {
            title: 'hoise??',
            is3D: 'true',
            width: 400,
            height: 300
        };
        var barChart = new google.visualization.BarChart(document.getElementById('barChart'));
                    barChart.draw(data, barChart_options);
        }
});


</script>

update 2

controller update

<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller {


public function index()
{

    try{
        $val=DB::connection()->getDatabaseName();
        if(DB::connection()->getDatabaseName()) {

            $barChart= DB::table('clients')
                ->select('clients.ClientName','clients.Price')
                ->get();
            $bar = json_encode($barChart);

            return view('home')
                ->with('bar', $bar);

        }else{
            $er="/connection status: database error";
            return view('errors/503')->with('error',$er);
        }
    }catch (\Exception $e){
        $er="/connection status: database error";
        return view('errors/503')->with('error',$er);
    }

}

public function barChart(){

    $barChart= DB::table('clients')
        ->select('clients.ClientName','clients.Price')
        ->get();
    echo json_encode($barChart);
}
public function create()
{
    //
}
public function store()
{
    //
}
public function show($id)
{
    //
}
public function edit($id)
{
    //
}
public function update($id)
{
    //
}
public function destroy($id)
{
    //
}
}
7
  • 1
    why are you not sending it to a view? Commented May 5, 2016 at 4:45
  • Instead create a blade file and simply access the values over there. Commented May 5, 2016 at 4:46
  • inside my view I want to use that $barChart variable json_encoded. $.ajax({ url: "{{URL::asset('/dist/chart/clients.php')}}", dataType:"JSON", success: function(result){ google.charts.load('current',{ 'packages':['corechart'] }); Commented May 5, 2016 at 4:48
  • plz post your controller update too. Commented May 5, 2016 at 6:12
  • @MubasharAbbas please check the update Commented May 5, 2016 at 6:20

3 Answers 3

1

Add your clients.php to resources/views directory and name it clients.blade.php, it will work the same but give you a nice templating engine.

In your controller/barChart method do this.

$barChart= DB::table('clients')
    ->select('clients.ClientName','clients.Price')
    ->get();
return view('clients', compact('barChart'));

In the view file resources/views/clients.blade.php you can now access the $barChart variable.

You can use it in your view like this:

{{ json_encode($barChart) }}

or if you are not using Blade, then

<?= json_encode($barChart) ?>
Sign up to request clarification or add additional context in comments.

4 Comments

but, I can't use $barChart as an url inside $.ajax({url: }) . The very reason I asked this question so that I can use the output of json_encode($barChart) , inside $.ajax({url: ..here... }) in my view. Integrating google chart is made me do this. If you know a better way to integrate google chart with laravel with the value from mysql database please tell me.
you need to send it as data property of ajax right?
Thanks for your effort but it didn't work for me. I updated my question. please look at it. It might help you to understand my problem clearly.
in my answer I mentioned putting your clients.php file in resources/views. Did you do that?
0

Put your clients.php to resenter code hereources/views directory and name it clients.blade.php

Change your controller like

<?php 
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller {
public function barChart(){
$barChart=DB::table('clients')
->select('clients.ClientName','clients.Price')-  >get();
return view('clients')->with('barChart' => $barChart);
}
?>

Comments

0

Well finally I came up with the solution. I can't pass variable to public folder and giving the ulr in ajax was also a problem in that case creating the data table is obvous then pass it. the controller part will be

public function index()
{
    try{
        $val=DB::connection()->getDatabaseName();
        if(DB::connection()->getDatabaseName()) {

            $barChart= DB::table('clients')
                ->select('clients.ClientName','clients.Price')
                ->get();

            $rows = array();
            //flag is not needed
            $flag = true;
            $table = array();
            $table['cols'] = array(
                array('label' => 'Weekly Task', 'type' => 'string'),
                array('label' => 'Percentage', 'type' => 'number')

            );

            $rows = array();
            foreach($barChart as $r) {
                $temp = array();
                $temp[] = array('v' => (String)$r->ClientName);
                $temp[] = array('v' =>(int)$r->Price);
                $rows[] = array('c' => $temp);
            }

            $table['rows'] = $rows;
            $bar = json_encode($table);





            return view('home')
                ->with('bar', $bar);

        }else{
        }
    }catch (\Exception $e){
    }

}

The view part will be

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
                    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
                    <script type="text/javascript">

                        // Load the Visualization API and the piechart package.
                        google.load('visualization', '1', {'packages':['corechart']});

                        // Set a callback to run when the Google Visualization API is loaded.
                        google.setOnLoadCallback(drawChart);

                        function drawChart() {

                            // Create our data table out of JSON data loaded from server.
                            var data = new google.visualization.DataTable(<?=$bar?>);
                            var options = {
                                title: 'My Chart',
                                is3D: 'true',
                                width: 400,
                                height: 300
                            };
                            // Instantiate and draw our chart, passing in some options.
                            // Do not forget to check your div ID
                            var chart = new google.visualization.BarChart(document.getElementById('barChart'));
                            chart.draw(data, options);
                        }
                    </script>

courtesy php mysql google chart json complete example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.