An issue occurred with a malformed JSON string when attempting to pass JSON data from AngularJS

I am facing an issue with passing a JSON string in an ajax request. Here is the code snippet:

    NewOrder =  JSON.stringify (NewOrder);
    alert (NewOrder);

    var req = {
        url: '/cgi-bin/PlaceOrder.pl',
        method: 'POST',
        headers: { 'Content-Type': 'application/json'},
        data: "mydata="+ NewOrder
    };  

    $http(req)
    .success(function (data, status, headers, config) {
        alert ('success');
    })
    .error(function (data, status, headers, config) {
        alert (status);
        alert (data);
        alert ('Error')
    });

The alert (NewOrder) displays:

{"ItemList":[{"ItemName":"Quality Plus Pure Besan 500 GM","Quantity":1,"MRP":"28.00","SellPrice":"25.00"}],"CustomerID":1,"DeliverySlot":2,"PaymentMode":1}

This appears to be a valid JSON string.

However, I encountered an error on the server side while trying to decode the JSON string:

my $decdata = decode_json($cgi->param('mydata'));

The error message received was: malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)")

If anyone could help me understand why this error is occurring, it would be greatly appreciated.

Answer №1

$cgi->param('myData') retrieves the query parameter string 'mydata', however, it seems that this specific data is not being sent in your case.

In your HTTP POST request payload, you are actually sending the JSON data within the body of the request, rather than as a query or form parameter. Therefore, you will require a different method to access and read the contents of the request body in your server-side script.

This can be achieved by using the following code snippet:


my $data = $query->param('POSTDATA');

You can find more information about this approach here:

Additionally, make sure to exclude the "mydata=" segment from your JSON data in the request body, since HTTP request payloads do not include parameter names (they are only used for query and form parameters).

Your final updated code should look something like this:

var req = {
    url: '/cgi-bin/PlaceOrder.pl',
    method: 'POST',
    headers: { 'Content-Type': 'application/json'},
    data: NewOrder
}; 

On the server-side, you can use the following code to decode the JSON data:

my $decdata = decode_json($query->param('POSTDATA'));

Answer №2

It seems like the issue might be connected to this particular problem: Why isn't AngularJs $http.post() sending data?

Typically, I would send data in the following way:

var req = {
    url: '/cgi-bin/PlaceOrder.pl',
    method: 'POST',
    headers: { 'Content-Type': 'application/json'},
    data: {"mydata" : NewOrder}
};  

However, if you are expecting the data to come as request parameters from something like this:

my $decdata = decode_json($cgi->param('mydata'));

In that case, the solution provided in the linked Stack Overflow question may be what you need.

Answer №3

When using Angular's $http.post method, it requires two parameters: the url and the payload.

   var url = '/cgi-bin/PlaceOrder.pl';
   var payLoad = {'myData' :JSON.stringify(NewOrder)}; 

    $http.post(url, payLoad)
    .success(function(data) {
    console.log(success);
    })

On the server side, we retrieve the necessary JSON string from the request parameter and then deserialize it like this:

    $result = $cgi->param('myData');
    my $decdata = decode_json($result);

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

Changing the Color of an Object3D Mesh in Three.js

Seeking advice on how to update the color of a Three.js Object3D. Initially created using MeshStandardMaterial, this object is later retrieved from the scene by its ID. Is it possible to change the color of the Mesh at this stage? If needing to replace th ...

Recognizing a component through various page loads

The title of this question may not be the best, but I hope my explanation clarifies what I'm trying to achieve. It's 4AM, so please forgive any confusion in my message. What I want to do is identify if a user-selected element appears on any page ...

"Utilize the await/async and promise functions to pause and wait for a code to

I am facing an issue with using await/async in conjunction with Promise.all to retrieve arrays and proceed with the code. However, when I introduce a delay in the code, it seems like it's not functioning as expected. Below is my code snippet: asyn ...

