Modify and save data in JSON file using Ajax - javascript

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.

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.
And then from the browser, making a 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.

Related

How to receive AJAX data in php [duplicate]

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 2 years ago.
I am trying to build a small form in my website which will use ajax to save the form details to the database with php. I can do it with jquery, since I am a student, I don't want to use any external libraries.
I was able to use ajax "get method" and even manage to create a post method but I have no idea how to receive this data in the php script and process it.
This is the ajax code i used to send json data
subForm.addEventListener('click',()=>{
var forms = {
"name": document.getElementById('name').value,
"phone": document.getElementById('phone').value,
"email": document.getElementById('email').value,
"message": document.getElementById('message').value,
"exe" : true
}
var jString = JSON.stringify(forms);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "recieve.php");
xhttp.setRequestHeader("Content-Type" , "application/json")
xhttp.send(jString);
});
If you've managed to process a GET. You'll manage the POST just in the same way. By peeking in the global variable $_POST['myJson'] in your "recieve.php".
On the client side, you'd need then to stringify like so:
var jString = JSON.stringify({"myJson": forms});
Therefore, on the server side, $_POST['myJson'] will contain the object 'forms', which you constructed on the client side. And if you want to access let's say, the name property value, you do like so:
var nameValue = $_POST['myJson']['name'];

Vuejs and Laravel sending data not working

I have a vue.js script that gets a csv, sends it to my server-side code that breaks it down into an array and sends it back.
Now, I then save that data into a array so the client can edit any data and manipulate ect. Here's the code that dose this:
//hide the upload box, and display new message
$('#upload').slideUp();
$('#message').html('Cheers, Just give us a sec to decode the file...');
//get the file and save it into a new File Object ready to send
var files = $('input#csvUpload').prop('files');
var csv_file = new FormData();
csv_file.append('csv_file', files[0]);
//send to a controller that will read this file and return a JSON string!
this.$http.post('uploadCSV', csv_file, function(data){
//the data is the array returned from the controller,
//this function is just the call back
//now for the rows
this.rows = data.rows;
console.log(this.rows);
//update the message with some new instructions
$('#message').html("Done, now remove the cards you don't want to process");
//and show our table
$('#table').slideDown();
});
Now, that all works fine. Nothing wrong with that. the confusing part is that after the end-user has finish making changes, I need to send that data to a controller that will do things with that data.
But the issue is that when I send the data, laravel can't seem to find it when it gets to the controller.
The code that sends the data:
this.$http.post('makePayment', this.rows, function(data){
this.processed = data;
console.log(data);
});
The Controller Code:
$array = $request->all();
return $array;
exit();
I have a feeling that it is staring at me in the face, but this has really stumped me, and the top picture shows what is in the this.rows object.
Thanks for any help in advance!
Ok, knew it was staring me in the face. So the solution is quite simple. What was happening was that I was sending an array instead of json string...shouldn't matter right? well it does. So the simple solution was before sending the data to my controller, i needed to convert the array to Json format...
So here's the updated code that sends my data:
var newJson = JSON.stringify(this.rows);
this.$http.post('makePayment', newJson, function(data){
this.processed = data;
console.log(data);
});

Accessing and decoding JSON sent from JavaScript to PHP

So I have a form, I took the contents of its inputs, threw them into an array, had it made into a JSON and then sent it to PHP so it can in turn decode and enter it into a database. I know it'd be easier to just use a <form method="POST" action="phpfile.php"> but I can't have this redirecting to another page, especially since my PHP is not embedded into HTML, instead it handles things offsite. Otherwise it'd be simpler to just use $_POST["name"] to get what I need. Nonetheless, this page in particular is supposed to create the user, receive a server response, that the user has been entered into the database and then is given an alert with a button to be redirected to the main page.
So anyway here are the relevant sections of this whole process.
JavaScript:
window.onload = function findSubmitButton() {
var button = document.querySelector(".send_info").addEventListener("click", serverInteraction);
}
function serverInteraction() {
var xmlhttp;
var inputArray;
var finalArray = [];
var JSONArray;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Your browser is not compatible with XMLHTTP");
return false;
}
inputArray = document.querySelectorAll("input[type=text]");
for(var i = 0; i < inputArray.length; i++){
finalArray[i] = inputArray[i].value;
}
console.log(finalArray);
JSONArray = JSON.stringify({finalArray: finalArray});
console.log(JSONArray);
xmlhttp.open("POST","phpFiles/sendUserInfo.php", true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(JSONArray);
}
PHP:
<?php
$finalArray = json_decode($_POST['finalArray']);
var_dump($finalArray);
?>
That var_dump simply returns a null and using echo gives me nothing, except a warning that my array variable isn't initialized through XDebug. I'm not quite sure what I'm doing wrong here, I've been following this just like the tutorials tell you to do it, and isn't generating the array. I've also tried $_POST['JSONArray']without any luck in case that was how it was supposed to go. Also tried file_get_contents('php://input') which sends an empty string as well.
You can't get your data from $_POST if you put JSON in your post body.
see this question Receive JSON POST with PHP. php can't handle application/json properly.
For your var_dump is empty, try this
var_dump(file_get_contents('php://input'));
var_dump(json_decode(file_get_contents('php://input'), true));
you will see your data.
And if you send your data without change it to JSON, you will get wrong data.
eg: your finalArray is ['a','b','c'] and you send it directly.
var_dump(file_get_contents('php://input'));
you will see php got string a,b,c instead of ['a','b','c']
So if you want to use $_POST to receive data, you need to use application/x-www-form-urlencoded. you can use jquery to do it. see http://api.jquery.com/jquery.ajax/
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
it will serialize your js object into x-www-form-urlencoded and php will handle it properly.
use chrome's dev tools, switch to network and see the request payload and response would be helpful for you.
You are bypassing $_POST by sending the the data as "Content-type","application/json" .
The data will instead be set in the body of request and can be retrieved using file_get_contents("php://input")
For further discussion see file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?
Generally there is no need to send your data as json to php

