Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

Sorry for the beginner question.

I'm trying to use PHP array to Javascript variable.

But I got below console error: enter image description here

This is my PHP,

<?php
namespace App\Http\Controllers\test;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use DB;

class PricePinpointController extends Controller
{
  function index(Request $request){

    $test = DB::connection('test')->table('aaa')->where('seq', '111')->select('longitude', 'latitude')->get();

    $position = array($test[0]->longitude, $test[0]->latitude);

    return view('index', ['center' => json_encode($position)]);
  }
}

?>

And This is my index.blade.php,

<script>
$(document).ready(function(){
    console.log({{$center}});
});
</script>

Could you help point out where did I go wrong?

share|improve this question

When you use {{ }} the data/text echo'd is escaped.

By default, Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks.

You just need to change these brackets to {!! !!} to avoid escaping the information:

<script>
$(document).ready(function(){
    console.log({!! $center !!});
});
</script>

You can read more about this in the docs.

share|improve this answer
    
Thank you very much! successed!! – jonggu yesterday
    
@jonggu. Great! Can you please mark this as accepted if it solves your problem. – James yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.