How to update data in a json file in AngularJS? - javascript

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.

Related

Retrieving JSON data using the value of a variable

Hello. I'm currently working on a small project and have the following issue that I can't seem to solve alone. I have attempted to search for a solution, with no luck. Admittedly, it doesn't help that I'm fairly new at JavaScript/jQuery, so I'm unsure of the "correct" search terms!
I have a JSON file that contains the following code:
var draft = {
"title": "Title",
"subtitle": "Subtitle",
"image": "/image.jpeg",
}
I'm then retrieving the JSON data with the following line:
draft["title"];
Based upon what the application is required to achieve - is there a way to access the JSON data using the value of a variable in place of "draft"? I have an AJAX function that is pulling the file name and extension of the JSON file, and then the following line of code that is refining the file name down to one word by removing the slashes, numbers, hyphens, and file extension:
var fileNameRefined = fileName.replace("/", "").replace(/\d+|-/g, "").replace(".json", "");
As a result, the "fileNameRefined" variable will contain the value "draft". This outputs to the console as expected. That said, it won't work with the JSON. I was hoping that the following lines of code would work in the exact same way:
draft["title"];
fileNameRefined["title"]; // var fileNameRefined = draft
Unfortunately, the resulting data is returned as "undefined". I'm assuming the application is treating the name of the variable as a string as opposed to passing the variable's value? I'm not sure.
Does anybody have a solution to this? Any help would be greatly appreciated.
Thanks, all.
Could be done, SHOULDN'T be done.
Use JSON (This is JS object you presented) and its API. Here is example for jQuery, there are similar examples for other libs/frameworks.
I would always go with fw or lib here for a clear Ajax API over writing it yourself in vanilla.
Here is get JSON example in fiddle (not written by me):
json get fiddle
function getSuccessOutput() {
$.ajax({
url:'/echo/js/?js=hello%20world!',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
},
});
return false;
}
As for JSON api you will be interested in parsing the response using JSON.parse()
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

How to retrieve JSON data located in a different file

I have 6 json files in the same directory as my index.htm. Each json structure has saved game data in it. I want to let the user choose a file and load its associated json data structure. How can I go about retrieving that data?
I tried using
var myjson = new Object();
$.getJSON("myJSON.json", function(json) {
myjson = JSON.stringify(json);
console.log(myjson);
});
This gives me an XMLHttpRequest error (cross-origin request not supported).
Your execution is fine -- though like the comments on your post suggest, you need to change the protocol you're using. Really just load the HTML page using http://127.0.0.1/mypage.html instead of file://home/website/mypage.html and you can likely keep your javascript the same.
Aside from this, you might want to consider the data in your myJSON.json file. I noticed if the JSON data contains function definitions then it will cause $.ajax() or in this case $.getJSON() to throw a parse error.
So this will not work
{
"json" : function () {
alert("HI");
},
"hello" : 432
}
But this will work
{
"json" : "5",
"hello" : 432
}

Phonegap - Send array from mvc controller to Javascript using Ajax

