Home > Enterprise >  How to convert Javascript JSON.stringify() to PHP Array
How to convert Javascript JSON.stringify() to PHP Array

Time:06-26

I've been banging my head against the wall for 2 days now, searching back and forth for solution for this problem, please enlighten me with this one:

I have this JavaScript Code that include a blade file and pass a data through it.

const loadTemplate = (locationinfo) => {

    let info = `
        <div >
            <h1>${locationinfo.business_name}</h1>
            @include('pages/business-space/templates/t1',[
                'locationinfo'=>'${JSON.stringify(locationinfo)}', //this is the code
            ])
        </div>`;
    return info;
}

When I log JSON.stringify(locationinfo) in my console it is just a plain json string:

{
   "id":3,
   "business_name":"Wen",
   "business_address":"sdfsdf",
   "lat":14.764397881407836,
   "lng":121.08031105807841,
   "is_active":"Yes",
   "created_by":null,
   "date_created":"2022-06-17 11:09:42"
}

In my t1.blade.php if I echo the locationinfo variable it still displays the same:

echo $locationinfo;
//and the result:
{
   "id":3,
   "business_name":"Wen",
   "business_address":"sdfsdf",
   "lat":14.764397881407836,
   "lng":121.08031105807841,
   "is_active":"Yes",
   "created_by":null,
   "date_created":"2022-06-17 11:09:42"
}

But When I tried to decode it using json_decode it becomes null. Here is my code:

$arr = json_decode($locationinfo); //this is null

foreach ($arr as $key => $value) {
  echo $key;
}

Another Error:

$arr = json_decode($locationinfo, true);

foreach ($arr as $key => $value) {
  echo $key;
}
//error: foreach() argument must be of type array|object, null given

Why is this happening? Thanks in advance.

CodePudding user response:

First make sure that $locationinfo is exactly a json string. I suspect it is a php associative array.

Try echo $locationinfo['id'];. If value appears u don't want to decode it. Use $locationinfo directly withot json decode.

If it is a json, Try using like this,

$arr = json_decode($locationinfo, true);

CodePudding user response:

Add a stripslashes.

$data = json_decode(stripslashes($data),true);

Demo : http://codepad.org/XX9QD3iX

Answered here : https://stackoverflow.com/a/37599821/19168006

Edit : example in demo has stdClass error, this is the working one : http://codepad.org/lfJJu5yA

CodePudding user response:

you can't pass js data to php ,because php renderd first.

but you can call ajax and return blade to response

your ajax call

const loadTemplate = (locationinfo) => {
    $.ajax({
        data: {
            'locationinfo': locationinfo,
        },
        type: "post",
        url: "{{route('someRoute')}}",
        success: function (data) {
            let info = `
            <div >
                <h1>${locationinfo.business_name}</h1>
                ${data}
            </div>`;
            return info;
        },
        error: function () {
            //has error
        }
    });
}

your route

Route::get('/getAjaxData', [AjaxController::class,'show']) ->name('someRoute'); // but i use __invoke controller

your controller

<?php

namespace YOUR_NAMESPACE;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AjaxController extends Controller
{
    public function show(Request $request)
    {
        $data = $request->input('locationinfo');

        return view('pages/business-space/templates/t1')->with([
            'locationinfo' => $data,
        ]);
    }

}
  • Related