I want to create a parser for login page. I have a url that gives response in json. When not logged in it gives response as :
{"status":0,"msg":"Email is Wrong!"}
and when loggged in it gives :
{"status":1,"msg":"Session is active","session_id":"lp47ngp9hlqtrkunjirqa7ijg5","user_id":"13"}
I have no idea how to start this. Please help...
Thanks in advance!
Not sure if I'm understanding a real question here, but as I understand it, try using jquery ajax to retrieve your json from the url. In the call to ajax, there'll be a parameter called success, that takes a function with one argument. That argument will be the data retrieved from the url. Simply do obj = eval(data), and your data will be parsed and you can access the status as obj.status.
Using plain javascript you can use JSON.parse to convert the JSON string to a Javascript Object.
Something like:
var response = JSON.parse([yourJsonString]);
if (response.session_id) {
// logged in, proceed
} else {
// not logged in, act accordingly
}
JSON.parse is available in modern browsers. For older browsers you need to include a JSON parser like this one (use json2.js)
If you use jquery and jquery.ajax/jquery.get, etc., you will receive a response in the form of a javascript object that you may use to react accordingly.
Jquery is an excellent javascript library very very widely used. It's kind of a defacto standard.
Just google it and you will find a lot of information, tutorials, books. In Stack Overflow you will find a lot of material on this topic.
You can use the jQuery parseJSON method to parse the JSON string into Javascript object
http://api.jquery.com/jQuery.parseJSON/
Related
I haven't really written any javascript but am building an iOS application that will utilize JavaScriptCore's framework to read a javascript code to get a variable. What I'm looking to do is set up a GET (I think) so that I can retrieve JSON data from a url and then pull a specific string from the JSON data. Within the GET method, I'll need to add credentials and one parameter. What is the best practice to do this?
As per Rory's statement above the server you are requesting the json data from must either be on the same domain as your Application/Js code or support the CORS headers.
If the above is true, then you can either use JQUery as suggested above, or for a more minimalist approach the W3Schools has a tutorial on basic Ajax.
https://www.w3schools.com/xml/dom_httprequest.asp
Referring to my question above, the reason I want to retrieve the file is that I want to know how it is structured so I can make the script that I copied work using my data instead.
Currently, the $.getJSON url includes the string "callback=?" in it.
So is there anyway, I can peek through or see how the data is structured in the file thats inside the $.getJSON url string?
actually, Im following along a demo below
https://code.google.com/r/kgraham-flr-map/source/browse/examples/medicare-dynamic-ds.js?spec=svn72fd5de93cf24b0b2baa5d2678d9518741e3d80b&r=72fd5de93cf24b0b2baa5d2678d9518741e3d80b
Tthe script in question has the $.getJSON('https://storelocator-go-demo.appspot.com/query?callback=?' to parse the data.
When I tried opening the url, I get this error strconv.ParseFloat: parsing "": invalid syntax
I want to see how the JSON file is structured so I can replace it with my own data instead.
Hope this clears my question.
From the comments:
so you mean the error that I got when trying to open the json file is due to a server problem?
Well, it could give you a more useful error message. The problem is that you're not giving it the arguments it requires.
If I go to:
https://storelocator-go-demo.appspot.com/query?callback=foo
...then like you, I get that error. But if I give it arguments (these are cribbed from the examples link you gave):
https://storelocator-go-demo.appspot.com/query?callback=foo&lat=-29.292219923932738&lng=137.763512&n=-10.691329506145314&e=167.382652625&s=-47.89311034172016&w=108.14437137499999&audio=&access=&_=1364633286163
I get back a valid JSONP response.
in my JS project I need to load data from cross-domain. (JavaScript sits on domain A, the data comes from domain B)
I have a solution that uses JSONP but I really need to load an XML instead (ordinary XML music playlist). The main goal is to be able to load and parse the XML data without the need to modify them first to some other format (like JSONP).
Is it completely impossible? Or are there any workarounds or hacks?
I am targeting mainly the latest browsers mainly on iOS.
Thanks!
PS: Could easyXDM be of any help? Or it's not relevant to XMLs?
UPDATE: unfortunately I can not use proxy, I am really asking about a direct solution.
You can totally do this, just have your domain B return something like
func("<myxml></myxml>");
or
var someVar = "<myxml></myxml>";
The name JSONP doesn't really have anything to do with JSON specifically since its concept is all about executing JavaScript that has your data embedded in the code.
Once your domain B returns exactly one of those 2 forms above, domain A can simply use it either by doing:
<script>
function func(xmlString) {
alert(xmlString); // you can parse the xmlString with
// jQuery or something else
}
</script>
or if you use the second example:
<script>
alert(someVar);
</script>
The usual solution is to have a "AJAX proxy" - a simple server-side script running on your domain, that fetches the data from the other domain and returns it unchanged.
The simplist is to give the script the URL you need the data from:
http://example.com/proxy.php?url=http%3A%2F%2Fexample.org%2Fajax%3Fid%3D123 gets the data from http://example.org/ajax?id=123
This can however be misused if you let any URL be fetched like that, so you should have your script, check that it actually only gets data from a specific URL.
In order to avoid having to parse the URL to check this, you could write a proxy specificly for your app, that only accesses the specific resource you need:
http://example.com/proxy.php?id=123 to access http://example.org/ajax?id=123.
If you have a JSON-P solution in place, you can just pass the XML to the JSON-P callback as a string. You can then do XML parsing of a variable string in JavaScript
The whole idea with JSONP is that the response must be executable as script. So sure, you can pass XML data back, as long as it's valid Javascript - for example, the server could wrap its response in a string:
myCallback('<xml><stuff/></xml>')
and you'd have to parse it with jQuery:
success: function(data) {
var xml = $(data); // now do stuff
}
This assumes that you control the other server and/or someone who does is interested in formatting their data that way. Otherwise, you're out of luck, and need a proxy of some sort - you might be able to do this with YQL.
I'm considering creating a simple remote debugging application for Javascript. Actually, I want to provide an object to Firebug Lite and let it do all the job.
So, can I get an object from one page, serialize it, send it to server and then to another browser and finally see the same results in Firebug Lite (on that other client) as I would see on the first browser (with doing "console.dir(obj)")? Is it possible to do?
Plain answer: no. You'll have to serialize your object to some kind of string. It could be XML, or JSON, or a format you make up, like:
var anObject = {first:1,second:2,third:'infinite'};
function serializer(obj){
var serialized = [];
for (var l in obj){
if (obj.hasOwnProperty(l)){
serialized.push(l+'='+obj[l]);
}
}
return serialized.join('&');
}
alert(serializer(anObject)); //=>first=1&second=2&third=infinite
If your object contains objects, you could use the serializer function recursively.
Using JSON for encoding the object?
http://json.org/
The easiest solution is to serialize to JSON. However, it is important to note JSON does not support all JavaScript types.
Instead of just half-answering the question, here's the real deal!
Like the others said, use JSON (implementation details) to serialize your data (because it's nativly supported by Javascript and it's lightweight), and then send it to your server using AJAX, maybe by sending it to a PHP script that just saves it to a file or a database or something.
Then on the other side, you simply receive it by again using AJAX to ask said PHP script to return that data to you!
The documentation page for the YUI "Get" utility says:
Get Utility is ideal for loading your
own scripts or CSS progressively
(lazy-loading) or for retrieving
cross-domain JSON data from sources in
which you have total trust.
...but doesn't have any actual examples for how to do so. Their one example doesn't actually request a JSON document from a remote server, but instead a document containing actual JavaScript along with the JSON data.
I'm just interested in the JSON response from the Google Maps API HTTP (REST) interface. Because I can't do cross-site scripting with the "Connect" utility, I am trying the "Get" utility. But merely inserting some JSON data into the page isn't going to do anything, of course. I have to assign it to a variable. But how?
Also, just inserting JSON data into the page makes Firefox complain that there's a JavaScript error. And understandably! Plain ol' JSON data isn't going to parse as valid JavaScript.
Any ideas?
Normally in this case the easiest thing to do is to return javascript that calls a callback with the json. For example:
function xdCallback( json ) {
// here I can do whatever I need with json, maybe
SomeModule.heresTheJson( json );
// or
globalVar.json = json;
// etc
}
And so on your server side you return not just JSON but instead something like:
xdCallback( { json: 'goes', here: true } );
...execute the 'script' when you get it via your ajax call and you're set.
OK. Looks like without Google's HTTP Geocoding interface supporting JSONP, there is no way to do this. :(
Sean -- You may find that YUI Connection Manager's XDR support is what you're looking for --
http://developer.yahoo.com/yui/examples/connection/xdr.html (YUI 2)
http://developer.yahoo.com/yui/3/examples/io/io-xdr.html (YUI 3)
Use Connection Manager (YUI 2) or IO (YUI 3) to bring in the JSON, and then use the JSON component in either codeline to parse the JSON once it's loaded.
If Google or Yahoo! has the necessary cross-domain support on the relevant servers, you should be in business.
-Eric
I have used YAHOO.lang.JSON.parse to parse a string to json. Also the stringify method can be used to go from JSON back to a string:
http://developer.yahoo.com/yui/docs/YAHOO.lang.JSON.html