Handling Ajax Posts in AngularJS and Symfony2: Dealing with Undefined Index Issue

My journey with the Symfony2 PHP framework is just beginning, and I am aware that it follows the MVC pattern for backend development. One of my current tasks involves creating a form that stores data in a database and then sends an email to the user with the information they inputted. To achieve this, I have utilized Doctrine, Swiftmailer, and entities within the Symfony2 framework.

When I use '<form method='post' action='saveIndex'></form>', everything functions as expected. However, when attempting to implement AngularJS AJAX for posting data, I encounter a 'Notice: Undefined index' error.

Here is the HTML code from my Twig template:

<form class="productForm">
<div class="inputs" style="float: left">
<input type="text" name="productId" data-ng-model="signup.user.productId"/>
<input type="text" name="firstName" data-ng-model="signup.user.firstName"/>
<input type="text" name="lastName" data-ng-model="signup.user.lastName"/>
<input type="email" name="email" data-ng-model="signup.user.email"/>
<input type="text" name="price" data-ng-model="signup.user.price"/>
<input type="text" name="timeStamp" data-ng-model="signup.user.time"/>
<textarea name="comments" data-ng-model="signup.user.comments"></textarea>
<button type="submit" name="submit" class="btn btn-primary" ng-click="submit(signup.user)">Submit Request</button>
</div>

</div>
</form>

Below is the code snippet from app.js:

myApp.controller('mainController',[
    '$scope',
    '$location',
    '$http',
    '$window',
    '$rootScope',
    function($scope, $location, $http, $window, $rootScope){
            $scope.submit = function (user) {
                    $http({
                        method: 'POST',
                        url: 'saveIndex',
                        data: $scope.signup
                    })
                    .success(function(data, status){
                        $log.warn(data, status);  //remove for production
                        $location.path('success');

                    })
                    .error(function(data, status){
                        $log.warn(data, status); //remove for production
                    });
            }
    }
]);

Here is the Symfony2 controller code:

// Save Information
public function saveIndexAction(){
    $post = new Post();                  
    $request = $this->get('request');
    $params = $request->request->all();
    $session = $this->get('session');
    $this->saveIndex(
        $params['productId'],
        $params['firstName'],
        $params['lastName'],
        $params['email'],
        $params['price'],
        $params['timeStamp'],
        $params['comments'],
        $session
    );

    $post->setProductId($params['productId']);
    $post->setFirstName($params['firstName']);
    $post->setLastName($params['lastName']);
    $post->setEmail($params['email']);
    $post->setPrice($params['price']);
    $post->setTimeStamp($params['timeStamp']);
    $post->setComments($params['comments']);

    // Store information in the database
    $em = $this->getDoctrine()->getManager();
    $em->persist($post);
    $em->flush();

    // Send the email
    $this->mailAction
        (
            $post->getId(),
            $params['productId'],
            $params['firstName'],
            $params['lastName'],
            $params['email'],
            $params['price'],
            $params['timeStamp'],
            $params['comments']
        );

    // Return the response
    $return=json_encode($post);//json encode the array
    return new Response($return,200,array('Content-Type'=>'application/json'));
}

I'm seeking guidance on how to successfully perform an AJAX POST request with Symfony2 controller and receive the response back in AngularJS for client-side routing. Any assistance would be greatly appreciated. Thank you.

Answer №1

After using var_dump($params), I discovered that the output was an undefined array with a size of 0.

To address this issue, I decided to add the following code snippet:

protected function getRequestJson(){
    $params = null;
    $content = $this->get("request")->getContent();
    if (!empty($content))
    {
        $params = json_decode($content, true);
    }
    return $params;
}


public function saveIndexAction(){
    $post = new Post();

    $signup_params = $this->getRequestJson();

    //flatten signup parameters
    $params = array();
    foreach ($signup_params as $p) {
        if (is_array($p)) {
            foreach($p as $key=>$val) {
                $params[$key]=$val;
            }
        }
    }
}

Implementing this change resolved the issue I was facing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to combining parameters prior to making an ajax request

