dpz3471 2016-12-14 15:01
浏览 44
已采纳

通过ajax调用搜索结果时获取未定义

I have a Symfony app which allows CRUD operations on some events and also searching for them. The problem I get is when trying to get the results I'm searching for displayed without refreshing the page. It's the first time I'm using ajax and I think it's something wrong with the function. When I search for a word in any event name, the page is not refreshing and it shows undefined instead of showing the entries. I appreciate any help!

Here's the method from the Controller:

public function ajaxListAction(Request $request){

        //fetch the data from the database and pass it to the view
        $em = $this->getDoctrine()->getManager();
        $searchTerm = $request->get('search');

        $form = $this->createFormBuilder()
        ->add('search', SubmitType::class, array('label' => 'Search', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))->getForm();

        $organizer = array();
        if($searchTerm == ''){
            $organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAll();
        }

        elseif ($request->getMethod() == 'GET') {
            $form->handleRequest($request);
            $em = $this->getDoctrine()->getManager();
            $organizer = $em->getRepository('AppBundle:Organizer')->findAllOrderedByName($searchTerm);
        }

        $response = new JsonResponse();
        $results = array();

        foreach ($organizer as $value) {
            $results[] = json_encode($value);
        }

        return $response->setData(array(
            'results' => $results
        ));
    }

and here's the script for the search:

    $(document).ready( function(event) {
    $("#search").submit(function(event) {
        event.preventDefault(); //prvent default submission event

        $form = $(this);

        var data  = $('#search_term').val();

        $.ajax({
            url: '/ajax',
            type: "GET",
            data: {'search' : data },
            success: function(response){
                var output = '';
                for (var i = 0; i < response.length; i++) {
                    output[i] = output + response;
                }
                $('#ajax_results').html('<tr><td>' + response.id + '</td></tr>' + '<tr><td>' + response.name + '</td></tr>' + '<tr><td>' + response.dueDate + '</td></tr>');
            }
        })

    });
});

and the index.html.twig file for displaying the data:

{% extends 'base.html.twig' %}

{% block body %}
    <h2 class="page-header"> Latest events </h2>
<form id="search" method="GET" action="">
        <input type="text" name="search" id="search_term" />
        <input type="submit" name="submit" value="Search" />
</form>
    <hr />
    <table  class="table table-striped">
         <thead> 
         <tr> 
             <th>#</th> 
             <th>Event</th> 
             <th>Due Date</th>
             <th></th>
         </tr>
         </thead> 

         <tbody id="ajax_results"> 
         {% for Events in organizer %}
         <tr> 
             <th scope="row">{{Events.id}}</th>
             <td>{{Events.name}}</td>
             <td>{{Events.dueDate|date('j F, Y, g:i a')}}</td>
             <td>
             <a href="/organize/details/{{Events.id}}" class="btn btn-success">View</a>
             <a href="/organize/edit/{{Events.id}}" class="btn btn-default">Edit</a>
             <a href="/organize/delete/{{Events.id}}" class="btn btn-danger">Delete</a>
             </td>
         </tr>

         {% endfor %}

    <table class="table table-striped">

        {% if organizer|length > 0  %}
           {% for items in organizer %}

           {% endfor %}
        {% else %}
                <tr>
                   <td colspan="2">No matching results found!</td>
                </tr>
        {% endif %}
    </table>
         </tbody> 
    </table>
{% endblock %}
  • 写回答

2条回答 默认 最新

  • dseax40600 2016-12-14 15:17
    关注

    Lets try to refactor your code first. Perhaps it will bring you near the solution.

    public function ajaxListAction(Request $request){
    
        $searchTerm = $request->get('search');
        //don't need form here
    
        if($searchTerm == ''){
            $organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAll();
        }else{
            //repository should search by searchterm in next step
            $organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAllOrderedByName($searchTerm);
        }
    
        return new JsonResponse($organizer);
    }
    

    and javascript:

    $(document).ready( function(event) {
        $("#search").submit(function(event) {
            event.preventDefault(); //prvent default submission event
    
            $form = $(this);
    
            var data  = $('#search_term').val();
    
            $.ajax({
                url: '/ajax',
                type: "GET",
                data: {'search' : data },
                success: function(response){
                    $('#ajax_results').html('');
                    $.each(response, function(key, value) {
                        console.log(key, value);
                        $('#ajax_results').append('<tr><td>' + response[key].id + '</td></tr>' + '<tr><td>' + response[key].name + '</td></tr>' + '<tr><td>' + response[key].dueDate + '</td></tr>');
                    });
    
                }
            })
    
        });
    });
    

    Please tell what do you see in js console after submit the search?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog