php - Send data in Ajax response

621

hey I am trying to populate one select dropdown on the basis of another one using ajax. I have one select populated with portfolios and the 2nd one is empty. when I select an option from the 1st select box. I call an ajax function in which I send the selected portfolio id, In the ajax method I find the groups for the selected id, how can I populate the 2nd select with the groups I found. My code is

The form which contains two selects

<form name="portfolios" action="{{ path('v2_pm_portfolio_switch') }}" method="post" >
    <select id="portfolios" name="portfolio" >
      <option selected value="default">Select Portfolio</option>
      {% for portfolio in portfolios %}
        <option get-groups="{{ path('v2_pm_patents_getgroups') }}" value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
      {% endfor %}
    </select><br/><br/>
    <select id="portfolio-groups" name="portfolio-groups" >
      <option selected value="default">Select Portfolio Group</option>
    </select><br/>
</form>

The JS

 <script>
    $(document).ready(function(){
        $('#portfolios').change(function() {
            var id = $("#portfolios").val();
            var url = $('option:selected', this).attr("get-groups");
            var data = {PID:id};
            $.ajax({
                type: "POST",
                data: data,
                url:url,
                cache: false,
                success: function(data) {
                    //want to populate the 2nd select box here
                }
            });
        });
    }); 
</script>

Controller method where I find the groups for the selected portfolio

public function getgroupsAction(Request $request){
    if ($request->isXmlHttpRequest()) {

        $id = $request->get("PID");
        $em = $this->getDoctrine()->getEntityManager();
        $portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
        ->getpatentgroups($id);
        return $portfolio_groups;
    }
}

Any idea how can i send the portfolio groups and populate the 2nd select

thanks in advance

457

Answer

Solution:

UsegetJson instead ofajax();

Json (JavaScript Object Notation) , is the most easiest way to send structured data between php and javascript.

I Assuming here that the controller respond directly to the ajax query and that$portfolio_groups is an associative array with "id" and "name" as keys or an object with this same properties.

In your PHP controller send json data:

public function getgroupsAction(Request $request){
    if ($request->isXmlHttpRequest()) {

        $id = $request->get("PID");
        $em = $this->getDoctrine()->getEntityManager();
        $portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
        ->getpatentgroups($id);
        echo json_encode($portfolio_groups);
    }
}

Then use getJson to retrieve data and iterate over it :

$.getJSON(url, data, function(result) {
    var options = $("#portfolio-groups");
    $.each(result, function(item) {
        options.append($("<option />").val(item.id).text(item.name));
    });
});

Have a look to the getjson documentation for more detail about it

276

Answer

Solution:

Check out this XML tutorial (someone out there is going to flame me for linking to w3schools) it's a good start.

AJAX requests are, in VERY broad terms, calls which make a browser open a window that only it can see (not the user). A request is made to the server, the server returns a page, the script that made the request can view that page. This means that anything which can be expressed in text can be transmitted via AJAX, including XML (for which the X in AJAX stands for).

How is this helpful? Consider, if you are trying to populate a drop down list, you need to return a list of items to populate it with. You COULD make an ajax call to a pagehttp://www.mysite.com/mypage.php?d=select1 (if you are unfamiliar with GET and POST requests, or are a little in the dark regarding the more utilitarian aspects of AJAX, another full tutorial is available here) and have it return a list of items as follows:

item1
item2
item3
...

And scan the text for line breaks. While this certainly would work for most cases, it's not ideal, and certainly won't be useful in all other cases where AJAX may be used. Instead consider formatting the return in your PHP (.NET, ASP, whatever) in XML:

<drop>
    <item>item1</item>
    <item>item2</item>
    <item>item3</item>
</drop>

And use Javascripts built in parser (outlined here) to grab the data.

204

Answer

Solution:

What I would do is to use the $.load() function. To do this, yourgetgroupsAction should return the options html.

The JS:

<script>
    $(document).ready(function(){
        $('#portfolios').change(function() {
            var id = $("#portfolios").val();
            var url = $('option:selected', this).attr("get-groups");
            var data = {PID:id};

            // Perhaps you want your select to show "Loading" while loading the data?
            $('#portfolio-groups').html('<option selected value="default">Loading...</option>');

            $('#portfolio-groups').load(url, data);
        });
    }); 
</script>

I don't know how$portfolio_groups stores the data, but let's say you'd do something like this in your response:

<?php foreach($portfolio_groups as $p) : ?>
    <option value="<?php echo $p->value ?>"><?php echo $p->name ?></option>
<?php endforeach ?>

This way, the select will be filled with the options outputted bygetgroupsAction.

563

Answer

Solution:

The easiest way would be to return json string from your controller and then process it in the 'success' call of the $.ajax.

Lets assume, that your $portfolio_groups variable is an array:

$portfolio_groups = array('1'=>'Portfolio 1', '2' => 'Portfolio 2');

then you can return it from controller as json string like this:

echo json_encode($portfolio_groups);

Then in your jQuery ajax call you can catch this string in the response (the 'success' setting of the $.ajax). Don't forget to add setting dataType: 'json'

Roughly, your $.ajax call will look like this:

$.ajax({
    type: "POST",
    data: data,
    url:url,
    cache: false,
    dataType: 'json', // don't forget to add this setting
    success: function(data) {
        $.each(data, function(id, title){
            var node = $('<option>').attr('value', id).html(title);

            // this will simply add options to the existing list of options
            // you might need to clear this list before adding new options
            $('#portfolio-groups').append(node);
        });
    }
});

Of course, you will also need to add the checks if the data is not empty, etc.

977

Answer

Solution:

Supposing that the function getgroupsAction stays in a flat php controller ( not inside a class ) you should tell the server to execute the function

so at the end of file being called by ajax you should barely call the function first ( probably you did it! )

For your patents group result set, you can generate the select by php or by javascript

In first case you should do this:

//php
  $options = getgroupsAction($_REQUEST);
  $return = "<select name =\"name\" id=\"id\"><option value=\"\"></option>";
 foreach( $options as $option){
       $return.= "<option value=\"$option\">$option</option>";
 }
 $return .= "</select>";
  echo $return;

Then in Javascript: // javascript

  var data = {PID:id};
        $.ajax({
            type: "POST",
            data: data,
            url:url,
            cache: false,
            success: function(data) {
                //inside data you have the select html code so just:
               $('#divWhereToappend').append(data);
            },
    error: function(data) {
                //ALWAYS print the error string when it returns error for a more easily debug
         alert(data.responseText);
            }
        });

People are also looking for solutions to the problem: php - How can I convert an RSS feed to $wp_query->posts?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.