Replace data into json file using PHP and javascript - javascript

I have a json file (file1.json) which contain json data.
I would like to replace these data by new datas (newDataToStore).
I don't know how to do it using a php file (save.php file below) ?
Content of file1.json :
[
{
"key" : "test1",
"desc": "desc1"
},
{
"key" : "test2",
"desc": "desc2"
},
]
New json to write into json1.json file :
var newDataToStore =
[
{
"key" : "test2",
"desc": "desc2"
},
{
"key" : "test3",
"desc": "desc3"
},
];
JS
this.save = function (newDataToStore) {
jQuery.ajax({
type : "POST",
dataType : "json",
url : 'save.php',
data : newDataToStore,
success : function() {
console.log("SUCCESS");
},
error : function() {
console.log("ERROR");
}
});
}

Another approach:
You'll need to stringify the JS-Object before sending it to the server:
this.save = function (newDataToStore) {
jQuery.ajax({
type : "POST",
dataType : "json",
url : 'save.php',
data : {'json': JSON.stringify(newDataToStore)},
success : function() {
console.log("SUCCESS");
},
error : function() {
console.log("ERROR");
}
});
}
On the serverside your script should do something like (as Mohammad Alabed pointed out):
file_put_contents('/path/to/file1.json', $_POST['json']);
BUT, beware! Users could write arbitrary data to the file. You should always validate user input on the server side. (Maybe using a json schema)

in php file the json data will be in the post global variable because you use post in your ajax
so all what you need is file_put_contents()
save.php
file_put_contents('file1.json', json_encode($_POST));
by using this function you will write a new json string to your json file (old content will be deleted)

in your save.php file
use json_decode()
it will decode your json datas passed from your ajax file

Related

How do I bind object property and send the data via ajax?

