Handling Ajax post requests with Symfony

View in another language:
Handling Ajax post requests with Symfony
Categories
Technologies
Author

Miro Lehtonen

Project Manager & Lead Developer
Date

Handling PHP forms and accessing the data that follows user input is the bread and butter of learning PHP. Symfony adds a Model-View-Controller (MVC) architecture with reusable components, a well-organized structure, and best practices to the development process, making it a typical environment for handling user input. Ajax, the technology that enables dynamic content on web pages, allows users to complete actions on the page without page transitions or reloads by processing data in the background, sending requests to the server and updating the page view according to the responses. Also known as asynchronous Javascript, Ajax functionality is often used instead of PHP forms to send user input data to the server.

Challenge: Adding items to shopping cart

Let’s assume we want to add items to the shopping cart. Resulting from the user input, we have a set of items with an id and quantity. The (id, quantity) pairs are the data that we send asynchronously to the server. Our choice of technology is a commonly used Javascript library called axios which comes with an interface for sending post requests to a given URL with the data in the request body. The reason behind that choice is that it’s easy to integrate into a VueJS or ReactJS environment.

The function call

axios.post(url, payload)
sends an asynchronous HTTP POST request to the route of the url variable with the data stored in the payload variable.

The Symfony controller handling the route is called addItems.

use Symfony\Component\HttpFoundation\Request;
public function addItems (Request $request) {

    // process data here, for example:
    $quantity = $request->request->get('quantity');

}

Normally, when processing PHP form data, the form field values are accessible through the $_POST variable which is mapped to the request. When we post an HTML form, the data is accessible as expected, but now that we make an Ajax request with axios, the request is empty. Did our data disappear? Why? Let’s compare HTML form submissions and axios ajax requests.

Cause: content type differences

Posting an HTML form sends the payload as a url-encoded string by default. One of the request headers indicates the content type.

Content-Type: application/x-www-form-urlencoded

Axios.post serializes the payload into a JSON string by default which also shows in the content type header.

Content-Type: application/json;

Because the JSON format allows for the storage of data with an arbitrary depth, it cannot be safely mapped to the Parameter bag PHP structure of $request->request. So we have to adjust our code to work with axios.post requests.

Code that solves the problem

Solution #1

Send the payload as a JSON string and modify the PHP code. Accessing the raw request body in the controller happens through getContent(). This raw JSON data has to be decoded into a PHP object through which the field values are accessible as properties.

$postData = json_decode($request->getContent());
$quantity = $postData->quantity;

Solution #2

Send the payload as a url-encoded string by modifying the Javascript code. We create a URLSearchParams object for the payload because axios does not automatically convert it into a JSON string. In a browser environment, we may also use the FormData interface instead of URLSearchParams.

const params = new URLSearchParams();
params.append('id',1234567890);
params.append('quantity',4);

Then post the data. For example:

const submitData = () => {
  try {
    return axios.post(url,params);
  } catch (error) {
    console.log(error);
  }
}
response = submitData()
  .then(({data}) => {
    console.log(data);
  });

Then the post data is normally accessible in the controller, for example :

$quantity = $request->request->get('quantity');

Other solutions

Whenever the first idea feels too hard or time-consuming to implement, we are inclined to look for an alternative solution. So how about sending an HTTP GET request instead? Packing the few parameters in the URL should be ok, right? It’s easy, it works, so why not use axios.get? Well here’s why not.

Something being easy or quick to implement is not relevant when we choose between HTTP post and get requests. Instead, we should ask if we can repeat the action without consequences, a feature also known as idempotence. For example, adding items to the shopping cart should always have consequences which show as data updates on the server. Each repeat of the action should add more items to the cart. So what if we implement this with a “get” request? The first time probably works just fine but the second time – we may get an “items successfully added” response message cached by the browser with no request ever reaching the server. Besides being a clearly unwanted consequence, it also explains why a get request cannot replace a post request. If we really need an alternative solution, we can use a different Javascript library as an HTTP client. For example, jQuery comes with full support for Ajax.

Miro Lehtonen · Project Manager & Lead Developer

Academic scholar with a research focus on information retrieval and web technology, educational and team leader experience at several institutions in Finland, Thailand, and Australia, Miro is currently also an adjunct lecturer at the Mae Fah Luang University, Thailand. He has been applying his academic expertise in a number of different projects at Outsourcify as the IT architect of web portals.

Have a project in mind?
Let's start your project today

Contact Us
Have a project in mind?
Let's start your project today

Related blog articles

Technologies

A ResTech MVP in 1 Month

September 19, 2025

A ResTech MVP in 1 Month
A ResTech MVP in 1 Month
Technologies

Recent Projects at Outsourcify: A Behind-the-Scenes Series

June 2, 2025

Recent Projects at Outsourcify: A Behind-the-Scenes Series
Recent Projects at Outsourcify: A Behind-the-Scenes Series
Technologies

