S
S
SolidSnake132020-08-23 16:08:17
PHP
SolidSnake13, 2020-08-23 16:08:17

How to write a string to JSON file?

I need to write a string to notes.json file. My php script is not working for some reason. There are no errors, just the line is not added to the file.

App:

import React, {
    Component
} from "react";
import Notes from "./Notes.js";
import $ from "jquery";
 
import {
    withoutIndex
} from "./utils.js"


class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            notes: []
        };
    }
    componentDidMount(){
        this.getNotes();
    }

    
    async getNotes(){
        let notesList = [];
        await $.getJSON('./api/notes.json', function(data) {
            for(let i = 0; i<data.length; i++){
                notesList.push(data[i].text);
            }
           
        });
        await this.setState({
            notes: notesList
        });
    }

    async onNoteCreate(newNodeText){
        this.setState(oldState => {
             return {
                notes: [newNodeText].concat(oldState.notes)
            };
          });
        $.ajax({
            url: './api/saveNote.php',
            method: 'GET',
            async: false,
            data: {
                text: newNodeText
            }
        });
    }

    render() {
        return <Notes
        notes={this.state.notes}
        onDelete={this.onNoteDelete.bind(this)}
        onCreate={this.onNoteCreate.bind(this)}
        />;
    }
}


export default App;


saveNote.php:
<?php

$text = $_POST["text"];
$notes = json_decode(file_get_contents("./api/notes.json"));

array_push($notes, ["text" => $text]);
file_put_contents("./api/notes.json", json_encode( $notes ));


The notes.json file looks like this
[{"text":"lorem ipsum dolor sit amet"}, 
{"text": "aezakmi"}]

I need the "text" key with the value from the input field to be added to the notes.json file when the button is clicked.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Sychev, 2020-08-23
@AlekseySychev

From js send data GET , and receive POST .
And check the paths. It seems to me that in php the file address should be without /api/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question