I'm struggling with sending a data which contains object as a member property.
This is the domain class.
public class Timeline extends Post{
String picture;
User user;
int like;
...
(getters and setters)
}
And I've got the JSON data with this code already so I could get the data from 'obj' variable.
var obj;
$.ajax({
method: "GET",
dataType: "json",
url: serverRoot + "/json/auth/loginUser",
async: false
})
.done(function(data) {
obj = data;
});
And the returned data looks like this.
"user" : {
"userNo" : 1,
"name" : "user01",
...
}
The next JSON data is the data I'd like to send to a server.
{
"no" : 23,
"content" : "hihi",
"createdData" : "2018-07-22",
"picture" : null,
"user" : {
"userNo" : 1,
"name" : "user01",
... **obj JSON data I got above**
}
}
And this is the codes to send to a server.
(Here is the thing I've been stuck)
$("#sh-tl-post-btn").click(() => {
$.ajax({
type: 'POST',
url: '../../../json/timeline/add',
data: {
picture: $('#sh_tl_upload').val(),
content: $('#sh_tl_post_write').val(),
**user: [{"userNo":obj.userNo}]**
},
}).done(function() {
console.log("inserted.");
location.href = "timeline.html"
});
});
The Mapper file looks like this.
<insert id="insert" parameterType="Timeline">
<choose>
<when test="picture != ''">
insert into TML(tmlno, uno, tmlpath)
values(#{no}, #{userNo}, #{picture})
</when>
<otherwise>
insert into TML(tmlno, uno)
values(#{no}, #{userNo})
</otherwise>
</choose>
</insert>
I've been searching what to write on here instead of
user: [{"userNo":obj.userNo}] , this...
I've been trying
user : {"userNo" : obj.userNo}
user.userNo : obj.userNo
user.[0].userNo : obj.userNo
...
but the console keeps saying
[Request processing failed; nested exception is
org.springframework.beans.InvalidPropertyException:.....
this kind of errors.
Is there anyone could help me how to bind the nested object's property via ajax
JSON data? Thanks in advance.

How to load a text file inside a JSON object within a Javascript function

I have an autocomplete function :-
$(document).ready(function () {
$('input.autocomplete').autocomplete({
data: {
The data JSON object will be responsible for giving the associated autocomplete values, the JSON key will be the autocomplete suggestions, and the JSON value will be null.
I don't want to manually enter values inside this JSON data like:-
data:{
"Chocolate": null,
"Cake": null,
"Icecream": null,
"Pudding": null }
Instead, I want to fetch the JSON values from a text file, which will have these contents, so that I can just load the text file for this data JSON object, instead of having to manually enter it.
So, the list.txt file will have:-
"Chocolate": null,
"Cake": null,
"Icecream": null,
"Pudding": null,
"Cream:null
And I want to call this list.txt file inside JSON object data, something like:-
data: {
$.get('list.txt') }
How can I achieve this?
Try the below code.
Read data from text file with ajax call and convert it into json object.
It will work, but slight modification is needed with your text file as follows.
{
"Chocolate": "null",
"Cake": "null",
"Icecream": "null",
"Cream":"null"
}
And your code will be as follows.
$(document).ready(function() {
$.ajax({
url : "list.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
var jsonData = JSON.parse(data);
}
});
});
If you don't want to modify the existing text file the below code will work.
$(document).ready(function() {
$.ajax({
url : "list.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
var jsonData = JSON.parse("{"+data+"}");
$('input.autocomplete').autocomplete({
data:jsonData
}); //to initialize autocomplete
}
});
});

Value showing undefined when trying to output data returned as json from server

I am new to Yii2 framework and PHP.I used Mongo DB as the backend database.I fetched a document from a collection and returned the data as Json from the controller.The data returned back is given below.
{
"55b08c383e1a36233fdbdc06": {
"_id": { "$id": "55b08c383e1a36233fdbdc06" },
"address": [ "abcdgt", "zxcv" ],
"age": "23",
"email": [ "qwert#gmail.com","abcd#mail.com" ],
"location": "kollam",
"name": "ajiths",
"phoneno": [ "9522585456", "7875642256" ] ,
"sex": "male"
}
}
But I am getting 'Undefined' when trying to alert result.name in Javascript code.The code at the front end is given below.
function loadClient(id){
url = "<?= Yii::getAlias('#serverpathweb')?>/client/showclient?id="+id;
$.ajax({
url: url ,
method: "GET",
success: function(result){
alert(result.name);
}
});
}
The code at the controller end is given below.
public function actionShowclient($id) {
$clientdetail = Yii::$app->mongodb->getCollection('client');
$result = $clientdetail->find(["_id" =>$id]);
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $result;
}
Can anyone tell me how to get the value result.name.
your getting JSON result with id as key so access ur JSON data like this
first get the key of ur JSON using Object.keys
next using key print the values you need
var id=Object.keys(result)[0]; //it will print your JSON key i.e. "55b08c383e1a36233fdbdc06"
alert(result[id]['name']); // it will print the name
Note if you are getting multiple user details please let me know
Your "result" object is probably a String because you're not telling jQuery otherwise. Trying adding the option dataType:json to your request as in:
$.ajax({ url: url, method: 'GET', dataType: 'json', etc...
Edit: It also looks like there's a simple bug in your code. You need to access your property where it's nested in the resulting object:
result[id].name

Send datas to JSON with jquery

i'm coding a script that send datas (nickname & score) to a JSON file in Jquery but i'm having trouble to make it work.
Here is my Jquery :
function addInfos() {
var nicknameSubmit = $(".nickname").val();
var scoreSubmit = $(".score").val();
var newScore = {
Nickname : nicknameSubmit,
Score : scoreSubmit
};
$.ajax({
url: './js/scores.json',
type: "POST",
data: JSON.stringify(newScore),
contentType: "application/json",
complete: console.log(nicknameSubmit + " " + scoreSubmit )
});
};
$(".submit").click(function(){
addInfos();
});
I used Jquery.post for this ( http://api.jquery.com/jquery.post/ )
And here is my JSON file :
[{
"Nickname" : "Alex",
"Score" : "1000"
},
{
"Nickname" : "Tom",
"Score" : "0"
}]
The script find the JSON file, it show me the correct values in the console but it doesn't add the values to the JSON file...
Can anyone know where i'm wrong ? Do i do the request properly ?
Thanks in advance,
remid
Unless your server is webdav compatible, you can't save a file on it via HTTP.
You need to create a server side script (perhaps PHP) that reads "POSTed"values and add them in your JSON file.

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

Categories