AI Is Reshaping Web Development — But Not in the Way People Think

March 18, 2026

AI Is Reshaping Web Development — But Not in the Way People Think
AI Is Reshaping Web Development — But Not in the Way People Think
Technologies

Will AI Replace Developers? A Reality Check From the Field

March 11, 2026

Will AI Replace Developers? A Reality Check From the Field
Will AI Replace Developers? A Reality Check From the Field
Technologies

Teaching AI and Software Development at Chulalongkorn University: A Two-Hour Conversation That Went Well Beyond the Slides

February 23, 2026

Teaching AI and Software Development at Chulalongkorn University: A Two-Hour Conversation That Went Well Beyond the Slides
Teaching AI and Software Development at Chulalongkorn University: A Two-Hour Conversation That Went Well Beyond the Slides
Technologies

Skipping Figma Doesn’t Mean Skipping Design

February 18, 2026

Skipping Figma Doesn’t Mean Skipping Design
Skipping Figma Doesn’t Mean Skipping Design
Technologies

Vibe Coding Rescue: From MVP to Scalable Platform

February 15, 2026

Vibe Coding Rescue: From MVP to Scalable Platform
Vibe Coding Rescue: From MVP to Scalable Platform
Technologies

Building AcadAsia: A Technical Deep Dive into Thailand’s International School Advisory Platform

February 11, 2026

Building AcadAsia: A Technical Deep Dive into Thailand’s International School Advisory Platform
Building AcadAsia: A Technical Deep Dive into Thailand’s International School Advisory Platform
Technologies

How to Choose the Right WordPress Agency: Beyond the Sales Pitch

January 20, 2026

How to Choose the Right WordPress Agency: Beyond the Sales Pitch
How to Choose the Right WordPress Agency: Beyond the Sales Pitch
Technologies

Astro Joins Cloudflare: The New Standard for High-Performance Web Architecture

December 14, 2025

Astro Joins Cloudflare: The New Standard for High-Performance Web Architecture
Astro Joins Cloudflare: The New Standard for High-Performance Web Architecture
Technologies

WooCommerce vs Shopify: Which Platform Fits Your Project?

November 21, 2025

WooCommerce vs Shopify: Which Platform Fits Your Project?
WooCommerce vs Shopify: Which Platform Fits Your Project?
Resources

Building a B2B Product: Laying the Right Foundations from Day One

September 29, 2025

Building a B2B Product: Laying the Right Foundations from Day One
Building a B2B Product: Laying the Right Foundations from Day One
Technologies

Our Headless WordPress Journey with Astro.js and Vue.js

September 2, 2025

Our Headless WordPress Journey with Astro.js and Vue.js
Our Headless WordPress Journey with Astro.js and Vue.js
Resources

Why Taking Over a Development Project Is Always a Challenge

August 11, 2025

Why Taking Over a Development Project Is Always a Challenge
Why Taking Over a Development Project Is Always a Challenge
Technologies

From Vibe-Coded Prototype to Production-Ready: How Client Mockups Accelerate Our Work

August 5, 2025

From Vibe-Coded Prototype to Production-Ready: How Client Mockups Accelerate Our Work
From Vibe-Coded Prototype to Production-Ready: How Client Mockups Accelerate Our Work
Technologies

Outsourcify’s 2025 Tech Stack Driving Digital Excellence

August 4, 2025

Outsourcify’s 2025 Tech Stack Driving Digital Excellence
Outsourcify’s 2025 Tech Stack Driving Digital Excellence
Outsourcify Story

What Our Clients Say About Us: A Look at Outsourcify’s Google Reviews

July 30, 2025

What Our Clients Say About Us: A Look at Outsourcify’s Google Reviews
What Our Clients Say About Us: A Look at Outsourcify’s Google Reviews
Outsourcify Story

The Agency Developer: Beyond the Code

July 14, 2025

The Agency Developer: Beyond the Code
The Agency Developer: Beyond the Code
Resources

A Website Is Non-Negotiable in 2025 — But Its Content May Be Training AI

July 9, 2025

A Website Is Non-Negotiable in 2025 — But Its Content May Be Training AI
A Website Is Non-Negotiable in 2025 — But Its Content May Be Training AI
Resources

SaaS Tools Annual Cost Comparison for a 35-User Team – and What You Can Learn from Our Journey

June 11, 2025

SaaS Tools Annual Cost Comparison for a 35-User Team – and What You Can Learn from Our Journey
SaaS Tools Annual Cost Comparison for a 35-User Team – and What You Can Learn from Our Journey
Resources

A Guide to Thailand’s Online Payment Gateways

May 4, 2025

A Guide to Thailand’s Online Payment Gateways
A Guide to Thailand’s Online Payment Gateways
Technologies

10 Programming Practices Worth Rethinking

April 29, 2025

10 Programming Practices Worth Rethinking
10 Programming Practices Worth Rethinking
Outsourcify Story

The Outsourcify Story #1: Lessons from a decade in Web Development

