0

I'm trying to inject a javascript variable inside php curly braces code, but I am no t able to get it working.

This is the code that I have inside a php.blade javascript function:

swal(...),
success(data){
    $('#especie').select2("trigger", "select", {
    data: {
        id: data.id_especie,
        text: "(" + data.especie.id + ") " + data.especie.nombre,
        html: "{{ view('especies.select', [ 'especie' => data.especie])->render() }}"
    },
    templateResult: iconosTemplate,
    templateSelection: iconosTemplate
    });
}

Inside html: {{ view('especies.select', [ 'especie' => data.especie])->render() }} I want the data variable to be the swal success data, but it is not taking it as it's inside php context.

  • 1
    PHP runs on the server while building the page. Therefore it runs _before_ your Javascript, which runs in the browser and (therefore) cannot execute until the page has been sent to the browser. If you look at the rendered output of this code (e.g. via your browser's View Source feature) you'll see that the `html: ` line will contain the _output of executing that PHP_. So what you're asking for doesn't really make sense I don't think. If you want PHP to do something as the result of some JavaScript code running, you need to send a new HTTP request to the server (e.g. via AJAX/fetch). – ADyson Nov 03 '22 at 10:43

1 Answers1

-1
swal(...),
success(data){
    $('#especie').select2("trigger", "select", {
    data: {
        id: data.id_especie,
        text: "(" + data.especie.id + ") " + data.especie.nombre,
        html: `{{ view('especies.select', [ 'especie' => '${data.especie}'])->render() }}`
    },
    templateResult: iconosTemplate,
    templateSelection: iconosTemplate
    });
}

You can use JavaScript's template syntax.

One thing you should be aware of is that objects in JavaScript are in JSON format, so your view function should handle that.

The html arg will be passed like this:

{{ view('especies.select', [ 'especie' => '{"id": 123, "nobre": 123}'])->render() }}
S.Visser
  • 4,645
  • 1
  • 22
  • 43
  • If `{{` denotes PHP templating code then you can't meaningfully put a JS variable into the middle of that, since the PHP code will have already executed by the time JS runs – ADyson Nov 03 '22 at 10:44