2

Currently I've been Ajaxing a route that renders a Twig template via a Controller and injecting it into the page - all is well.

return $this->render('MyBundle:Requests:results.html.twig', array('system' => $lc_system));

However, in my JavaScript, I would like to get some extra information returned... Specifically I want a count of the results, so I can check it against a JS variable. I could put it into the twig file and then get it in JS that way, but it feels horrible.

Is there any way to get any variables sent down with the Ajax response, or a best practice way to approach this.

andybarnes
  • 294
  • 1
  • 14
  • How about returning a JSON response containing your variables and your rendered string as one of them as in this answer - http://stackoverflow.com/a/28212182/1791606 ? – qooplmao Jan 30 '15 at 16:27
  • possible duplicate of [How to return both integer parameter and render template as response in Symfony2](http://stackoverflow.com/questions/28211290/how-to-return-both-integer-parameter-and-render-template-as-response-in-symfony2) – Michael Sivolobov Jan 30 '15 at 17:00
  • Thanks every one. This answered my question: http://stackoverflow.com/a/28212182/1835501 – andybarnes Feb 03 '15 at 09:12

2 Answers2

0

Use echo in your PHP function instead of return.

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function() {
    doSomething(data); //Data is output
    }
});

In PHP:

<?php 
  $output = some_function();
  echo $output;
?> 

It's an argument passed to your success function. The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation.

Matheno
  • 4,112
  • 6
  • 36
  • 53
0

If you weren't returning actual page content in your response, I'd say to return a JSON response and call it good. But since you're already using your response body for some HTML, you have to come up with another way to return the info.

One approach I've used in the past is to add a custom HTTP header and return my "meta" values that way. First, set the header in your PHP (make sure this happens before any output):

header('X-MyCustomHeader: ' . $phpVar);

Then, you can get it in your jQuery success method like this:

success: function(result, status, xhr) { 
    var customHeader = xhr.getResponseHeader('X-MyCustomHeader'));
}

While you can technically name your custom header anything you want, see this post for best practice/naming convention ideas:

Custom HTTP headers : naming conventions

Community
  • 1
  • 1
mopo922
  • 6,293
  • 3
  • 28
  • 31