0

I'm trying to store a session array inside a jquery variable.

My code:

<script>
@if(session()->has('zoektermen'))
    var zoektermen = '{{ session()->get('zoektermen') }}';
    console.log(zoektermen);
@endif
</script>

Putting in session inside controller:

if(isset($_GET['searchquery'])) {
    $searchquery = $_GET['searchquery'];
}

if(session()->has('zoektermen')) {
    session()->forget('zoektermen');
    session()->put('zoektermen', $searchquery);
} else {
    session()->put('zoektermen', $searchquery);
}

But i'm getting an error because {{ }} expects a string and not an array.

htmlspecialchars() expects parameter 1 to be string, array given

What is the correct way to store the array from the session into a JS array?

5
  • Try with other blade {!! !!} and see. Commented Jun 27, 2017 at 11:13
  • 2
    You can not use php array to JS. You have to convert to JSON and then you can use there Commented Jun 27, 2017 at 11:13
  • @PandhiBhaumik Same error Array to string conversion Commented Jun 27, 2017 at 11:15
  • 1
    Then you likely did not do it correctly ... encoding any data object as JSON will give you a string value. Commented Jun 27, 2017 at 11:17
  • Your code is not sufficient to solve this issue, paste the whole or relevant code from which the errors causes. Commented Jun 27, 2017 at 11:17

2 Answers 2

3

Do like this

<script>
@if(session()->has('zoektermen'))
    var zoektermen = '{{json_encode(session()->get("zoektermen"))}}';
     zoektermen= $.parseJSON(zoektermen);
    console.log(zoektermen);
@endif
</script>

I thing it will help you.

Sign up to request clarification or add additional context in comments.

1 Comment

escape quotes or use double quotes arounds here '{{json_encode(session()->get('zoektermen'))}}'
2

Use php json_encode and decode in JS to get PHP array in JavaScript

<script>
@if(session()->has('zoektermen'))
    var zoektermen_json = "{{ json_encode(session()->get('zoektermen')) }}";
    var zoektermen = JSON.parse(zoektermen_json);
    console.log(zoektermen);
@endif
</script>

2 Comments

I'm getting this error :SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
@JordyGroote : what after replacing {{ ... }} to {!! ... !!} ?

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.