Send javascript var values to php page (not ajax)

I'm using this code, to get values from a dynamic created <table>
$("#finalizar-pedido").click(function(){
var id = [];
var qtde = [];
var makiRecheio = [];
var makiComplemento = [];
var makiCreme = [];
var makiFinalizacao = [];
var makiQtde = [];
var i = 0;
$("tr.row-item").each(function(i){
var Linha = $(this);
id[i] = Linha.find("td.pedido-nome input.id-item").val();
qtde[i] = Linha.find("td.pedido-qtde").text();
});
$("tr.row-temaki").each(function(i){
var Linha = $(this);
makiRecheio[i] = Linha.find("td.pedido-nome input.mak-recheio").val();
makiComplemento[i] = Linha.find("td.pedido-nome input.mak-complemento").val();
makiCreme[i] = Linha.find("td.pedido-nome input.mak-creme").val();
makiFinalizacao[i] = Linha.find("td.pedido-nome input.mak-finalizacao").val();
makiQtde[i] = Linha.find("td.pedido-qtde").text();
});
});
This is working well, i made some tests and the values are OK.
The Question is: How i can send the values to another page.php...
I don't want to show the result in this same page, i need to send the values to another page just like de standard html form does.
I tried to use the jQuery.post() method, but i dont know how to go to another page holding the values that i got from the table.
Sorry for the bad english, Thanks for your attention. :)
post method may have data. For example this code will send a post request to test.php with 2 parameters, name and time:
$.post( "test.php", { name: "John", time: "2pm" } );
Also you can send arrays:
$.post( "test.php", { "id": id , "qtde": qtde , ... } );
EDIT:
If you need to submit the post request and redirect to another page with the post request (No Ajax) you may make a dummy hidden form, put your data in it, make its method post and submit that form. Here you can find how to do it: jQuery post request (not AJAX)
I suggest you set a cookie in javascript, redirect the user to whatever page you like to show the data and then use PHP to read the cookie and process or display the data.
Read on setting javascript cookies on
quirksmode or w3schools
also read on working with cookies in PHP on php.net

How to update data in a json file in AngularJS?

I am using $resource.query() to fetch an JSON array from a JSON file. I can change the data with $save, but the JSON file is not actually updated. Can't find solutions after googling for the entire morning. Not sure if it is possible to update local json file with AngularJS. Any help would be appreciated.
Here is my code.
getData: function(datatype){
var url = "data/" + datatype + ".json";
return $resource(url, {}, {
query: {
method: "GET",
isArray: true
}
});
},
Call the getData() function in another service function:
var post = this.getData("jobs").query(function(){
angular.forEach(staffs, function(staff){
for(var i = 0; i < post.length; i++){
if(post[i].id == jobId){
alert(post[i].name); //Here it shows the original name "names and numbers"
post[i].name = "changed";
post[i].$save();
alert(post[i].name); //Here it shows the new name "changed"
//but the data json file is not changed
continue;
}
}
});
});
jobs.json:
[
{
"id": 554114,
"name": "names and numbers",
"facility_id": 0
},
...
]
The answer above by Chris doesn't seem to be on point. The original question is about Save using angular's $resource. Not whether javascript can write to file.
$resource has "Post" defined already on it. So a $resource.save() called correctly will make the post back call to the server. On the server you still need to write code to preserve the posted data. But the bottom line is $resource allows Post.
shaosh seem to have issues with the $resource.save
post is your resource. Not post(i)
So don't you have to do a
post.$save();
instead of post[i].$save() ?
This Stackoverflow question and answer might be of some use to you: Edit a file using javascript
In short; Javascript typically can't write to a file unless you're making a post back to a server which can then do the update to your json file.
Hope this helps.

Categories

Resources