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

Is it possible to achieve consistent scrollY height values across various screen sizes?

Looking to apply a class when a certain screen height is reached? Here's my approach: window.onscroll = function() {scrollPost()}; function scrollPost () { var x = window.screen.width; var i = window.scrollY; var a = i / x; animator ...

Unforeseen outcomes of JavaScript when using the let and var keywords

In JavaScript, when using the var keyword to declare a variable, the JS engine assigns a default value of "undefined" at creation stage. console.log(message); // undefined var message = "My message"; However, with the let keyword: console.log(message); ...

Is there a way to automatically override the CSS cursor style?

Issue with SCSS styling on image link I attempted to modify the cursor style from pointer to default, but after saving and reloading my React app, the change did not take effect. I tried writing some code, but it seems that Stack Overflow is indicating an ...

What is the process for assigning a function and its arguments as a callback in programming?

Here is a code snippet for your consideration: $scope.delete=function(){ foo('x',3); }; How can we improve the clarity of this code snippet when the callback function contains only one line that calls another function? It's important ...

What is the simplest method for converting a large JSON array of objects into an object containing the same data under the key "data" in TypeScript?

What is the most efficient method for converting a large JSON array of objects into an object with a key named "data" using TypeScript: Original Format: [ { "label":"testing", "id":1, "children":[ { "label":"Pream ...

MySQL field being updated upon page unload

I'm currently developing a Content Management System (CMS) that allows users to access and organize records within a MySQL database. One of the features I have implemented is a user login system for the CMS. As part of this project, I am working on in ...

Tips on updating an HTML page following the receipt of a CURL request by a PHP script

I am currently developing a unique login system with customized requirements. The HTML form will submit data to a PHP script using AJAX, which will then forward the information to another PHP script for processing through CURL. After some time has passed ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

Forward ReactJS

https://i.stack.imgur.com/r0IAE.pngI'm having trouble implementing a redirect to a submit confirmation page after pressing the submit button on my form. The backend server is set up to send an email upon submission, but adding an href to the button pr ...

input value does not change when the "keyup" event is triggered

I'm encountering an issue with the code below. The code is for a simple To Do app using Javascript. I followed a tutorial step by step, but my app isn't functioning as expected. When I press the enter key, the input value should be added to the l ...

Issue with MaterialUI value prop not updating after dynamic rendering of components when value state changes

As I dynamically generate Material UI form components, I encounter an issue with updating their values. The value prop is assigned to a useState values object, and when I update this object and the state, the value in the object changes correctly but the M ...

Dealing with errors in a sequelize ORM query: Tips and tricks

Currently, I am implementing Sequelize ORM in my Node/Express project using Typescript. Within the database, there is a 'users' table with a unique column for 'email'. As part of my development process, I am creating a signIn API and ...

Ways to dynamically incorporate media queries into an HTML element

Looking to make some elements on a website more flexible with media rules. I want a toolbar to open when clicking an element, allowing me to change CSS styles for specific media rules. Initially thought about using inline style, but it turns out media rul ...

Tips for changing a specific item within an ng-repeat loop in AngularJS

Here is my HTML code: <tr ng-repeat="customer in customers"> <td> {{customer.customer_name}} </td> <td> {{customer.mobile}} </td> </tr> Upon executing this code, I receive 3 <tr>...</tr> blocks as s ...

Pagination displays identical data on each page

When utilizing pagination in my AngularJS application to display search results fetched from an API call, I encountered an issue where the same data set appears on all pages. Here's what I have attempted: Within the Controller $rootScope.currentPag ...

What is the best way to transfer data from an AJAX GET request to a Node.js GET route?

Here is an example of an ajax request being made $.ajax({ url: '/reload', type: 'GET', contentType: "application/json", data: { Name: $("#inputName").val(), Link: $("#inputLink").val() }, succe ...

Understanding how to read a JSON response when the dataType is specifically set to JSONP

I am attempting to send a JSONP request for cross-domain functionality. The issue is that my server does not support JSONP requests and interprets them as regular JSON, responding with an object: {result: 1} Below is the AJAX request I have made: jQuery. ...

Steps for sending a form with jQuery's submit method1. Start

Below is the jquery code that I have written: $(document).ready(function () { $('.bar_dropdown').on('change', function() { console.log("dropdown changed") $('#bar_graph_form_id').submit(function(e ...

The .AppendChild() method does not appear to be working as expected following the completion of

Encountering a peculiar problem here. The scripts run smoothly, but the content doesn't display on screen until I "inspect element" and then close the inspector window or zoom in/out. It's not an issue with the "display" CSS property because even ...

Unable to generate a JSON formatted generic object

Encountering an issue when attempting to return a generic object, resulting in an exception: @RequestMapping(value="/administration/get_stat_all") public @ResponseBody List<StatAllBean<String>> get_stat_all(..) { List<StatAllBean<Stri ...