0

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

2
  • Check console for errors. Commented May 28, 2015 at 13:13
  • What is the error in your javascript console ? Commented May 28, 2015 at 13:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

can you be more specific? what do you mean with "// Get your data from ajax here and prepare it" ?
i think that the problem is not there, because $data is null
Then you need to solve front-end issue not symfony side of the story.
help me to understand, to extract the value from the $data variable, i have to write something like "$itemName = $data['theInputAttributeName'] right?
You need to do some research before asking questions. Why don't you just do print_r($data) to what it has in it? Then access it's content. While making AJAX call open your browser network tab to see what the response is so son....
|
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.