Reputation: 3207
First of all here's my .json file:
{
"ids": [1,2],
"names": ["John Richards", "Doe Williams"],
"skills": [ "Senior Software Engineer", "Junior Software Developer"]
}
And here's my ajax call to display each name from the object.
$.ajax({
dataType: "json",
url: "entries.json",
success: function(data){
for (var i = 0; i < data.names.length; i++){
console.log(data.names[i]);
}
}
});
I have a form with 3 fields and a button which I'm using to submit new data. The problem is that I can't modify that json file and submit that data.
$("#add").on("click",function(){
var url = "entries.json";
//Form input
var id = $("#empID").val();
var fullName = $("#empFullName").val();
var prof = $("#empProf").val();
var entry = { "ids":id,
"names":fullName,
"skills":prof
};
....
Ajax call for modification of the json file?!?!
What I mean by modify is to basically insert the id, fullName and prof into the corresponding field of the json and save it with the new values appended. Any insight? I'm stuck. Pulling is fine. How do I push data to the .json file? If I missed to provide anything important please let me know. I'm relatively new working with ajax.
Thanks in advance!
P.S:I've already made the project using a database if anyone's wondering.
Upvotes: 3
Views: 8804
Reputation: 19080
You cannot write to a JSON file using only JavaScript in the browser. But with JavaScript in the browser you can write Document.cookie and also write in the Window.localStorage.
Writing in the localStorage of the browser:
// Form input
var id = $("#empID").val();
var fullName = $("#empFullName").val();
var prof = $("#empProf").val();
var obj = {
"ids": id,
"names": fullName,
"skills": prof
};
localStorage.setItem('myJavaScriptObject', JSON.stringify(obj));
And than to retrieve the object, from the localStorage, you can do:
var obj = JSON.parse(localStorage.getItem('myJavaScriptObject'))
Other thing you can do is to create a service in the backend with a server-side technology like: NodeJS, Ruby on Rails, PHP, JAVA, etc... to handle the writing data in the JSON file.
POST
request that sends the form inputs data to the endpoint of your service, the data can be saved into the JSON file. Hope this can help.
Upvotes: 2