i want to send a json string from a html webpage using javascript to a WCF.. is there any good tutorial for that?
this is the code i am using
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function() {
JSONStringer json = new JSONStringer()
.object()
.key("cno").value("2000")
.key("cname").value("HI")
.key("cmail").value("HI")
.key("cphno").value("9292")
.key("cmailtype").value("Home")
.key("cphnotype").value("Office")
.key("clientno").value("1")
.endObject();
var dat = JSON.stringify(json.serializeArray());
alert("I am about to POST this:\n\n" + dat);
$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
});
</script>
</head>
let me know where i have to post it to a particular service.. something like specifying the URL
I think you are mixing up java with javascript. Despite their names they are not related to each other in any way. As far as I know, JSONStringer doesn't exist in javascript nor jquery. JSON stands for JavaScript Object Notation, so that means it is very native to the javscript languages (with some subtle differences). Since it's so close it is very easy to parse Json in javascript.
Also, javascript is a dynamically typed language so supplying the type as you did normally results in a parse error. Use firebug or the Chrome console when your code doesn't work. You will see an error when the browser was unable to parse your code.
for the serialization you probably want to use (in a browser that supports JSON and/or with json2.js)
var dat = JSON.stringify({
cno: 2000,
cname: 'HI',
cmail: 'HI',
cphno: '9292',
cmailtype: 'home',
cphnotype: 'Office',
clientno: 1
});
The url goes where you have put frm.attr("action"). I don't see where you create the frm object. I don't think you need a JQuery object for that, document.getElementById is supported in all major browsers and I bet it is faster too.
var myForm = document.getElementById('myformid');
$.post(
myForm.action,
dat,
function(data) {
alert('Response: ' + data);
}
);
Also as far as I know, postdata has to be in query parameter format so perhaps you need to put something like
'myData=' + dat,
Copy/pasting code from the web can get things started quickly but a lot of javascript programmers forget that you have to understand the language first. Don't just blindly copy code, try to understand what happens. Try to solve problems first without a library and discover where you actually need a library.
http://www.learn-ajax-tutorial.com/PassingData.cfm#JSON
Get json.js.
Encode array or object in to json.
Do Ajax.Request to post the json string. Simplez!
That is pretty much all you need, not sure about the WCF side but if it is a proper webservice then all you need is the descriptor to figure out the function names and their parameters.
Related
I'm new to jQuery and I have a simple jQuery script.
I've put this in my header:
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'/>
In my body, I have this:
<script type='text/javascript'>
$(document).ready(function() {
alert(1);
$.getJSON('http://puppygifs.tumblr.com/api/read/json', function(data) {
alert(2);
});
});
</script>
But, while Firebug says the JSON is accessed and there are no errors, I only get the first alert, not the second. Why doesn't the second alert execute?
The json response returned by http://puppygifs.tumblr.com/api/read/json is not valid json, which causes the success handler not to execute.
If you look at the first line the response its var tumblr_api_read={, which isn't valid. To see a valid json example checkout: http://json.org/example.html
This situation is noted in the Jquery Documentation:
As of jQuery 1.4, if the JSON file contains a syntax error, the
request will usually fail silently. Avoid frequent hand-editing of
JSON data for this reason. JSON is a data-interchange format with
syntax rules that are stricter than those of JavaScript's object
literal notation. For example, all strings represented in JSON,
whether they are properties or values, must be enclosed in
double-quotes. For details on the JSON format, see http://json.org/.
getJson Documentation
Also be sure to close the script tag with an end tag and not the shorthand end tag
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
If you are accessing this json from outside the providing domain you must indicate its jsonp This can be accomplished by appending &callback=? to the url as described in the jQuery Documentation.
$(document).ready(function() {
alert(1);
$.getJSON('http://services.faa.gov/airport/status/SFO?' +
'format=application/json&callback=?', function(data){
alert(2);
});
});
JS Fiddle http://jsfiddle.net/J5jYW/
I have a url [https://www.inquicker.com/facility/americas-family-doctors.json] that is a JSON data url. How can I access the contents of this url, and write out the values.
The format contains schedules as an array that inside it contains schedule_id, name, and available_times. I have tried various ways of getting the JSON file, but none have worked.
UPDATE:
Well I have got it this far with this code, and it's laying out what looks like objects from the array. So I believe I got the cross site issue under control. I just need to figure out how to access the data now.
<!DOCTYPE html>
<html>
<head>
<title>JQuery (cross-domain) JSONP</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
alert(data.facility);
$.each(data.schedules, function(i, name){
$('#names').append('<li>' + name.available_times[0] + '</li>');
});
});
});
</script>
</head>
<body>
<ul id="names"></ul>
</body>
</html>
Any help, or suggestions will be greatly appreciated, Thanks.
You cannot generally pass an Ajax request across domains. Normally a server will refuse any Ajax calls that don't come from the same source unless it is explicitly configured otherwise. I am guessing that you aren't calling from the same domain, given that you are using a fully-qualified URL. If you own the server, you will have to configure it to accept such calls from your other domain.
If this is not the case, launch the script in Firefox with Firebug running and look at the console output and tell me what error you get if any.
Once you manage to pass the JSON from your server back to the page, you will retrieve it in your JavaScript as a string. You then need to execute this function:
var jsonObject = JSON.parse(jsonString);
where jsonString is the string that you received from your server. jsonObject becomes an object representation of the JSON passed back to the answer that you can access using dot notation.
Try something like :
alert(json.facility);
There is no title json object in the url you have mentioned.
The JSON is already parsed when it comes to your function.
$.get('https://www.inquicker.com/facility/americas-family-doctors.json', function(result){
alert(result.facility); //Do whatever you want here
// result.schedules array is also ready
});
I want to get the username's profile image. So i prefer to use twitter api version 1 for this.(The regular version of api is here). But my code doesn't return any data. How can i fix this?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready( function() {
var userPage = "https//twitter.com/jack";
var arr = userPage.split("/");
var username = "";
for(i=3;i<4;i++)
username += arr[i];
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username;
$.getJSON(page, function(data) {
alert(data.profile_image_url);
});
})
</script>
</head>
<body>
</body>
</html>
Add "&callback=?" to the URL to force jsonp format to get around the Access-Control-Allow-Origin issue.
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username + "&callback=?";
EXAMPLE
JSONP:
The way JSONP works is simple, but requires a little bit of
server-side cooperation. Basically, the idea is that you let the
client decide on a small chunk of arbitrary text to prepend to the
JSON document, and you wrap it in parentheses to create a valid
JavaScript document (and possibly a valid function call).
The client decides on the arbitrary prepended text by using a query
argument named jsonp with the text to prepend. Simple! With an empty
jsonp argument, the result document is simply JSON wrapped in
parentheses.
I'm trying to make a variable (eventually to be replaced by more complex json selected from the database) accessible to client-side javascript. I wanted to load it when the page is rendered instead of an ajax call and its not going to be rendered via a template like ejs (I want to pass the data to an extjs store for a combobox). So I have a standart response I render:
function (req, res) {
res.render('index.html', {foo: ['a','b']});
}
and a blank html page I want to access foo:
<!DOCTYPE html>
<html>
<head>
<script type=text/javascript>
console.log(foo);
</script>
</head>
<body>
</body>
</html>
any ideas? I've thought of maybe writing the whole html page via res.send() (which has a few more things than the example above) but that seems like such a workaround for something that should be obvious to do...
Assuming the same array foo in your question above, here are a couple ways you could do this.
This one uses an EJS filter to write an array literal:
<script type="text/javascript">
var foo = ['<%=: foo | join:"', '" %>'];
</script>
This one encodes it as JSON, to later be parsed by your client-side javascript:
<script type="text/javascript">
// note the "-" instead of "=" on the opening tag; it avoids escaping HTML entities
var fooJSON = '<%-JSON.stringify(foo)%>';
</script>
IIRC, ExtJS can handle JSON directly as its data. If not, then you could use its JSON parser first and then hand it a local variable. If you weren't using ExtJS, you could use this to parse on the client: https://github.com/douglascrockford/JSON-js
If you choose to encode it as JSON, it would make it also make it easier to later switch back to AJAX for retrieving your data. In some cases, that would have an advantage. The page could load and display some data, along with a busy icon over the element for which you're loading data.
This isn't to say there's anything inherently wrong with including all the data in the original request. It's just that sticking with JSON gives you the flexibility to choose later.
In EJS the following should work
<script type=text/javascript>
console.log( <%= foo %>);
</script>
I do recommend against dynamically generating JavaScript though as it breaks seperation of concerns and forces JavaScript to be on.
Edit:
Turns out the above doesn't work nicely for arrays. So simply encode your data in semantic HTML. Then enhance it with JavaScript. If the JavaScript must get data then store it somewhere more sensible like the cookie or retrieve it through ajax.
I'm calling a REST webservice and getting JSON format as a result. I'm calling rest service from another domain than mine. How can I parse this?
To answer the question you asked: There is a long list of parsers, including several for JavaScript, at the bottom of http://json.org/
If your question is actually: "How can I read JSON data from another domain with client side JavaScript in the browser?", then you can either fetch it using a proxy on the same domain as the page, or you can provide the data using JSON-P instead.
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
var myObject = JSON.parse(myJSONtext);
or use jQuery
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) {
alert(json.followers_count);
});
if you need only parsing jQuery also can do this:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
Are you getting the json result? Most implementations have protection agains cross site scripting and will only allow a request back to the original host of a page.
Could you please post some example code for your current implementation.