Transmit an array containing JavaScript objects using POST method

I'm facing an issue where I have an array of objects that need to be sent to a PHP script. Initially, all the data is accessible within the array, but once it reaches the PHP script, a var_dump call returns NULL. I'm struggling to figure out how to properly send this data.

chrome.storage.local.get('object', function (object) {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            alert(xmlhttp.responseText);
        }
    }

    xmlhttp.open("POST", "http://example.com/php.php", true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

    var uid = 2;

    JSON.stringify(object);
    xmlhttp.send("json=" + object + "&uid=" + uid);
});

This is the array in question:

var obj = [
    {
        "key": "val",
        "key2": "val2"
    },
    {
        "key": "val",
        "key2": "val2"
    }
]

obj.push({"key":"val","key2":"val2"});
chrome.storage.local.set({'object':obj});

Answer №1

Here is a quick tip:

Never forget to assign the returned value from JSON.stringify() back to a variable.

This way, you are not wasting the result and can use it later on:

object = JSON.stringify(object);

Additionally, don't overlook encoding your parameters for better security:

xmlhttp.send("json=" + encodeURIComponent(object) + "&uid=" + encodeURIComponent(uid));

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

Unable to verify whether a specific value in the props object is defined

After numerous attempts, I have been unable to solve this issue. As a user of Redux with React, my goal is to utilize the date from the store within my React component. The challenge lies in the fact that the data is not present on the initial render, res ...

My pure JS component is not being recognized by ASP.NET Core when integrated with Vue.js

I decided to try writing a simple component in "ASP.NET Core with Vue.js" template using pure JS instead of Typescript. However, I encountered an issue where my port does not seem to work properly. What could be causing this problem? in ./ClientApp/compon ...

Identify the URL being requested in an AJAX call

Recently, I implemented a function to detect ajax calls. Here is the code snippet: var oldXHR = window.XMLHttpRequest; function newXHR() { var realXHR = new oldXHR(); realXHR.addEventListener("readystatechange", function() { if(realXHR.re ...

Revolutionize iPad user experience with seamless HTML5 video integration

What is the most effective method for dynamically embedding HTML5 video to ensure compatibility with the iPad? (using pure Javascript) I'm having difficulty getting this approach to work: <div id="placeholder"><script type="text/javascript" ...

Why isn't the jQuery function being triggered from an Angular callback?

Here is the code snippet that I am currently working with: $http({method: 'GET', url: 'api/participants/areyouhuman'}) .success(function(data, status, headers, config) { console.log(data); $( ...

PHP array addition techniquesExplanation on how to add arrays

Hello there, I'm fairly new to PHP so your patience is appreciated. I've been trying to add an array using a foreach loop but for some reason, it's not working as expected. if($size > 0) { $resultArray = array(); fo ...

How do I generate a unique key in a MySQL database using PHP and JSON for a field that is duplicated multiple times in a row?

After establishing a connection between two tables where certain fields were repeated twice in a row, I conducted an experiment on phpMyAdmin and obtained new results. However, when running the same experiment on PHP and printing the data as Gausson, the ...

Error: In nodejs express, the reference to 'next' is not properly defined

My challenge lies in managing the input data received from a form using joi validation. I have implemented a middleware called validateCampground to validate the input, but encountered an issue when attempting to define the next function for the subsequent ...

Is there a way to retrieve a key-value map from JsonNode?

There is a JSON file that I have with the following structure: { "data": { "k1": "v1", "k2": "v2", ... } } Is there a way to extract the keys and values from this JSON file as a Map<String, String> using pathpath? This is how I am ...

Unusual size and elements of a character array influenced by a different array in the C programming language

My task involves working with a char array that has letters and blanks, with a maximum length of 100. I needed to create another char array of the same length, where blanks in the original array are replaced by blanks and letters are replaced by '#&ap ...

Unlock the Power of Vue Draggable in Vue.js 3 with These Simple Steps

When attempting to implement Draggable in Vue.js 3, I encountered an error message: VueCompilerError: v-slot can only be used on components or <template> tags. Below is a snippet of my code: <draggable tag="transiton-group" name="s ...

Delete content from an active Web browser using JavaScript

My goal is to eliminate all elements with the "RemoveByMe" class using JavaScript on an open browser. I personally added these elements before. To accomplish this, I am triggering the JavaScript from Python: Selenium manages the browser and sends the scri ...

Retrieve information from JSON but unable to locate the key

var data = [{ "error": false, "date": "09-02-2016", "day": "5", "checkin": "20:29:11", "checkout": null, "break_timein": null, "break_timeout": null, "checkin_remarks": "test", "checkout_remarks": null, "break_time_remarks": null }]; console.log(data[0].c ...

The error message received was: "npm encountered an error with code ENOENT while trying to

About a week ago, I globally installed a local package using the command npm i -g path. Everything was working fine until today when I tried to use npm i -g path again and encountered the following error: npm ERR! code ENOENT npm ERR! syscall rename npm ER ...

Issue: Unable to delete message due to message.$delete not being a valid function

Every time I attempt to execute a DELETE request using the angular-resource service, I consistently encounter the following message within the dev tools: Error: message.$delete is not a function $scope.deleteMessage@file:///Users/me/Desktop/angular/my ...

Experiencing difficulties with AngularJs as onblur event is not functioning properly when the input field is empty

I am currently working on a form that allows users to input data. I am facing an issue where if a user enters a number, deletes it, and moves away from the input field, it will display an error message. However, I want the error message to display only i ...

Integrate CSS and Javascript Plugins into your Ruby on Rails application

I am utilizing an HTML, CSS, and JS template to design the interface for my Rails application. Within this template, there are several plug-ins that are required in both CSS and JS formats. I have stored these plug-ins within the "/assets/plugins/" directo ...

Execute a JavaScript function once the server-side validation has successfully been carried out

I am facing a challenge with a lightbox that contains a small form (2 fields) within an UpdatePanel. My goal is to close this lightbox using JavaScript when the 'Save' button is clicked. The complication arises from the presence of a server-side ...

Changing a 3-dimensional array in Python

Having difficulty working with specific elements in a 3D array in Python. The array example is shown below: [[[ 0.5 0.5 50. ] [ 50.5 50.5 100. ] [ 0.5 100.5 50. ] [ 135. 90. ...

Frequent crashes occurring when using the application's http request functionality

For the past few weeks, I have been encountering frequent errors while fetching data from the server. Sometimes it works fine, and other times it doesn't. The logcat indicates that the error is occurring in the jsonparser file during the execution of ...