Here is a code snippet that works: $('#someId').on('click', function() { var myData = '{ Periode: "something" }' $.ajax({ type: "POST", url: "/Nyhedsbrev/SendMailKunTilMig", contentType: &apos ...

Ways to enhance the functionality of a textarea

Question: How can I set a default value for an HTML <textarea>? Currently, I am utilizing ajax to transfer data from a form to the database but encountering a problem: <input class="input" type="text" name="do_kogo" id="odbiorca" size="25" v ...

Shutting down the jQuery pop-up

I am struggling with trying to display this code as a popup on my website. Here is the code I have: <div id="myDialog" title="myTitle"> <div class="table_cell"> <div class="message"></div> </div> <div class="tabl ...

Reordering div elements with JQuery

As soon as my page loads, I have a div set to display:block and another div set to display:none. I have implemented a toggle switch that should replace the visible div with the hidden one. However, I am facing an issue where after performing the switch, ...

Using JavaScript, you can move through an array of divs by detecting keypress events

<div id="wrapper"> <img class="seperator selected" src="imgs/character_1.png" tabindex="0" /> <img class="seperator" src="imgs/character_2.png" tabindex="0" /> <br /> <img class="seperator" src="imgs/character_3.p ...

Utilizing JSONP in the perfect combination of Jquery version 1.9 and Jersey version 2.5

I've searched extensively without finding a solution that meets my requirements. While I came across some similar threads here, here, and here, none of them resolved my issue or I failed to comprehend the solutions provided. Additionally, I have revie ...

Where can the data be found within an AngularJS HTTP POST request?

Can someone help me with this issue? I'm trying to send data to my server using an AngularJS button that triggers a function with an HTTP post request. However, I can't seem to locate where the data is stored in the request. Here is the code for ...

Assign values to variables in a JavaScript file using node.js

My tech stack includes node.js, express.js, and either pug or jade. Within my server, I inject a variable called pageId into a view. In the pug view, I utilize this variable using the following script: script. document.addEventListener('DOMConten ...

Using an asynchronous pipe filter with the ngFor loop in Angular 2 for efficient data

I have a JSON array that I need to iterate through in order to display data using an NGfor Loop. My goal is to apply filters after the data has been loaded to refine the results. The issue I am facing is that my pipe filter is returning 'cannot read p ...

Utilizing a PHP variable in an external JavaScript file

I have a PHP variable that I need to access in my JavaScript code. What is the best way to transfer the value from PHP to JavaScript? My PHP file contains HTML code similar to the following: <!doctype html> <html> <head> //some imp ...

Is there a way to utilize local resources in case CDNs are unable to load properly?

Encountering an issue with Bootstrap and jQuery loading from CDN, sometimes failing to import from the CDN source. For instance: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYii ...

Utilizing the map function on an object that includes several arrays

I have a situation where my props object contains both a user comment array and a userId array. Initially, I only had the user comment array, which allowed me to style each comment individually using the map function. Now that there are two arrays inside m ...

Is there a way to refresh a specific element without having to reload the entire page when the button is clicked

While working on a rock, paper, scissors game in JavaScript, I found it tedious to have to constantly reload the page after each play. To solve this issue, I attempted to add a button that would reset the game for a new round. However, I encountered an err ...

Employ the AJAX call within a fresh popup window

Currently, I have implemented an auto-complete textbox where users can input an actor's name and it works smoothly. There are two buttons on the page - "browse movies" which should display a dynamic dropdown list of movies featuring the actor entered ...

Incorporate a unique identifier $id within the ajax request

Whenever I make changes to my product, I would like the categories to show up in a dropdown menu. Currently, it only displays: -- Select your category -- For instance, if my $current_category_id = 2, I want the dropdown to show the relevant categories. ...

The mousewheel scrolling function does not function properly when the mouse is positioned over the grid in UI-Grid using AngularJS

I've been working on my Angular js grid project, using ui-grid(v3.1.1) to create the table layout. However, I've run into an issue with scrolling when changing the pagination size. When I try to scroll down using the mouse wheel, it doesn't ...

The lifecycle of XMLHTTPRequest objects in JavaScript - from creation to destruction

After years of working with traditional compiled object-oriented languages like C++ and .NET programming, I decided to dip my toes into JavaScript for a new project. As I was experimenting with AJAX, I stumbled upon a perplexing aspect related to how objec ...

When the initial page is loaded, Jquery is successfully loaded. However, when the page is reloaded within an

Upon the initial page load, all content displays correctly. However, when attempting to reload a specific section of the page using Ajax to refresh the content, there seems to be an issue with Jquery not fully loading. Could this be due to the fact that J ...

One AngularJS Controller for each view or individual entity

Recently, I've been pondering the idea of controllers in the MVC pattern, and I have a question I'd like to explore further. When working with AngularJS, should we create a controller per entity (such as Product) or per view given that AngularJS ...

Tips for restricting the information retrieved from an API?

Currently, I am in the process of learning how to use AJAX with vanilla JS. My goal is to implement a limit on the amount of data received from an API, specifically restricting it to 10 objects maximum. The API url that I am working with can be found here ...