Unable to transmit information back to React

Recently stepping into the world of React and Node.js, I have successfully created a function in my Node.js application that executes a Python script using child process. However, I seem to be facing a challenge with my router post method named pythonExecu ...

IntelliJ does not support the use of newlines within Vue.js component templates

While working with Vue.js in IntelliJ IDEA, I encountered a small problem related to defining component templates. The issue is that IntelliJ seems to struggle when the template spans more than one line and attempts to concatenate them together. For examp ...

Combining Java for the back-end and JavaScript for the front-end: a comprehensive guide

Looking for advice on integrating a Java back-end with a JavaScript, HTML 5 front-end in my web application. Any tips on passing content between the two languages? ...

How can one transfer information from a client to a server and complete a form using JavaScript?

Can the information be transferred from a client to the server using just JS, then fill out a form on the server, and finally redirect the client to view a pre-filled form? I am considering utilizing AJAX to send a JSON object, but unsure if it will be s ...

Setting up a React Package by reinstalling a git repository

While immersing myself in learning React JS, I decided to create a git repository containing React components that could be exported and used or installed as a package in a separate React application. I developed some UI Components in a git repository and ...

Using EJS to Render a Function Expression?

Has anyone been able to successfully render a function call in express using EJS? Here's what I've tried so far: res.render("page", { test: test() }); Can someone confirm if this is possible, or provide guidance on how to call a function fr ...

What is the best way to keep an image centered in the nav-bar as it decreases in size?

As I work on building a website using a template (https://github.com/learning-zone/web-templates/tree/master/victory-school-free-html5-bootstrap-template), I encountered an issue with the navigation bar. The original design appears like this: Before shrin ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

What are the necessary requirements for utilizing JSON Diff in a document or project?

When working on web projects that utilize API features, JSON Diff becomes a key tool. But what about projects that don't incorporate API functionalities? Is there a specific set of criteria for JSON Diff to work effectively in such cases? ...

Is there a simpler method to examine scope in Angular when debugging?

During my Angular sessions, I often catch myself repeatedly performing the following steps: Choosing an HTML element in the "elements" tab of dev tools Executing scope = angular.element($0).scope() Is there a simpler way to accomplish this task? Maybe a ...

Developing New Arrays from JSON Responses using AngularJS

I have a function linked to the factory for controlling: fac.GetDailyCountersList = function () { return $http.get('/Data/GetDailyCountersList') } Within the controller, this is how the function is invoked: $scope.DailyCounters = null; Dai ...

Managing null values in a map using Jackson

HashMap testMap = new HashMap(); testMap.put("Key1", "Value1"); testMap.put("Key2", null); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enableDefaultTyping(); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL,JsonTyp ...

Is there a way to retrieve JSON data from a specific URL and assign it to a constant variable in a React application?

I am exploring react-table and still getting the hang of using react. Currently, in the provided code snippet, a local JSON file (MOCK_DATA.json) is being passed into the const data. I want to swap out the local JSON with data fetched from a URL. How can ...

Apply SetTimeout exclusively for desktop devices

A website I'm working on has a background video from YouTube using YTPlayer. To enhance the user experience, I have implemented a CSS spinner that displays while the page is loading. However, I noticed that the spinner disappears before the video fini ...

Incorporate extra padding for raised text on canvas

I have a project in progress where I am working on implementing live text engraving on a bracelet using a canvas overlay. Here is the link to my code snippet: var first = true; startIt(); function startIt() { const canvasDiv = document.getElement ...

Creating dynamic <a> tags using JavaScript

My current view includes a div tag with 2 links - one for displaying the page in English and another for Arabic. I want to modify it so that if the page is already in English, only the Arabic <a> tag will show, and vice versa if the page is in Arabic ...

Save this page for later by using JavaScript to create a

Does anyone have a solution as to why window.location.href does not save the current webpage URL as a bookmark? Thank you ...