I got this JSON as data:
data = {"livemode":false,"pending":
[{"amount":0,"currency":"jpy"},{"amount":8121,"currency":"usd"}],
"available":
[{"amount":-400,"currency":"jpy"},{"amount":99601,"currency":"usd"}]}
now I want to convert this into a more readable text something like this:
"Pending :" + "\n" + "Amount :" + data.pending[0].amount + "\n" + data.pending[0].currency;
So I want to give back the amount of 0 with the currency of jpy but all I get is an Error or undefined, what I'm doing wrong here?
onRetrieveBalancePressed : function() {
var that = this;
jQuery.ajax({
type : "GET",
contentType : "application/json",
url : "https:" + "/retrieve",
processData: true,
dataType : "text",
async: false,
success : function(data, textStatus, jqXHR) {
var sResult = "Balance successfully retrieved! \n"
+"Pending :" + "\n"
+"livemode :" + data.pending[0].amount + "\n"
+"Currency : " + data.pending[0].currency;
First just try to convert your data to JSON using
var obj = JSON.parse(data);
then try to get data from obj.
In case of jquery, you can also try this:
var obj = jQuery.parseJSON(data);
Try to use a JSONObject and put data in that obj then you can work more easily
Related
I am sending XML to a particular web service. When I view the response in my browser's network tab, it seems it's a proper request as I expected, but still the error callback in my JS code is firing hence handling it as an error instead of making use of the returned response as expected. What could be the cause of this?
const endpoint = "https://secure1.sandbox.directpay.online/API/v6/";
$(document).ready(function() {
$("#sendBtn").click(function() {
var x2js = new X2JS();
var req = "<?xml version='1.0' encoding='utf-8'?>" +
"<API3G>" +
"<CompanyToken>TOKEN-TO-BE-PLACED-HERE</CompanyToken>" +
"<Request>createToken</Request>" +
"<Transaction>" +
"<PaymentAmount>450.00</PaymentAmount>" +
"<PaymentCurrency>USD</PaymentCurrency>" +
"<CompanyRef>49FKEOA</CompanyRef>" +
"<RedirectURL>https://secure1.sandbox.directpay.online/payv2.php?ID=TOKEN-HERE</RedirectURL>" +
"<BackURL>http://localhost/computicket_node_server/</BackURL>" +
"<CompanyRefUnique>0</CompanyRefUnique>" +
"<PTL>5</PTL>" +
"</Transaction>" +
"<Services>" +
"<Service>" +
"<ServiceType>5525</ServiceType>" +
"<ServiceDescription>Flight from Malawi to India</ServiceDescription>" +
"<ServiceDate>2013/12/20 19:00</ServiceDate>" +
"</Service>" +
"</Services>" +
"</API3G>";
$.ajax({
url: endpoint,
type: "POST",
data: req,
//timeout: 5000,
dataType: "text/xml",
success: function(response) {
var res = JSON.stringify(x2js.xml_str2json(response));
console.log(res);
document.getElementById("response").innerHTML = res;
},
error: function(xhr, status, error) {
console.log(xhr, status, error);
}
});
});
});
The results that I am getting
Is dataType not the responding type? You should use contentType
contentType: "application/xml",
Don't know what type you expect to get back, I think you can avoid it.
I am sending back in the response an array of objects from my resource, and when the array contains only one element I cannot loop the array because the response turns out to be a single object instead of array containing one object.
having this code from the front end side:
function loadContent(sUsername, sPath){
arrayContentBeans = new Array();
var sUrl = "http://localhost:8080/crosscloudservice/services/RDF/retrieveContent?username="+sUsername+"&path="+sPath;
$.ajax({
type: "GET",
url: sUrl,
contentType: "application/json",
dataType: "json",
async: false,
success: function parse(resp, status, xhr) {
$("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
$("#message").hide();
$.each(resp, function() {
$.each(this, function(i, cb) {
arrayContentBeans.push(cb);
});
});
renderContent();
},
error: function(resp, status, xhr){
$("#message").html("ERROR: " + resp.status + " " + resp.statusText + "\n" + xhr);
$("#message").show();
}
});
}
Anyone can tell me how to force JSON to have an array even when it contains one single object?
UPDATE 1
Here is the Resource:
#GET
#XmlElement(name = "contentbean")
#Path("/retrieveContent")
#Produces(MediaType.APPLICATION_JSON)
public List<ContentBean> retrieve(#QueryParam("username") String Username, #QueryParam("path") String Path) {
ContentBean oContentBean = buildResult(Username, Path);
List<ContentBean> lContentBeans = new ArrayList<ContentBean>();
lContentBeans.add(oContentBean);
return lContentBeans;
}
UPDATE 2
I've added what should serialize my array now jackson-core-2.2.3.jar and the following tag in my web.xml:
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.qcri.crosscloud.ws;org.codehaus.jackson.jaxrs</param-value>
</init-param>
But no luck, it still behaves the same :( any ideas?
if you are sending an Array of object then make sure that when there is only one element to send serialize it as Array so the client side will always get same data structure
I am working a visual studio 2012 MVC program.
I use ajax to send data to a controller and wish the controller returns a body of html. the data is in json format. the data is a string name and decimal TotFees.
I found that the parameters value in the public ActionResult ImmPay(string Name) in the controller are always null. Finally I tried just to pass name, but the value of name in the controller side is still null.
what is wrong in my code, and how to solve the problem? Thank you.
View:
function ImmPay()
{
var name = "ASP";
var TotFees = 100.01;
//var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "\'}";
//var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "m\'}";
dd = "{\'b\':\'" + b + "\'}";
dd = JSON.stringify(dd);
$.ajax({
url: '#Url.Action("ImmPay", "Consult")',
type: 'GET',
async: true,
data: dd,
contentType: 'application/json',
context: document.body,
success: function (response, textStatus, jqXHR) {
$("#dialog-immpay").html(response);
$("#dialog-immpay").dialog("open");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
},
complete: function () {
;
}
});
}
Controller:
public ActionResult ImmPay(string Name)
{
do something here
}
JSON.stringify takes an object or an array and converts it into JSON, so you can build your data into an object and stringify it like so
dd = JSON.stringify({b: b});
I want to send my string value to server as json data, but i get 400 bad request.
here is the code how i am sending data.
dataString = '{"comment":"' +dataString+ '"}';
dataString = '[' + dataString + ']';
$.parseJSON(dataString);
console.debug("After parsing : "+dataString);
$(form_element).clearForm();
$.ajax({
type : "POST",
url : loc,
cache : false,
data : dataString,
dataType: 'json',
contentType: "application/json",
success : function(data) {
console.debug("After success");
}
When i debug the code, the #RequestParameter "comment" have null value.
Kindly help me, thanks in advance.
The parseJSON function returns an object.
You should do
var obj = $.parseJSON(dataString);
$.ajax({
type : "POST",
url : loc,
cache : false,
data : obj,
That's supposing you really need to build your string as you do. It's generally simpler to just build your object instead of making a json string, parsing it then asking jQuery to serialize it again.
I think you shoud pass json object NOT json array.
var dataString = '{"comment":"test"}';
//dataString = '[' + dataString + ']'; //delete this, NOT array
var obj = $.parseJSON(dataString);
console.log(obj);
$.ajax({
type : "POST",
url : url,
cache : false,
data : obj,
contentType:"application/json; charset=utf-8",
dataType:"json",
success : function(data) {
console.debug("After success");
}
});
I am sending a request by post using jquery ajax, but some of the words i send have + to join words like: HTA+HIPERAQUITISM+DBLR, the php recieve HTA HIPERAQUITISM DBLR changing the + by blank spaces, i post the code below. help!
function getItemInfo(itemName, itemField, itemComparative, itemTable){
var result = "";
var nombreItem = itemName;
var campoItem = itemField;
var comparativeItem = itemComparative;
var tableItem = itemTable;
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+nombreItem+
'&campo='+campoItem+
'&comparador='+comparativeItem+
'&tabla='+tableItem,
success: function(data) {
result = data.toString();
},
failure: function() {
result = "";
}
});
return result;
}//end function
This is because in a URL + means space.
You'll need to URL encode the data first before adding it to the query string.
You can use the encodeURIComponent() function to encode your value before adding it to the query string.
Once your PHP code picks it up you can then decode the value with the urldecode function
So your code should update to something like this:
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+encodeURIComponent(nombreItem)+
'&campo='+encodeURIComponent(campoItem)+
'&comparador='+encodeURIComponent(comparativeItem)+
'&tabla='+encodeURIComponent(tableItem),
Your code seems to be correct. You are passing those variables one by one (nombreItem, campoItem, comparativeItem and tableItem). So I don't really understand what you say is not working.
A suggestion to make passing data easier:
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php',
data : ({ fun : consul_item,
nombre_item : nombreItem,
campo : campoItem,
comparador : comparativeItem,
tabla : tableItem }),
success: function(data) {
result = data;
},
failure: function() {
result = "";
}
});
If you want to pass all your info as one textual string you should do:
...
data: ({ test : consul_item + '+' + nombreItem + '+' + campoItem + '+' + comparativeItem + '+' + tableItem }),
...