Answer the question
In order to leave comments, you need to log in
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;
<?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 ));
[{"text":"lorem ipsum dolor sit amet"},
{"text": "aezakmi"}]
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question