Andrea
Andrea

Reputation: 13

Symfony2: saving on db using ajax call

i'm studying the Symfony2 framework and i want to create a simple application with a very simple form (one text field) and save the submitted data (using ajax) in a very simple table on the database. My goal is to view and update (in the same page using ajax) the entire database table every time a new submitted data is sent and saved. This is what i done until now, i'm not able to save anything and a 500

DefaultController.php

class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {
        $item = New Item();
        $form = $this->createForm(new ItemType(), $item,  array('action'=>$this->generateUrl('vendor_name_simple_homepage'),'method'=>'POST'));
        $form->add('Submit','submit',array('label'=>'Add'));
        $form->handleRequest($request);
        if ($request->isXmlHttpRequest()) {
            $this->saveAction($item);
        }
        return $this->render('VendorNameSimpleBundle:Default:lista.html.twig',array('form' => $form->createView()));
    }
    public function saveAction($item){
        $em = $this->getDoctrine()->getManager();
        $em->persist($item);
        $em->flush();
        return new Response('success');
    }
}

The JQuery script

<script>
            $(document).ready(function() {
                $('form').submit(function(event) {
                    // prevents the browser from "following" the link
                    event.preventDefault();

                    var $url = $("form").attr("action");// + '.json';
                    var $value = $('#item_itemName').val();

                    $.ajax({
                        type: "POST",
                        url: $url,
                        data: $value,
                        success: function(data) {
                            $('ul').html(data);
                        }/*,
                        dataType: 'json'*/
                    });
                });
            });
        </script>

EDIT: This is the Network console output, there is no error in the JS console

An exception occurred while executing 'INSERT INTO item (itemName) VALUES (?)' with params [null]: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'itemName' cannot be null (500 Internal Server Error)

UPDATE: seems that the request is successfully sent but i can't access (or i don't exactly know how to do) to the content request because the controller receive this Request:

/app_dev.php/myapp/path/ HTTP/1.1 Accept: / Accept-Encoding: gzip, deflate Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3 Cache-Control: no-cache Connection: keep-alive Content-Length: 11 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Cookie: PHPSESSID=qhou8f9lias0i9fh3besdpbii7 Host: localhost:8000 Pragma: no-cache Referer: http://localhost:8000/app_dev.php/myapp/path/ User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 X-Php-Ob-Level: 1 X-Requested-With: XMLHttpRequest MyInputData

Upvotes: 0

Views: 1417

Answers (2)

BentCoder
BentCoder

Reputation: 12740

I think you're overcomplicating it. I would suggest you to do all in one methods such as:

Note: This gives you general idea!

public function saveAction(Request $request)
{
    if ($request->isXMLHttpRequest()) {
        $data = $request->request->get('request');
        $itemName = // Extract it from $data variable

        $item = NewItem();
        $item->setItemName($itemName);

        $em = $this->getDoctrine()->getManager();
        $em->persist($item);
        $em->flush();
    } else {
        // Do something else
    }
}

You should also handle exceptions like this Catching ORM, DBAL and PDO exceptions in symfony. Also look at Symfony2cheatsheet for nice stuff since you're learning.

Upvotes: 1

Ricardo
Ricardo

Reputation: 522

I can't say for certain until you post the exact error, but your saveAction($item) seems to expect an Object that you persist/flush into Doctrine, however it looks like you're not passing that along.

Ah my bad, see you've done that through the indexAction, I'd recommend to check if you post to the right url. In most browsers you can also see the XHR Requests to check what the exact error is the request gave you.

Edit Thanks for your error, the item you're saving is the empty object you've created, make sure you save the item with the data you've retrieved, with this line:

$filledinItem = $form->getData();

Upvotes: 0

Related Questions