March 23, 2025

The Outsourcify Story #1: Lessons from a decade in Web Development
The Outsourcify Story #1: Lessons from a decade in Web Development
Technologies

Outsourcify partners with Sisense: the Power of Business Intelligence

February 16, 2025

Outsourcify partners with Sisense: the Power of Business Intelligence
Outsourcify partners with Sisense: the Power of Business Intelligence
Technologies

The 8 Archetypes of Software Engineers Every Team Needs (And How to Harness Their Superpowers)

February 6, 2025

The 8 Archetypes of Software Engineers Every Team Needs (And How to Harness Their Superpowers)
The 8 Archetypes of Software Engineers Every Team Needs (And How to Harness Their Superpowers)
Outsourcify Website

Eco-friendly and Accessible Websites: Building a Sustainable Digital Future

December 10, 2024

Eco-friendly and Accessible Websites: Building a Sustainable Digital Future
Eco-friendly and Accessible Websites: Building a Sustainable Digital Future
Technologies

The impact of API-centric approaches on software development

November 27, 2024

The impact of API-centric approaches on software development
The impact of API-centric approaches on software development
Technologies

How to know you can trust a web agency: A practical guide

November 15, 2024

How to know you can trust a web agency: A practical guide
How to know you can trust a web agency: A practical guide
Technologies

Who’s watching? A guide to privacy on websites and protecting your data

November 14, 2024

Who’s watching? A guide to privacy on websites and protecting your data
Who’s watching? A guide to privacy on websites and protecting your data
Technologies

Understanding the differences between MVP and MMP for smarter product development

November 13, 2024

Understanding the differences between MVP and MMP for smarter product development
Understanding the differences between MVP and MMP for smarter product development
Technologies

The top 3 strategic pitfalls that can derail a tech startup

November 8, 2024

The top 3 strategic pitfalls that can derail a tech startup
The top 3 strategic pitfalls that can derail a tech startup
Technologies

How to avoid AI project failures: lessons from automation

November 7, 2024

How to avoid AI project failures: lessons from automation
How to avoid AI project failures: lessons from automation
Technologies

The top 3 pitfalls facing CTOs and how to overcome them

October 31, 2024

The top 3 pitfalls facing CTOs and how to overcome them
The top 3 pitfalls facing CTOs and how to overcome them
Technologies

How do we extract the needs of a startup in the context of a Define Scope – Requirements Workshop?

October 29, 2024

How do we extract the needs of a startup in the context of a Define Scope – Requirements Workshop?
How do we extract the needs of a startup in the context of a Define Scope – Requirements Workshop?
Technologies

The vital role of a product owner in your web project

October 25, 2024

The vital role of a product owner in your web project
The vital role of a product owner in your web project
Technologies

How to choose a web agency: Top platforms to help you find a reliable partner

October 15, 2024

How to choose a web agency: Top platforms to help you find a reliable partner
How to choose a web agency: Top platforms to help you find a reliable partner
Technologies

The breadth of expertise required for Web Development

October 9, 2024

The breadth of expertise required for Web Development
The breadth of expertise required for Web Development
Technologies

Running daily, a day early: cron jobs for everyone

October 7, 2024

Running daily, a day early: cron jobs for everyone
Running daily, a day early: cron jobs for everyone
Company Activities

Behind the scenes: Triple baby party & reflecting on our company’s sociology

October 4, 2024

Behind the scenes: Triple baby party & reflecting on our company’s sociology
Behind the scenes: Triple baby party & reflecting on our company’s sociology
Technologies

Caching: Our number one suspect

August 9, 2024

Caching: Our number one suspect
Caching: Our number one suspect
Technologies

What is a database and how do you choose one for your web application project?

June 18, 2024

What is a database and how do you choose one for your web application project?
What is a database and how do you choose one for your web application project?
Technologies

Outsourcify’s expertise with the Astro framework

June 11, 2024

Outsourcify’s expertise with the Astro framework
Outsourcify’s expertise with the Astro framework
Technologies

What is an API and how does Outsourcify use them?

May 22, 2024

What is an API and how does Outsourcify use them?
What is an API and how does Outsourcify use them?
Technologies

Which LLMs are we using to facilitate the development at Outsourcify?

May 10, 2024

Which LLMs are we using to facilitate the development at Outsourcify?
Which LLMs are we using to facilitate the development at Outsourcify?
Technologies

Integrating an AI service for Real Estate

January 19, 2024

Integrating an AI service for Real Estate
Integrating an AI service for Real Estate
Technologies

Vue 3 vs React: The Quiet Revolution in Front-End Development

April 7, 2025

Vue 3 vs React: The Quiet Revolution in Front-End Development
Vue 3 vs React: The Quiet Revolution in Front-End Development
Technologies

The main reasons we use Symfony for web application developments

April 1, 2018

The main reasons we use Symfony for web application developments
The main reasons we use Symfony for web application developments