Raw json is not appearing on the page - json

I am trying to do a 'get' request through ajax on a url. everything works fine on the console but unable to get the raw json data to display on the page. here data.collections gives me an array of objects. I specifically want raw json data only on the page.
my script is this:
var research;
$.ajax({
url: url,
type: 'GET',
dataType: 'json'})
.done(function(data){
research= JSON.stringfy(data.collections)
});
$('.rsh').html(research);
html is this
<div class = 'rsh'></div>
I want raw json data on page like this but my page is blank.
{
"lab": {
"type": "xy",
"year": "yz",
"team": "yx"
},
"name": "qwerty",
"assistants": 5,
}
edit: this question deals with displaying data in raw json format on the page. Unfortunately the problem in my code was wrong placement of the code. Initial question has nothing to do with asynchronous nature although it is good to know.

var research;
$.ajax({
url: url,
type: 'GET',
dataType: 'json'})
.done(function(data){
research= JSON.stringfy(data.collections)
$('.rsh').html(research);
});
An ajax call is asynchronous so you will need to use the response within the done/success method.

Related

how to process json post request with nodejs http (no express framework)? [duplicate]

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

How to call .asmx web service using plain html page

I am trying to call an asmx web service in plain html page. But not getting output. I'm not getting the exact problem. Here is my ajax code that I wrote to call that asmx web service.
function Getdet(Name)
{
alert('hellotest');
$.ajax({
type: "POST",
url: "http://192.168.1.20/myservice/service.asmx?HelloWorld", // add web service Name and web service Method Name
data: "{''}", //web Service method Parameter Name and ,user Input value which in Name Variable.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert('abcd1');
$("#spnGetdet").html(response.d); //getting the Response from JSON
},
failure: function (msg)
{
alert(msg);
}
});
}
Should I have to add anything in the code..?? Please let me know where I am going wrong in this above code.
ASMX pages are plain old Web Services and the output is (almost) always in XML format, so don't except JSON out of the box.
Plus, they don't work well on different domain call by default, you will need to ensure that the cross domain is correctly handled.
After all this is done, you will then use the call as:
success: function(response) {
// http://stackoverflow.com/a/1773571/28004
var xml = parseXml(response),
json = xml2json(xml);
$("#spnGetdet").html(json.d);
}

Posting parameters in one URL and getting JSON from another URL

Am working in jQueryMobile and PhoneGap.
Currently am facing an issue that; For get the details in JSON format ; I post parameters into an URL (URL1) and I get the JSON response from another URL (URL2)
Currently i cant access the JSON data from the second URL.
My code is ;
function proceed_payment(){
var cardholder_= $('#input_Cardholder_name_').val();
var card_num_ = $('#input_CreditCard_').val();
var payment_ =$('#card_type_').val();
var cvv2_=$('#input_cvv2_').val();
var url;
url='https://www.sample.com/json/save_pament.php?json=1&rcg_mobile=2&reserv_num='+reservation_number+'&callback='+reservation_carcompany+'&cardholder='+cardholder_+'&payment='+payment_+'&card_num='+card_num_+'&card_cvv2='+cvv2_+'&card_expire_mon='+expire_month+'&card_expire_year='+expire_year+'&org_deposit='+sCarDeposit+'&org_cur='+currency+'&mond='+company_Show_mond+''
$.ajax({
url:url,
data:'',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain:true,
cache: false,
async:false,
success:function(data)
{
alert(data.Status);
$.mobile.changePage( "#reservation_status", {reverse: false, changeHash: true});
event.preventDefault();
},
error: OnError
});
};
Here I Post the parameters to URL1 : - https://www.sample.com/json/save_pament.php?
and get the JSON result in URL2 : https:// www.sample.com /result_bank_eup6.php?app=1
But My problem is i cant access the result from URL2.
Is there any method for solve this?
Please HELP :-(
Ullas Mohan V.
As per our discussion in comments and the error you mentioned
( [object Object]-parseerror-SyntaxError: Unexpected token < ).
The issue is related to web service/server side
Web service is not sending the desired response.
So client side/$ajax is not able to parse it.
You can check the actual response using Google Chrome's Advance REST Client.
To resolve this issue, you should contact the company
which is developing server side for you.

Why is my json encoded?

I have the following code which I post a bunch of JSON data to an ASHX file where I will process this data. Somehow the JSON is encoded and I have no clue what encoded it.
$.ajax({
url: '/save_objects_channels.ashx',
data: jsonParams,
contentType: 'application/json',
dataType: 'json',
success: function(data) {
},
error: function (xhr, ajaxOptions, thrownError){
},
complete: function() {
}
});
Here is my sample json that I posted (I generate this as string):
var jsonParams = '[ { objectID: 333, channelID: 3, supplierId: 2, checked: true },{ objectID: 444, channelID: 4, supplierId: 5, checked: true } ]';
jQuery encoded it. You chose to send it as a GET request (which is the default for .ajax()), which transfers all data in the URL as part of the query string. As Clement Herreman also points out, the query string must be encoded.
You might want to switch to type: "POST" in your .ajax() parameters.
GET requests have a length limit that can bite you when the JSON string gets longer. POST requests have virtually no size limit.
Plus, you will cause a data leak: Query strings are written to the web server logs, possibly sensitive data could end up there when you are not careful. POST requests are logged, too. But their payload will not be logged, as it is not part of the URL.
Because URL must be encoded, according the RFC 3986
Hint on how to encode url using Javascript : Encode URL in JavaScript?

Posting JSON with JQuery

Trying to get JQuery to post JSON to a server:
$.ajax({
url: "/path/to/url",
type: "POST",
dataType: "json",
contentType: "json",
data: {"foo": "bar"},
success: function(){
alert("success :-)");
},
error: function(){
alert("fail :-(");
}
});
Problem is the data appears on the server as "foo=bar" rather than the desired "{\"foo\":\"bar\"}.
I thought specifying either the dataType or contentType params would do the trick, but no.
Anyone know the correct ajax configuration ? [or alternatively a way of serialising the 'data' parameter as JSON prior to posting ?]
Thanks!
You could use json2.js:
data: JSON.stringify({"foo": "bar"})
Datatype is for returned data. Contenttype is not applicable, see here
It can only send strings, I use JSON.stringify on my created javascript objects, in your case you could just manually code the string.
You will also need to access the string on server side, for that if you are using java I can recommened google's gson