What is the best way to transfer POST data using ajax requests?

Currently, I am in the process of developing a script that can effectively receive and parse a JSON array within the POST array. To start off, I am sending some random JSON data to my script so that I have something to work with.

The receiving script is written in PHP (although it could also be implemented in Javascript). At this moment, I am simply serializing the POST array and saving it to a text file to confirm that data is being received. However, what the script is saving appears to be an empty array.

To send the data, I am utilizing an ajax request. The following is what I currently have:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        $(document).ready(function() {  
        var jsondata = JSON.stringify({
            val1:"this",
            val2:"that"
        });  

        $.ajax({
            url: "http://api.mydomain.com/test/index.php",
            method: "POST",        
            data: {json: jsondata},
            contentType: "application/json",
            success: function(data){alert(JSON.stringify(data));},
            error: function(errMsg) {
                alert(JSON.stringify(errMsg));
            }
        });
    });
    </script>
</head>
<body>  
</body>
</html>

I have tested various modifications as well, such as

  • not stringifying jsondata
  • adjusting data to: data: jsondata
  • utilizing type: instead of method:in the request
  • adding datatype: "json" to the request

and several other attempts that are slipping my mind at the current moment. Is there a simple step that I am overlooking? Or perhaps, is there a simpler way to approach this task?

EDIT: I have included my index.php file below:

if (isset($_POST)){
    // This line is commented out because it breaks it.
    //$jspost = json_decode($_POST['json']);
    $jsser = serialize($_POST);
    echo "I'm here.";
    // Write to text file
    $myfile = "response.txt";
    $fh = fopen($myfile, 'w') or die("can't open file");
    $now = date("n/j/y g:i:s a");
    fwrite($fh, $now."\r\n");
    fwrite($fh, "I received a POST.\r\n");
    fwrite($fh, $jsser);
    fwrite($fh, "\r\n\n");
    fclose($fh);
}

Answer №1

JavaScript
Transmit a JSON String

    $(document).ready(function () {
        var dataObject = {
            value1: "this",
            value2: "that"
        };
        dataObject.value3 = 'these';
        dataObject['value4'] = 'those';
        $.ajax({
            type: "POST",
            url: "service.php",
            data: {
                 json: JSON.stringify(dataObject)
            },
            success: function (response) {
                // Handle service.php response
                console.log(response);
            }
        });
    });

service.php
Decode and manipulate the received object

$jsonData = filter_input(INPUT_POST, 'json');
$decodedData = json_decode($jsonData);
$value1 = $decodedData->value1;

var_dump($decodedData, $value1);

Conversely, if you want to transmit a JSON from PHP and decode it in JavaScript

PHP

$responseDataArray = array();
$responseDataArray['key1'] = 'value1';
$responseDataArray['key2'] = 'value2';

echo json_encode($responseDataArray);

JavaScript

success: function (response) {
    var parsedJson = JSON.parse(response);
    console.log(parsedJson['key1']);
}

Answer №2

I found a solution that worked for me by utilizing data variables collected from the element instead of using a form. After trying other methods without success, I came up with the following approach:

<script>
    $(document).ready(function() {  
    var jsonData = new FormData();
    jsonData.append("val1", "this");
    jsonData.append("val2", "that");

    $.ajax({
        url: "http://api.mydomain.com/test/index.php",
        method: "POST",        
        data: jsonData,
        contentType: false,
        cache: false,
        processData: false,
        dataType: 'json',
        success: function(response){alert(JSON.stringify(response));},
        error: function(errorMessage) {
            alert(JSON.stringify(errorMessage));
        }
    });
});
</script>

Answer №3

give this a shot

let jsonInfo = {
        "key1":"here",
        "key2":"there"
    };  

    $.ajax({
        url: "http://api.mywebsite.com/testing/index.php",
        method: "POST",        
        data: jsonInfo,
        contentType: "application/json",
        success: function(result){
           //handle success here
        },
        error: function(errorMessage) {
            //deal with error here
        }
    });

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

What is the best way to integrate a CSS file into Vue.js 2?

At the moment, I'm diving into Vue.js 2 but I've hit a roadblock. Can anyone advise me on how to incorporate external CSS in Vue.js 2? I would greatly appreciate any solutions you can offer. Thank you! ...

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

Include an index within the array

I need to incorporate an index in my array: Here is the loop I am using: for(j=0; j< data.data.tickets.length; j++) { var created_at = data.data.tickets[j].created_at; var tickettitle = data.data.tickets[j].subject; cleartab[requesterid]['t ...

Validation errors are returned by express-validator duplicated

I am working on validating the request object using Express-Validator. Suppose I have two routes: a GET /users/:id route (fetchUserById) and a POST /users route (createUser). this.router = express.Router(); this.router.route('/').post(this.userR ...

Obtain the URL linked to the button that was just clicked

As a newcomer to jQuery, I have a question: For instance, on a webpage with a voting feature, when a button is clicked, a counter is increased by +1. Now, how can the URL of this button be displayed on a website? This way, if the URL is shared with others ...

Turn off the annoying right-click context menu in Firefox

I'm currently working on an HTML 5 game that requires the player to use right click for control. To disable the right click context menu, I have used the following code: <body oncontextmenu="return(false);"> However, I discovered that in Fire ...

Tips on implementing jQuery in a JavaScript file referenced in angular.json

Currently, I am utilizing a JavaScript file that incorporates jQuery within it. In order to employ this JavaScript file, I have included it in the scripts array within the angular.json file. Additionally, I have also included jQuery in the same array befor ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

Deciphering the code within Javascript

So I have extracted the javascript code as a text from an html file, and I am looking to extract the value "CurrencyCode":"EUR" from it. I am particularly interested in capturing the EUR value. Does anyone have recommendations on the best way to do this? S ...

`Troubles arise when attempting to showcase my API data within my React application.`

Currently in the process of developing a React app that pulls random food data from spoonacular.com. I am facing an issue where the title name of the food is not displaying on the page as expected. Additionally, there seems to be a continuous fetch of diff ...

What is the best way to effectively link promise calls that rely on each other?

Here is the code snippet I am currently working with: const request = require('request-promise'); request(validateEmailOptions).then(function(result) { if (result.valid) { request(createUserOptions).then(function (response) { if (re ...

What could be causing media queries to not update values even after being changed through JavaScript?

I have a simple navigation bar on my website, featuring links to different subpages. To enhance the user experience on mobile devices, I added a hamburger menu icon that is displayed on smaller screens. The links in the navigation bar are hidden using CSS ...

Guide on obtaining the Parent hierarchy within the Tree View component

Hello! I am working with a tree object that has parent and nested children, displayed with checkboxes. When a child is checked, I need to retrieve the names of the parent and grandparent up to the entire hierarchy. Below is my JSON data: { [ ...

There was an error when trying to set the data in the DocumentReference function. The data being passed is invalid and contains an unsupported field value of undefined in the

I'm currently attempting to save my automatically generated ID into the documents field. Here's what I've tried: var act = this.afs.collection("activities").add({ activityId: act.id, }) .then(function(docRef) { console.log("Doc ...

"Help needed: My experience with logging into Chrome using Selenium usually results in an automatic logout. Any

Currently, I am delving into the world of Scraping using Python along with Selenium. Desire My goal is to successfully log in to Google and Chrome while utilizing Selenium. However, there are concerns that this activity may be perceived as automation for ...

Repeating data multiple times in ng-repeat directive

Website Development <div ng-app="templeApp" ng-controller="templeList"> <div ng-repeat="temple in temples track by $index" > <h2>{{temple.strTempleName}}</h2> <h4>{{tem ...

The significance of naming in Laravel and the power of AJAX requests

I have encountered a challenge without any documented solution. I am trying to implement multiple AJAX searches on my webpage, all originating from the same database. The only variation among these searches is that each may be required to search only one s ...

Attempting to retrieve JSON data from an online API

I am attempting to retrieve the JSON data from the following URL: However, every time I try, I encounter an error message like this: XMLHttpRequest cannot load http://status.mojang.com/check. Origin null is not allowed by Access-Control-Allow-Origin. A ...

Using InnerHTML in Javascript within the Quasar/VueJS framework is unsupported

I am looking to dynamically create tables based on the items inside the 'counts' array below. The number of tables and their contents can change. Here is my divContainer, where the innerHTML will be appended: <div id="divContainer" style="pa ...

Text that serves as a temporary substitute within the <p> element

I attempted to include a placeholder in the <p> tag, but my approach didn't yield the desired result. I'm looking to have a placeholder within the <p> tag that can be substituted with the input text value. Link to JS fiddle $( ...