chicken burger
chicken burger

Reputation: 774

Basic error message in AJAX - Symfony3

I'm working on PhpStorm.2016.3.2 with Symfony3 (Ubuntu 16.04)

I created an AJAX request that is functional. The only part i'm missing is the error message.

I have a TextType.php(form) where I can write things and a button where I can search the results, and if it matches, my result appears, but if it is wrong, well nothing happens and I would like to show a message error like "Oops ! There is nothing !" while staying on the same page.

Here is my AJAX request in my view:

<script>
        $(document).ready(function () {
            $('.ajax').on('click', function(e){
                e.preventDefault();
                $.ajax({
                    url:'{{ (path("app_sort_restaurants")) }}',
                    type: "POST",
                    dataType: "json",
                    data: {
                        "city": $('#search_bar_city').val()
                    },
                    success: function (data)
                    {
                        var bloc = $('#ajax-results');
                        bloc.html('');
                        for(var i = 0; i < data.length; i++) {
                            bloc.append('<div><h2>' + data[i]['name'] + '</h2></div>'); 
                        }
                    },
                });
            });
            return false;
        });
    </script>

And here is my controller:

public function ajaxSortRestaurantAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $restaurants = $em->getRepository('AppBundle:Restaurant')->findBy(array('city' => $request->request->get('city')));


    $formattedData = array();
    foreach ($restaurants as $restaurant) {
        $formattedData[] = array(
            'name' => $restaurant->getName(),
            'city' => $restaurant->getCity(),
        );
    }
    return new JsonResponse($formattedData);
}

I don't know whether I should make a loop like this in the controller or in the AJAX request. I know there is the error: function() missing but I don't know where to put it to make it properly work. I'm a bit lost on the error side.

To show you what is happening, actually its like this

here its working

enter image description here

and here is not

enter image description here

I would like to show "Oops ! There is nothing !" when the search is wrong. Not a blank space like in the example

If anyone have an advice it would be must appreciated

Upvotes: 1

Views: 106

Answers (1)

madsroskar
madsroskar

Reputation: 1238

I know there is the error: function() missing but I don't know where to put it to make it properly work.

This is to be added on the same level as success and the other options passed to $.ajax(), meaning your code could be

$(document).ready(function () {
        $('.ajax').on('click', function(e){
            e.preventDefault();
            $.ajax({
                url:'{{ (path("app_sort_restaurants")) }}',
                type: "POST",
                dataType: "json",
                data: {
                    "city": $('#search_bar_city').val()
                },
                success: function (data)
                {
                    var bloc = $('#ajax-results');
                    bloc.html('');
                    for(var i = 0; i < data.length; i++) {
                        bloc.append('<div><h2>' + data[i]['name'] + '</h2></div>'); 
                    }
                },
                error: function(xhr, status, error) {
                    // Handle error
                }
            });
        });
        return false;
    });

Note the parameters, which are described in the documentation:

xhris an XMLHttpRequest, status is "a string describing the type of error that occurred and an optional exception object, if one occurred.", and error is a string that shows the message of the HTTP status code. e.g. "Not Found" for 404.

Edit after comments

As I understand, having the controller return an error is also an issue. For this to happen, you need to return a Response object with a non-200 status code, or throw an exception.

An example of this is:

public function ajaxSortRestaurantAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $restaurants = $em->getRepository('AppBundle:Restaurant')->findBy(array('city' => $request->request->get('city')));


    $formattedData = array();
    foreach ($restaurants as $restaurant) {
        $formattedData[] = array(
            'name' => $restaurant->getName(),
            'city' => $restaurant->getCity(),
        );
    }

    if (0 === count($formattedData)) {
        return new Response("", 404);
    }

    return new JsonResponse($formattedData);
}

In the case above, a 404 will be returned if there is no formatted data to return.

Once this is done, you can use the error function in the Ajax-option error to display an error message where you want it to show.

Upvotes: 1

Related Questions