Symfony 5 error 500 when performing an ajax query

I’m currently working on a mini web project, so i considered as an opportunity to learn Symfony framework since it’s very knows and have a great reputations.
So the thing is i’m developping a simple game and the players can store some items in their inventory, or change their coordinates and to do so dynamically i thought about using Ajax but each time the query is not being executed and the console shows me: 500
Internal Server Error and also the route isn’t being mapped correctly by the twig path function.
Here’s the html.twig file containing a portion of the JS code (to test if it works i inserted it directly to the html.twig but in reality i want it on an external js file because i have many interactions and functions to implement already coded but unfortunately i always face the same problem)

<html lang="fr">
<head>
<meta charset="UTF-8">
<title>{% block title %}LIP{% endblock %}</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
{% block stylesheets %} 

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-    awesome.min.css">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
    integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq  /sMZMZ19scR4PsZChSR7A=="
    crossorigin=""/>
<link rel="stylesheet" href="{{asset('css/signInUp.css')}}"/>
<link rel="stylesheet" href="{{asset('css/Homestyle.css')}}"/>
<link rel="stylesheet" href="{{asset('css/Playerstyle.css')}}"/>

{% endblock %}
<link rel = "icon" href =  "{{asset("Icons/eiffel64.png")}}" type = "image/x-icon"> 
       {% block javascripts %}
        <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
        integrity="sha512- XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin=""></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
        $(document).ready(function () {
            console.log("executing internal ajax!");
            //var idMagasin = $('#choixMagasin option:selected').attr('id');
            $.ajax({
                method: "POST",
                url: "{{path('move_player')}}",
                //data: {id: idMagasin},
                success: function(data){
                    console.log(data);
        
                    //var periode = data.periode;
                    //console.log(donnees);
                }
            });
        });
     </script>
    {% endblock %}

 </head>
 {% block body %}
 <body>

  <div class="section1" id="mapid">
  

  </div>


  <div class="section2" id="playerInterface">
  {% if app.user %}
    <a href="{{path('logout_Player')}}" id="logout">Déconnexion</a>
  {% else %}
  {% endif %}  
  <div move-path="{{path('move_player')}}"></div>

  </div>
  <div class="footer">
  <p>2020 Copyright ©  ENSG Géomatique Developped by MaghraouiDE & Namekon Teulong PF</p>
  <a href="https://www.facebook.com/ENSGeomatique" class="fa fa-facebook"></a>
  <a href="https://fr.linkedin.com/edu/ecole-nationale-des-sciences-g%C3%A9ographiques-12351" class="fa fa-linkedin"></a>
  <img src="{{asset('Icons/logo_ensg.png')}}"  class="logo"/>
</div>{% if app.user is defined %}
        {% set player_data = {
                pseudo: app.user.Username,
                longitude: app.user.longitude,
                latitude: app.user.latitude,
                inventaire: app.user.inventaire,

            } %}
            <div data-player='{{ player_data | json_encode | raw }}'>
            </div>
        {% endif %}

            


    {% block javascript %}
    <script src="{{asset('js/code.js')}}"></script>
    {% endblock %}
    {% endblock %}
    </body>
    </html>

Here’s my controller:

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationRequest;
use AppEntityItems;
use AppEntityPlayers;
use AppEntityInventaire;


class InteractionsController extends AbstractController
{
/**
 * @Route("/interactions", name="interactions")
 */
public function index(): Response
{
    return $this->render('interactions/index.html.twig', [
        'controller_name' => 'InteractionsController',
    ]);
 }
/**
 * @Route("/interactions/move_player",name="move_player")
 */
public function moveplayer(Request $request,EntityManagerInterface $em){
    $player = $this->getUser();
    return new JsonResponse(array("username"=>$player->getUsername(),"longitude"=>$player->getLongitude()));
}
}

/**
 * @Route("/interactions/affiche_scenario", name="affiche_scenario")
 */
public function afficheScenario(Request $request){
    if ($request->isXmlHttpRequest()){
        $repository = $this->getDoctrine()->getRepository(Scenarios::class);
        return new JsonResponse($repository->findBy($request->request->get("num_scenario")));
    }
    else{
        return new JsonResponse(array["error"=>"Something went wrong!"]);

    }
}
}

/**
 * @Route("/interactions/add_item",name="add_item")
 */
public function addItem(Request $request,EntityManagerInterface $em){

    $player = $this->getUser();
    $inventaire=$player->getInventaire();
    return new JsonResponse(array("player"=>$player,"inventaire"=>$inventaire->getItem_id()));
    
    }

I removed the different processing from these controllers because i just want to test the json response which doesn’t work, i should also add that i tried to use other method (ajax query in classical JS without Jquery, with using XMLHttpRequest and also fetch API wich i have already used them in other applications but i can’t figure out what am i doing wrong here on Symfony environmment.

Thanks in advance everyone and have a good day.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *