peace_love
peace_love

Reputation: 6471

How can I display a variable with twig via ajax?

I have a function that is loading a form via Ajax on my page.

mypage.html.twig:

function forms(e,el) {

  var id = $(el).attr("data-id");
  var target = $(el).attr("data-target");

  e.preventDefault();
  var $link = $(e.currentTarget);
  $.ajax({
      method:'POST',
      data: {
        "id": id,
        "target": target
      },
      url: $link.attr('href')
  })
}


$('.create-item').on( 'click', function (e) {
      forms(e,this);
});

MyController.php

  $response = new JsonResponse(
        array(
          'message' => 'Success',
          'output' => $this->renderView('form.html.twig',
          array(
            'entity' => $item,
            'form' => $form->createView(),
          ))), 200);
          return $response;

This is the form that is loaded (form.html.twig):

<section class="content-header" style="margin-bottom:20px">
  <h1 style="float:left;margin-bottom:30px">{{ target }}</h1>
</section>
<section class="content" style="clear:left">
  <div class="form-group">
    {{ form_start(form) }}
    {{ form_end(form) }}
  </section>

The form is loaded correctly. But in the <h1></h1> area I want to load the variable target.

It is not working, I get an error message:

Variable "target" does not exist.

Upvotes: 0

Views: 146

Answers (1)

DarkBee
DarkBee

Reputation: 15607

You are not passing the posted value target to your view

$response = new JsonResponse(
        array(
          'message' => 'Success',
          'output' => $this->renderView('form.html.twig',
          array(
            'entity' => $item,
            'form' => $form->createView(),
            'target' => $target, //<-----
          ))), 200);
          return $response;

Upvotes: 2

Related Questions