Performing a JSON POST Request: Steps for sending a POST request with JSON data format

I need to send the following data:

{
  "contactsync":
      { "rev":4,
        "contacts":[
                   { "fields": [
                                {
                                   "value":
                                      {
                                        "givenName":"dfgheeej",
                                        "familyName":"ffftestfff"
                                      },
                                   "type":"name",
                                   "flags":[],
                                   "op":"add"
                                },
                                {
                                   "value":"fffffff",
                                   "type":"nickname",
                                   "flags":[],
                                    "op":"add"
                                },
                                {
                                   "value":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2543434343436543434343430b464a48">[email protected]</a>",
                                   "type":"email",
                                   "flags":[],
                                   "op":"add"
                                }
                            ],
                     "categories":[],
                     "op":"add"
                   }
       }
}

to a specified url (for example: site.com/anything/add?format=json&wssid=t4764.444&wssid=some_value&windowid=&r=776566756).

What is the best way to send the above data to a url using JavaScript? (I want to create an HTML file with a script to accomplish this.)

This process will involve sending data from one server to another, rather than within the same server.

Answer №1

For those situations where your script is on the same server, and the server supports CORS or JSONP, you can utilize ajax. Below is an example using jQuery:

var data = {"contactsync":{"rev":4,"contacts":[{"fields":[{"value":{"givenName":"dfgheeej","familyName":"ffftestfff"},"type":"name","flags":[],"op":"add"},{"value":"fffffff","type":"nickname","flags":[],"op":"add"},{"value":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e78181818181a78181818181c984888a">[email protected]</a>","type":"email","flags":[],"op":"add"}],"categories":[],"op":"add"}]}};
var url = 'site.com/anything/addformat=json&wssid=t4764.444&wssid=some_value&windowid=&r=776566756';

$.post(url, JSON.stringify(data), function(response) {

});

If ajax cannot be used, a PHP proxy can be created. This involves passing the JSON to the remote address and printing the response. Here's an example:

function post($url, $data) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    return curl_exec($ch);
}

function get_raw_post_data() {
    if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
        return $GLOBALS['HTTP_RAW_POST_DATA'];
    } else {
        return file_get_contents('php://input');
    }
}

$url = "site.com/anything/addformat=json&wssid=t4764.444&wssid=some_value&windowid=&r=776566756";

echo post($url, get_raw_post_data());

Instead of the URL of the remote site, use this script on the same server.

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

Displaying a PHP variable on the console through the power of jQuery and AJAX

I'm attempting to display the value of a PHP variable in the browser's console using jQuery and AJAX. I believe that the $.ajax function is the key to achieving this. However, I am unsure about what to assign to the data parameter and what should ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

What is the best way to record data while initiating a process in node.js?

In my latest project, I have implemented a function that spawns a process and requires logging specific information to the console. Here is an example of how this function is structured: function processData(number) { var fileName = settings.file || "de ...

Angular decode UTF8 characters with pascalprecht.translate

I'm facing issues with UTF8 characters when using SanitizeValueStrategy('sanitize'). This is necessary because the client will be editing texts in language files and may include tags like <b> or <i>... I want to rely exclusively ...

Retrieving data from an Ajax POST request URL

I am currently working on a project where I need to extract the URL of a POST request made through AJAX. My router is set up to handle all user requests, including GET and POST methods. However, I am struggling to identify the specific URL being used in th ...

Unable to interact with the page while executing printing functionality in

component: <div class="container" id="customComponent1"> New Content </div> <div class="container" id="customComponent2"> different content </div> ...

Could use some assistance in developing a custom jQuery code

Assistance Needed with jQuery Script Creation <div>Base List</div> <div id="baseSection"> <ul class="selectable"> <li id="a">1</li> <li id="b">2</li> <li id="c">3</li> ...

What is causing the error in this particular stream function?

I created a function that logs the provided arguments to the console when piped into it. function logToConsole() { var stream = new Stream.Transform({objectMode: true}), args = [].slice.call(arguments); stream._transform = function (data, ...

Is the response of the $.ajax function null?

I am facing an issue with my JavaScript code. Here is the snippet: $.ajax({ type: 'GET', url: 'http://133.333.33.33/reporting/summary_table.php?loc_id='+locid+'&loc_type='+loctype+& ...

What causes req.body to be null after using event.preventDefault() in conjunction with fetch api, express, and node.js?

Is there a way to submit a form without causing the page to reload and still retrieve an object from MongoDB using server side scripts? I've tried preventing the default behavior of the form with an event handler to avoid the page refresh, but this ca ...

Dealing with Uncaught Type Errors in the Fixed Data Table

I am attempting to implement a fixed data table using the following code snippet. var MyCompi = React.createClass({ getInitialState: function() { return { rows : [ {"id":1,"first_name":"William","last_name":"Elliott","email":"<a ...

Dealing with Oversized Images in Jcrop: Tips and Tricks

Utilizing Jcrop for cropping images, everything runs smoothly with small images. However, when I attempt to use large images like 2080x2080 or 1600x1600, it takes up the entire screen and cannot be controlled by CSS properties such as width and height in t ...

Incorporate validation features within a jQuery method

I am struggling with some HTML and jQuery code that generates links based on user input. HTML <input type="text" id="text" placeholder="Enter text" autofocus /> <a id="link1" class="btn btn-info" href="#" target="_blank"> Search 1 </a> ...

"Steps to retrieve the button's ID when using the onClick event in Reactjs

Currently, I am working with Reactjs and Nextjs. I am utilizing functional components instead of classes. Within a loop, I have buttons and I am attempting to retrieve the id of the button when clicked using "onClick". Unfortunately, I am encountering th ...

What is the method to identify the key responsible for triggering a textbox input event?

Suppose there is a textbox on the webpage: <input id='Sub' type='text'> To capture each time the input changes, you can use the following code: sub = document.getElementById('Sub'); sub.addEventListener('input&a ...

Prevent AJAX request while in progress?

I've made some adjustments to a jQuery Autocomplete plugin, which now retrieves a JSON object from a MySQL database instead of an array. However, I've noticed that each time I click on the input field, it triggers a new request, even if it&apos ...

How to programmatically clear an input field in Angular using Bootstrap's typeahead feature

My current setup involves utilizing a form to populate a list displayed alongside the form. The markup looks like: <form name="stateForm"> <input type="text" ng-model="model.name" typeahead="state for state in states | filter:$viewValue"> ...

"PHP and MySQL Join Forces: Troubleshooting UNION Query Issues

I am encountering an issue with debugging this query using PHP/MySQL-AJAX. The variable $param is the result of an AJAX call on a form textbox. Essentially, I am attempting to create a dynamic search across three database tables that have different fields, ...

Highlighting text within ReactJS using Rasa NLU entities

Currently, I am working on a React application that retrieves data from the Rasa HTTP API and displays it. My goal is to tag the entities in a sentence. The code functions correctly for single-word entities but encounters issues with two-word entities (onl ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...