Markdown

[Symfony] how to use put method in Ajax.

how to use put method in Ajax.
<script>
    var Submit = function () {
        var data = {
            userName: "testEdit",
            msg: "testEdit"
        }
        $.ajax({
            url: 'http://test123/api/edit/111',
            type: "PUT",
            data: data

                    success: function (msg) {
                // alert(msg);
                console.log(msg)
            },

            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }
</script>
    /**
     * Get a request and edit the Message
     * @Route("api/edit/{id}", name="api/edit")
     * @Method("PUT")
     */
    public function editActionAPI(Request $request, $id)
    {
        $paramMsg = $request->request->get('msg');
        $paramName = $request->request->get('userName');

        $em = $this->getDoctrine()->getManager();
        $messages = $em->getRepository('AppBundle:Message');
        $message = $messages->find($id);

        if ($message && $paramMsg !== null && $paramName !== null) {
            $message->setUserName($paramName);
            $message->setMsg($paramMsg);
            $message->setupdatedAt(new \DateTime('now', new \DateTimeZone('Asia/Taipei')));

            $encodersArray = [
                new XmlEncoder(),
                new JsonEncoder()
            ];
            $normalizersArray = [new ObjectNormalizer()];
            $encoders = $encodersArray;
            $normalizers = $normalizersArray;
            $serializer = new Serializer($normalizers, $encoders);
            $json = $serializer->serialize($message, 'json');
            $dejson = json_decode($json, true);
            $json = $serializer->serialize($dejson, 'json');

            $response = new Response();
            $response->setContent($json);
            $response->headers->set('Content-Type', 'application/json');
            $response->headers->set('Access-Control-Allow-Origin', '*');

            $em->flush();
            dump($json, $messages);
            return $response;
        } else {
            return new Response("GG");
        }
    }

留言