I'm using phonegap and I'm trying to send an array encoded as json from a controller to view.
In my controller (server side):
$users = Model_Users::find(1);
$a=$users->to_array();
return json_encode($a);
In my view (into smartphone application using phonegap):
$(document).ready(function() {
$.ajax({
url: 'my/url...',
method: 'POST',
data: {
},
success: function(data) {
alert(data);
}
});
});
This working fine, infact in the view I get this alert:
data = {"name":"Jhon","surname":"Larry","age":"25"}
This work because the result of the query is only one row.
Instead when I try to get more than one query result, example:
$users = Model_Users::find('all');
$a=array();
foreach ($users as $user){
array_push($a,$user->to_array());
}
return json_encode($a);
In this case an empty response comes up, in fact I get this alert:
data = []
What is the problem?
Thanks in advance
I will try to build an answer with some tips based on what we already know thanks to the comments.
First of all now we are sure that the JSON is valid (jsonlint.com for example).
So,now, we are completely sure that the problem resides on the PHP / server-side.
My solutions:
Pay attention to not echo/return something before the value you need;
Change return with echo;
Add an exit; statement after the echoed value to be sure that no other characters will be included in the server answer;
Not exactly needed, but you can even think to set the header('Content-Type: application/json');
Debug looking at the console and using console.log instead of alert() (there are a lot of threads explaining the difference
Hope this will help!

Django/JS: json.dumps and parse.json

I'm no programmer, so I can't go to source code of Django or Jquery and figure out how and why these function don't return what I want from them, because I simply wouldn't understand the source code.
I do one little project for myself and here's my confusion about json part:
here's my django/python function:
def searchPatients(request):
patients = Patients.objects.filter(KeyName__icontains=request.POST.get('KeyName'))
response = []
for patient in patients:
tmpvar = {}
tmpvar = { 'Name1':patient.Name1, 'Name2':patient.Name2 }
response.append(tmpvar)
return HttpResponse(json.dumps(response), content_type="application/json")
I checked in shell, json.dumps(response) gave me this:
'[{"Name2": "TestName2", "Name1": "TestName1"}, {"Name2": "TempName2", "Name1": "TempName1"}]'
Looks ok form me. And then I don't understand part starts. This is my JS/JQuery function:
input_newRecord_Search.keyup(function() {
$.post('/edit/ajax_search_patients', { KeyName: $(this).val() }, function(data) {
var patients = jQuery.parseJSON(data);
for (var patient in patients) {
$('#searchResults ul').append('<li>'+patients[patient].Name1+'</li><li>+'patients[patient].Name2+'</li>');
};
}, "json");
});
I get an error: "SyntaxError: JSON.parse: unexpected character".
I checked what data jquery gets from server: console.log(data):
[{Name2: "TestName2", Name1: "TestName1"}, {Name2: "TempName2", Name1: "TempName1"}]
So, as far as I know JSON syntax looks like - {"key":"value"} and I'm missing quotes on key field. And I don't understand why I'm missing them. I can put them manually through regex, for instance, but I don't think it's the right way. And using regex I can parse my entire data without need of jQuery.parseJSON(), but again I want to use jQuery function - after all it was made exactly for this purpose.
Can anyone help me with this one?
The trick is that when you tell jQuery.post that the server is returning JSON it parses it for you.
// This line can be safely removed;
// jQuery is doing it for you behind the scenes
var patients = jQuery.parseJSON(data);
When you use parseJSON on the already parsed data you wind up trying to parse the string representation of a JavaScript object. Simply use the already parsed data and everything should work correctly.
jQuery is automatically converting the json to js objects for you. You don't need to call parse yourself.

Json object in jquery can't be read?

I am trying to read the finance info from the google page into a json object.
Code is below:
try {
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?",function(data){
alert(data);//var jsondata = data;
//jsonobj = $.parseJSON(jsondata);
//alert(jsonobj[0].id);
});
} catch(e) {
alert(e.toString());
}
However I keep getting this error all the time on firebug
invalid label
"id": "4052464"
Is there any way this info can be read. My ultimate goal is to create a windows 7 gadget that doesnt use server side scripting and can be used from any Windows 7 system.
Appreciate all the help.
John
Response isn't valid JSON (response is prefixed with //), so jQuery won't be able to parse it correctly anyway.
To solve change &jsoncallback=? to &callback=?
so
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&callback=?", function(data) {
alert(data)
});
The response from Google has two leading /'s, making the response invalid JSON... for some reason.
Because of this, you cannot use jQuery.getJSON, as it expects a JSON response. Instead, you should use jQuery.get, and parse the JSON yourself after removing the two leading slashes.
jQuery.get('http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?', function (string) {
var validJson = string.slice(2);
var obj = jQuery.parseJSON(validJSON);
// use obj
});
Two additional points:
No JSONP is being used, so you don't need the jsoncallback=? in your request URL
The Windows Sidebar has been retired, so you cannot publish you finished gadget to the official gallery.

Categories

Resources