Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to consume data from an API using REST call .
I've succeeded to get data from the API :
You can check demo on jsfiddle : http://jsfiddle.net/zTXyq/33/
Now , I am trying to perform the work to get different resources from this API
I am reading these two articles :
- http://www.jquery4u.com/demos/ajax/
- http://welcome.totheinter.net/tutorials/model-view-controller-in-jquery/
I would like to know why do we use JSON.stringify() if we can show data in HTML pages .
Why do we use so-called 'class'/'model' to parse data using json ?
Regards ,
JSON is a data structure, which means it serves to transport variables, arrays and stuff.
Sending variables in html code would be silly - that is why we use JSON.
JSON.stringify() is an utility function, which is most commonly used for debugging, when you want to print some variable to console, but there are some other uses, too.
console.log( JSON.stringify(myObject) );
What the function does, is that it takes an object, array or about anything else, and makes a readable string of it, while simply using something like this ↓↓ would give you only [Object].
console.log( myObject );
If all you really want is to send some HTML to be displayed, then you don't need to bother with JSON at all, and just use jQuery.load() or something similar.
I hope you will agreee that in javascript code JSON objects are nice and easy to use, for example
var jsonObj { "p1": "1", "p2": "2"};
if ( jsonObj.p1 == '1' ) { // do something }
But if we want to pass that object around to non javascript code, for example to a PHP script, we cannot do it.
So the stringify comes into play, we stringify our JSON object i.e. convert the whole object to a string, now we can pass this around to anything that has the ability to convert it back to something useful. So PHP has the json_decode() function to convert a stringified json object/array to a PHP object/array so it becomes useful again.
Now when we want to pass data back from PHP to javascript we convert a PHP object/array to a json string using json_encode() and we can now pass an object/array back to a javascript as a string for it to use JSON.parse() on so it can convert it back to a usable object/array.
So in summary, stringify allows us to convert language specific formats for objects/arrays into a universally available format i.e. a string. Therefore any language that provides a method of converting this stringified format into its own language specific formats for objects/arrays can use this data and of course return it again via the stringified format.
Related
I'm trying to use AJAX to receive updates from a database without needing to reload the page. I've had very minimal problems thus far, however, I finally hit one. When retrieving information from a database, I have it convert all possible rows to an array. From there, I encode that array back to Javascript using $test1 = json_encode($array). In this same PHP function, I'm doing this to multiple pieces, converting those encoded arrays to a string by doing echo $test1."#".$test2."#".$test3. In Javascript, I split that string by the hashtag, and then grab the information of an array by doing something like test1 = array[1]. When doing that, I can retrieve that array entry as a string even though it's in the fashion of a Javascript array. Any ideas on how I can make it treat that string, which is setup like an array, as an array? Thanks in advance!
When retrieving the information from the AJAX response, you need to make it a Javascript Object. Convert the response to an object by doing JSON.parse(response) to get it to work
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am learning web development. I have come across a part in jquery where i can dynamically produce html elements like div table etc. But i wanted to know how to store these dynamically produced data. What are all the ways to store these jquery dynamic data?? And if i want to store it in mysql how to do?? It will be helpful if you have any reference links or code. Pls help me with this
The dynamic data often comes from a JSON string. JSON represents an object (or a set of objects) that can be used directly in Javascript.
Using Jquery, you can get JSON with this utility method : getJSON( url [, data ] [, success ] )
So you have to provide an URL responding with JSON, to be used as the url parameter in getJSON function.
It can be either a static file (ie http://domain:port/data/myData.json) or a dynamic content generated by a server side process in the language of your choice (PHP, Java, JS with NodeJS...), ie http://domain:port/myData.php?filter1=value1.
Note : JSON is the most standard format for transferring objects to Javascript, but it could any format (CSV, XML, ...)
In the callback method of getJSON, you will be provided a plain Javascript object that will contains everything that was in your JSON file, and you could use it to produce whatever you want (html elements like div table etc).
If you need to request a SQL backend, you will have to use a server side process to do the SQL request and map it back to a JSON object.
If there is a cookie on our website called cabbages and $.cookie("cabbages") returns this:
"purchaseType":"NONE","futurePurchaseType":"NONE","id":73041988,"unlimitedStatus":null,"hasFuturePrivilege":false,"corpUser":false,"suspendedStatus":null,
What is the prescribed or conventional way to get back the value of id? I want the ID of the visitor so in this example I'd like to write some Javascript that returns 73041988.
Contents of your cabbages cookie looks very close to json object syntax to me. So JSON.parse() would be naturally the way I would take. You just need to add curly braces to that string to make it valid json object syntax.
Actually this has got nothing to do with cookies. If any variable contains data having syntax similar to this, you can always go for JSON.parse() to extract it in to a javascript variable.
Json objects look like:
{name1:value1,name2:value2,name3:value3}
Similarly a json array looks like:
[value1,value2,value3]
and you could use JSON.parse for any data having json sytax.
You can see some more good examples of JSON syntax in links below.
http://json.org/example
http://www.tutorialspoint.com/json/json_syntax.htm
Please note that this JSON API which provides native support for json serialization in javascript may not be available in some older browsers and the function call will fail.
As you mentioned $.cookie() in your question, I guess that your project is already using JQuery. So you better use jQuery.parseJSON(), which makes use of JSON.parse where the browser provides a native implementation, and also provides a fall back parser when browser support is not available.
This Stack Overflow thread has more details about Native JSON support in browsers.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Is there any way to save a php object in the client side, so when I further need it I don't need to make Ajax request to get another new.
Yes -- use an HTML5 localStorage key to save whatever data you need:
localStorage["hi"] = "ho";
// and then later ...
alert(localStorage["hi"]);
Strings saved into the browser's local storage will persist when the user navigates to a new page on your site, or returns to your site later. Its browser support is pretty good -- even IE8+ supports it.
One note: you can only save string data. So, if you have an object, then you'll need to use JSON.stringify / JSON.parse:
var user = { firstName: "foo", lastName: "bar" };
localStorage["name"] = JSON.stringify(user);
// and then later ...
var restoredUser = JSON.parse(localStorage["name"]);
if (restoredUser)
alert("Hi, " + restoredUser.firstName);
You can use object serialization/deserazlization as explained here storing php objects on html form element and passing php objects through GET method?
serialize the object and encrypt the output xml string that goes on client
Then when client send request back you can decrypt the xml string and restore the object on server side by using deserialization
About encryption see this one Simplest two-way encryption using PHP
And also you can use HTML 5 client local storage as said above but this may not work in older browsers by default see localStorage supported browsers
And again it is really depends on what you exactly want to achieve and what kind of data you want to store, in some cases you can just simply use server caching so in such case you do not need to store the whole object on the client at all.
Sure, you can certainly store a PHP object at the client side. Eve an object, which contains references to object, arrays as member variables...
But don't trust anything coming back from the client that you
forwarded before to the client!
An attacked can easily change or replace the serialized object at the client side. Therefore, it's extremely dangerous to store server-side objects at the client side.
That said, here is how to store a PHP object at the client side
First, serialize the object:
$serializedObject = serialize( $someObject );
Next, save the object using local storage at the client side (base64_encode() 'hides' quotes):
<script type="text/javascript">
localStorage["soAccessor"]
= "<?php echo base64_encode( $serializedObject ); ?>";
</script>
Finally, you might pass it back to the PHP-side using e.g. a hidden field of a form.
In case you need to deserialize something back to its original object state, use deserialize(). Note, that you need to require_once() each object's class definition before doing the deserialize operation.
During deserialization, PHP tries to __wakeup() serialized objects. This won't happen correctly, if the class isn't orderly defined yet.
how to convert this json to database:
var obj = {
'one' : ['qq','rr'],
'pizda' : { }
}
and then retrive it and use it?
You could store it in mongodb without too much effort.
db.foo.save(obj); // Save obj to a database
db.foo.find(); // find it again.
You might want to give a bit more details.
Assuming that the database runs on the webserver and you thus need to pass the JSON as a string around between webserver and webbrowser, then the answer depends on the server side language you're using.
If you're using PHP, then you can convert between a JSON string and a PHP array using json_decode() and json_encode()
If you're using JSP/Java, then there are several libraries available to convert between a JSON string and a Java object, the popular ones being Google Gson, JSON.org and Jackson.
If you're using ASP/.NET, then there are several libraries available as well, under each Google JSONSharp.
Also see the bottom of this page for an overview of several JSON parsers/formatters in various languages.