The successful Ajax POST request does not result in an update to the JSON file

I am facing an issue with adding data to a *.JSON file. Despite receiving a "success" message from Ajax, the file remains unchanged. I have also noticed that when the JSON file is empty, nothing happens at all. Can someone help me find a solution? I'm struggling to locate the source of the problem. Any insight into other possible causes would be greatly appreciated. Thank you.

Here is the ajax code snippet:

 $.ajax({
     type: "POST",
     url: "data/test.json",
     data:  JSON.stringify({ "userName": "1", "password" : "1" }),
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function(data){alert("success");},
     fail: function(errMsg) {alert("fail");
     }
});

Answer №1

One of the most effective solutions involved implementing denver and utilizing PHP code on the server-side.

The following snippet is from the JavaScript file:

deleteNewsItem: function(newsId, callback, scope) {
    var dataPath = this.dataPath;
    $.getJSON(dataPath + '/delete-news.php?id='+newsId, function(rawHeadlines) { 
        var headlines = [];
        $.each(rawHeadlines, function(index, rawHeadline) {
            headlines.push(rawHeadline.id);
        });
    });

    if (callback) {
        callback.call(scope, headlines);
    }
};

This excerpt represents the code within the "delete_news.php" file:

<?php

$deleteId = isset($_GET['id'])?$_GET['id']:false;

if ($deleteId){
    $content = file_get_contents('delete-news.json');
    $json = json_decode($content);

    $newData = array();
    foreach($json as $key=>$id){
        $newData []= (array)$id;
    }
    $newData []= array("id"=>(int)$deleteId);

    $fill_view = json_encode($newData);
    file_put_contents('delete-news.json', ($fill_view));
    echo $fill_view;
} else {
    echo json_encode(array());
}
exit();

?>

Answer №2

Using jQuery alone, saving a JSON file is not within reach. To accomplish this task, you need to incorporate server-side coding.

Answer №3

Your code seems to have an error, remember there is no such thing as failure but rather errors or failures. Give this a try and let me know if it helps. It appears that saving data to a file using JavaScript/jQuery may not be possible due to security reasons. If you want to retrieve or store information, you'll need to do so on the server side. For smaller amounts of data, consider using cookies or localStorage("Key", "Value As Json");

To save data in localStorage, use the following method:

    $.get("data/test.json", null, function (data) {

    localStorage.setItem("data", JSON.stringify(data));
});

Unfortunately, as mentioned earlier, saving directly to a file using JavaScript/jQuery may not be feasible. Instead, utilize localStorage for temporary storage.

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

Use Angular and JavaScript to fetch HTML from a mySQL database and dynamically render it on a webpage

I'm currently utilizing Angular for the front end and Node for the back end. The data is retrieved from a MySql database where it's manually stored in text format with HTML tags. For example: <ul> <li>item1</li> <li> ...

Unable to import the Node.js array in the import() file

I have encountered an issue while building an array path for the Router.group function. The parameter passed to Router.group is added to the end of the this.groupPath array, but when I check the array data within an import(), it appears to be empty. What c ...

How can I apply red border styling only after the first click in MUI React?

I am currently working with MUI Textfields and I have a specific styling requirement. I would like the field to display a red outline only after the first click, if the input is left blank or deleted. Essentially, I want the field to appear normal initiall ...

Search Live Results in Drupal

Exploring Drupal Search Functionality Diving into the world of Drupal, I find myself faced with the task of revamping the search feature on a website. Currently, users must manually input their search term and hit enter to initiate the search. However, the ...

Shift the attention from the text box to the AJAX combobox when the enter key is pressed

I need to make it so that when I press the enter key in a textbox, the focus shifts to an ajax combobox. <script type="text/javascript"> $(document).ready(function () { $("#txtGroupSname").keydown(checkForEnter); function checkF ...

Creating a canvas texture on tube geometry with three.js for optimal display on iPad devices

I have a 3D model of a tube geometry with 18000 coordinates on the production side. To simplify, I am selecting every 9th coordinate to plot 9000 coordinates for building the tube geometry using only the CanvasRenderer. When utilizing vertexColors: THREE. ...

The React-Chartjs chart is displaying without any color rendering

I attempted to create a radar chart using react-chartjs library, but I am facing an issue where the colors are not appearing when it renders. https://i.stack.imgur.com/tjAsW.png What could be causing this problem? I followed a significant portion of the ...

Ensuring the Line Breaks in CSS and JavaScript to Easily Modify the Style

Is there a way to determine when a line will break so I can apply different styles? The design team needs 3 buttons in a grid (3 columns) with specific sizes. They want buttons with content that breaks onto the next line to have a border-radius of 13px, w ...

Converting Nested Classes into Rows in a Table using Spring Framework

Currently, I am utilizing Spring Boot along with several essential dependencies such as Jackson and Hibernate. Within my project, there exists a table named Buildings which consists of columns like Unit, Number, Street, and more. However, instead of direct ...

javascript strange behavior observed with multidimensional array

Looking to create a jquery autocomplete input that responds to the user's input from a previous field. I have a php script that returns a json variable, but I'm having trouble setting up my array correctly afterwards. I've attempted settin ...

Using the information selected from the dropdown menu, the table was refined through an AJAX request

Having a small issue with ajax when working on my project. I have two actions in the view: <body> @Html.Action("SetSearchFilter") @Html.Action("FillTable") </body> The first action is a DropDownList: @Html.LabelFor(m => m.Manager, ...

Modal containing Jquery GalleryView

I am facing an issue with loading galleryView inside a modal. Even though using galleryView on its own works fine, I have been unable to make it work within a modal. Despite looking for solutions in previous posts, I couldn't find anything that fixed ...

How can PHP Ajax be used to determine when a modal should pop up?

Is there a way to automatically display a modal without refreshing the page? Currently, I have a button that submits to home.php and triggers the modal, but it requires a page refresh for the modal to appear. I'm looking for a solution that will eith ...

Div keydown event not being triggered in Vue

I've been struggling to get my event to fire despite following the instructions in the title. @keydown="keyPressed($event)" Although currently it looks like this, I have also attempted setting the tabIndex and adding it on mount as shown be ...

Dividing a single AJAX request containing 5000 rows into separate AJAX calls each returning 100 rows

Currently, I have an ajax function that loads data into a datatable after calling it. Here's the jquery script for the ajax call: <script type="text/javascript"> var oTable; $(document).ready(function() { window.prettyPrint() && pre ...

Retrieving data from a JSON object in Python

I have a python script that handles http post requests from an application that sends the payload as JSON. class S(BaseHTTPRequestHandler): def _set_response(self): self.send_response(200) self.send_header('Content-type', &ap ...

Invoke index functions within a component

I have a widget/component written in Angular 4 within the index.html file. Before and after this angular app, there are various HTML elements due to the nature of it being an additional component for the website. The head section of the index file include ...

Three.js - Troubleshooting: Imported OBJ model displaying partially transparent triangles

Currently, I am encountering an issue with an obj file that was exported from Rhino3D into obj format. In this case, half of the triangles making up a certain part of the model appear to be transparent, despite appearing fine in the 3D editor. var loader ...

Adding new users to the Ajax Chat Script is an essential process that can enhance communication

After downloading the standalone version of the script from , I realized that it lacked a register page for adding new users. Taking matters into my own hands, I decided to create one myself. User information is stored in chat\lib\data\users ...

Error Message for Sequelize Validation Fails to Appear as Expected

I am trying to implement Sequelize model validation in order to validate a form field. When the book or author fields are left empty, I want this message to be displayed: Oops! An error occurred. "Title" is required. "Author" is required. The issue I&ap ...