Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
How to convert Javascript JSON.stringify() to PHP Array

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 class="location-info">
            <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.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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 class="location-info">
                <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,
        ]);
    }

}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda