Transmitting JSON data using a Jquery AJAX request in PHP

I'm facing an issue passing a JSON array from a jQuery AJAX call to a PHP file and attempting to write the received data to a file. This is my code:

var contacts = [{"address":[],"phone":[],"last_name":"abc","email":[{"address":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e89c8d9b9ca89189808787c68b8785">[email protected]</a>","type":null,"selected":true}],"first_name":"Test"}];
    $.ajax({
    url: 'handler.php',
    type: "POST",
    dataType: 'json',
    data:  { 'json': JSON.stringify(contacts) } ,
    success: function(response){
        alert(response);
    }
});

Here's the PHP code I'm using:

$json = $_POST['json'];
    $response = json_decode($json);

$file = fopen('test.txt','w+');
    fwrite($file, $response);
    fclose($file);

echo "Done";

The problem I'm encountering is that the JSON data is not being written into the file, resulting in an empty file.

Answer №1

json_decode takes a JSON string and converts it into either an object or associative array. In this case, parsing is not necessary as you are looking to save the JSON string directly to a file (files store strings, not objects).

$json = $_POST['json'];
file_put_contents('text.txt', $json)

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

Despite the onsubmit returning false, the submit operation still goes through

I seem to have hit a roadblock yet again. My registration form incorporates three JavaScript functions which display the desired output when triggered by an onchange event within my HTML form. These functions generate a Bootstrap alert while the user is co ...

Verification forms and age detection algorithms

Recently, I designed a website dedicated to a particular beer brand which required an age verification page. The PHP script that handles the verification utilizes sessions to store the verification status. This script redirects all visitors to the verifica ...

Is it possible to direct the focus to a specific HTML element when the tab key is pressed?

Seeking a solution to shift focus to a button once the user presses the tab key from the currently selected control, while bypassing other dynamic controls in between. The order of controls is as follows: <dynamic drop down control 1> <dynamic d ...

What could be causing the issue of not being able to access an element visible in AngularJS Videogular?

I am currently working on integrating the videogular-subtitle-plugin with the most recent version of Videogular/AngularJS. As a newcomer to AngularJS, I believe there must be a simple solution that I am overlooking. My main challenge lies within a directi ...

Sending the user to their destination

There is a code in place that triggers when an email is sent to the user, containing a link that leads them to a specific endpoint upon opening. I am experiencing issues with redirection at the end of the function. The redirect does not seem to be working ...

Maintain selected dropdown option after page reload

I attempted to preserve the selected item after triggering a reload with an onchange event, however, I encountered this error in the console: "TypeError: o.nodeName is undefined[Learn More]" Here is my select element : <select onchange="showMov(this. ...

Include certain variables in the JSON response within the Aspect

Our goal is to include some variables in the JSON response, embedded within a specific aspect. We are looking to implement a process similar to this function, but focusing on modifying the response rather than the request. ...

Steps to open a PDF from a Response MemoryStream in a new tab

I'm not entirely sure if this is the right approach. My goal is to display a PDF in a new browser tab. I have a method that generates a MemoryStream and returns it to my ajax call. What is the best procedure for achieving this? Here is my Ajax Call: ...

Tips on excluding a particular attribute during the deserialization of a JSON object

Currently, I am dealing with an established REST interface. Within one of the incoming JSON objects, there is a key called size that I need to exclude when deserializing this particular object. Typically, my approach is to flag unknown properties as error ...

Converting a list into a JSON string using Thymeleaf and the Spring Boot converter

Currently, I am developing a service that generates HTML pages using Thymeleaf templates. In one of these templates, I need an HTML attribute to be represented as a JSON string. The object related to this in my context is an ArrayList<String>. By def ...

When the JQuery event-listener for .show('drop', 500) has completed execution

Currently on the lookout for an event listener that can be used to verify when the animation using .show('drop', 500) has completed. The desired usage would be as follows: if($('#id').show('drop', 500) == complete){ // perfo ...

Do not reveal result of coin flip using Javascript and API

Even though I meticulously copied my professor's parsing process, the display isn't turning out as expected. It seems like something is off in my code. <div class="main"> <p>Heads or tails? click to toss the coin</p> & ...

An error occurred while attempting to save a new entry using the New Entry Form in DataTable, stating that the variable "

I have encountered an issue with a table that includes a bootstrap modal containing a form. After filling out the form and saving the data or closing the modal, I want to refresh the table data. However, I am receiving the following error: TypeError: c i ...

Transferring an organized array to processing

My goal is to transfer an array of integers from a php file called load.php to a JS script, which will then forward it to a Processing file written in JavaScript. In load.php, I define the array and send it using JSON (the array contains a minimum of 40 i ...

Finding keywords in a string present within an array: A step-by-step guide

In my scenario, I am dealing with a string that has a maximum of 200 characters and an array containing 4000 elements. Each element in the array is unique and may consist of up to three words. The main objective is to extract all keywords from the string ...

Restore checkbox to default setting

Is it possible to reset checkboxes in a form back to their initial status using javascript, PHP, jQuery, or any other method? Here is the code I am currently using: <form method="POST> <input type="text" name="name" id="name" value="default val ...

Exploring boundaries with PHP computations

Can PHP compute the limit as n approaches infinity for n^(2/3)? This is what I attempted: $n = INF; echo pow($n, (2/3)); Expected outcome: INF Actual outcome: 0 Any advice on how to correctly compute limits in PHP? UPDATE: I fixed the is ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

Ways to turn off .removeClass()

Encountering an issue with jquery-2.1.4.js. Upon integrating a layerslider into my website, the script modified div classes. Attempted using older versions of the script without success. Currently have classes as follows: <a href="#" class="col-md-3 ...

Transform into dynamic types in Java

Today, I'm facing a challenge with JSON data that consists of an array of objects. Each object in the array contains two properties: type and value. [{ "type": "Boolean", "value": false }, { "type": "String[]", "value": ["one", "two", ...