I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.
Related
I have an ajax call to a PHP module which returns some HTML. I want to examine this HTML and extract the data from some custom attributes before considering whether to upload the HTML into the DOM.
I can see the data from the network activity as well as via console.log. I want to extract the values for the data-pk attribute and test them before deciding whether to upload the HTML or just bypass it.
$.ajax({
url: "./modules/get_recent.php",
method: "POST",
data: {chat_id:chat_id, chat_name:chat_name, host_id:host_id, host_name:host_name}, // received as a $_POST array
success: function(data)
{
console.log(data);
},
})
and some of the console log data are:
class="the_pks" data-pk="11"
class="the_pks" data-pk="10"
etc.
In the above data I want to extract and 'have a look at' the numbers 11 and 10.
I just do not know how to extract these data-pk values from the returned data from the ajax call. Doing an each on class 'the_pks' does not work as at the time I am looking at the data they have not been loaded into the DOM.
I have searched SO for this but have not come up with an answer.
Any advice will be most appreciated.
I hope I understand your question.
If you get a HTML as a response, you can always create an element and insert that html inside it, without adding it to the DOM. And after that you can search it as you do with a DOM element.
const node = document.createElement("div");
//then you can do
node.appendChild(data);
// or
node.innerHTML = data;
And after that you can search inside the node:
node.querySelectorAll("[data-pk]")
I will re-engineer this - it was probably a clumsy way to try and achieve what I wanted anyway. Thanks to those who tried to help.
So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.
What are some arguments as to when to use JSON external file such as with jQuery's
$.getJSON('external.json',function(data){});
(ajax retrieving) versus defining it in javascript with
var myJson = { "someVar": { "1": ["test1","test2"], "2": ["test3","test4"]} }
What is the "proper" way of doing it? Does it depend on JSON length or are there any other factors that can tell you what approach to use?
The way I see it: choose between loading another file which is supposed to be slow as you are loading data via ajax call or adding plenty of lines into already packed javascript file which is not a good thing either. Surely there must be some distinction as to where you should use one or another ... ?
I am not interested only in speed difference (getting file from ajax is of course slower) but also in other aspects such as what is generally used when and what should be used in some case ...
The first one is a shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
This is an Ajax request which will take more time than having a simple JSON object into the file.
I would prefer the second one IF it's possible. Also if you attend to have good performances the first one is longer.
time( Loading+parsing 2 files ) >> time( Read a Javascript object )
If your data is known at page creation time you're probably best to use an object literal like:
var myJson = {...}
However, as Kursion mentions,
$.getJSON(...)
is a shorthand method for retrieving json data asynchronously via ajax. You'd use it if you want to retrieve data from the server that wasn't known at the time of page load...
For example, if a user enters a search term in an input control, you might want to retrieve JSON in response to that without performing a whole page update. You couldn't simply define a javascript object up-front because you wouldn't know what the search term was in advance.
I've started using Newtonsoft.Json.Schema.JsonSchemaGenerator along with various property attributes over in my C# code to help keep my client script DRY. What I'd like to do is create a default initialized object client-side based on the schema from the server. This would be useful for, say, when the user clicks 'New Foo' to add a new entry into a table.
Obviously I can just code it up to iterate the .Properties and build up the new object, which is what I'm doing at the moment. However I'd prefer to avoid reinventing any wheels.
Are there any JS libraries for working with JSON schema that will do this, among other nifty things I've yet to realize I need?
1/29/2013 UPDATE
Some people have attempted to answer my question and have been off base, and as a result have received some negative feedback from the SO community. So let me attempt to clarify things. Here is the challenge:
In JS client script, you have an object that represents the JSON Schema of another object. Let's say, this came from the server via JSON.NET and is the representation of a C# class.
Now, in the JS client script, create one of these objects based upon the JSON Schema. Each field/property in the object must be default initialized according to the schema, including all contained objects!
BONUS: Bind this new object to the UI using MVVM (eg Knockout). Change some of the fields in response to user input.
Send this new object to the server. The server-side code will add it to a collection, database table, whatever. (Yes, the object will be sent as JSON using Ajax -- we can assume that)
No duplication! The only place where the class is defined is in the server-side code (C# in my example). This includes all metadata such as default values, description text, valid ranges, etc.
Yes there is (I tried it with NodeJS):
JSON Schema defaults
Link updated.
i think...you have to use two way binding with your HTML code...so, once your client side change you will get on your costume js file.
check here for knockout js.
Knock Out JS Link
and on C# code use : $("#urlhidden").val() OR Document.GetElemenyByID("#urlhidden").val().
here you will get array/list or textbox value
Use json with Ko
create new viewmodel for knockout js which you will get the idea about on above link.
and create a json call
like:
self.LoadMAS_Client = function () {
try {
var params = { "clientID": ClientId };
$.ajax({
type: "POST",
url: "http://" + ServerString + "/Services/LogisticsAppSuite-Services-Web-Services-MasClientService.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
// in response u will get the data.and use as per your requirement.
eg. self.SelectedClient(response.your value);
},
error: function (ErrorResponse) {
}
});
}
catch (error) {
}
};
================================New Update ==========================================
i think..one way you can do...get data on xml format at C# code and covert into json string...check below code // To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
I have built a calendar in php. It currently can be controlled by GET values from the URL. Now I want the calendar to be managed and displayed using AJAX instead. So that the page not need to be reloaded.
How do I do this best with AJAX? More specifically, I wonder how I do with all GET values? There are quite a few. The only solution I find out is that each link in the calendar must have an onclick-statement to a great many attributes (the GET attributes)? Feels like the wrong way.
Please help me.
Edit: How should this code be changed to work out?
$('a.cal_update').bind("click", function ()
{
event.preventDefault();
update_url = $(this).attr("href");
$.ajax({
type : "GET"
, dataType : 'json'
, url : update_url
, async : false
, success : function(data)
{
$('#calendar').html(data.html);
}
});
return false;
});
Keep the existing links and forms, build on things that work
You have existing views of the data. Keep the same data but add additional views that provide it in a clean data format (such as JSON) instead of a document format (like HTML). Add a query string parameter or HTTP header that you use to decide which view to return.
Use a library (such as YUI 3, jQuery, etc) to bind event handlers to your existing links and forms to override the normal activation functionality and replace it with an Ajax call to the alternative view.
Use pushState to keep your URLs bookmarkable.
You can return a JSON string from the server and handle it with Ajax on the client side.