JSONP Object Error - javascript

I am trying to make a cross domain request to send/recieve some data. I can't get past the object error. Before I was getting the No Transport Error but adding Query.support.cors = true; solved this issue.
var url = "http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract";
$.ajax({
type: 'GET',
url: url,
data: 'tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation',
datatype: "jsonp",
contentType: "application/json",
success: function (response) {
alert(response.data);
},
error: function (error) {
alert(error.statusText);
}
});
If I type the url out in a browser:
http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract?&tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation
I get the correct response.
{"d":{"__type":"ClientSideData:#ProdResourceToolService","details":"9","product":"Some Product","result":"1","site":"Somewhere, SD","systime":"2\/6\/2013 2:50:20 PM","team":"0000000000","tool":"1","user":"username"}}
When I use ajax it does not submit it to the database or return data, just object error. Does anyone have any suggestions on how to get around this?
I should also specify if I remove http://CROSSDOMAINSERVER:PORT/ from var url when debugging locally I get the correct json response. Why does cross domain not work?

This is your current response:
{
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
}
This is a valid JSON string. However, its not valid JSONP. If possible, make your service wrap the json in a function:
responseFunc({
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
});
And in your $.ajax() call, add a property: jsonpCallback: 'responseFunc'.
Also, I would suggest passing the data as an object:
data: { tool: 1, product: 'Some Product' } //etc...
If you can access the service from the serverside without any issues you could create a httphandler (.ashx for example) and let it generate the JSON for you. Then you wouldn't have to deal with the cross domain issues on the client side.

Related

Get Data from an Object in the Browser

How can I get an object from my browser / get the data stored in the object from my browser?
The user presses submit button after filling out a form with a bad credit card number (a scenario I am testing), which triggers a jQuery function SubmitAPI() (code below).
Google Chrome console displays 400 Bad Request error (because the credit card number is bad) as well as an API Response holding the object with the declined credit card data (response below)
I specifically need to grab "response_type":"D","response_code":"U20","response_desc":"INVALID CREDIT CARD NUMBER" because I want to display this error message to the user. How can I do this in jQuery?
I have tried for hours to figure this out. I use response.response.response_type to get the Response Type when the transaction is successful (approved credit card). However with a bad credit card number, this same attempt results in "undefined". So, instead, I just want to grab the data from my Google Chrome browser that managed to get the Response Code response.
PART 1: jQuery Code (Directly from the API's documentation - except I changed the credit card to be a bad number)
function SubmitAPI() {
var settings = {
"url":
"https://sandbox.forte.net/api/v3/organizations/org_ID/locations/loc_ID/transactions",
"method": "POST",
"headers": {
"X-Forte-Auth-Organization-Id": "org_ID",
"Authorization": "ID",
"Content-Type": "application/json"
},
"data": JSON.stringify({ "action": "sale", "authorization_amount": 102.45, "subtotal_amount": 99.95, "billing_address": { "first_name": "Jennifer", "last_name": "McFly" }, "card": { "card_type": "visa", "name_on_card": "Jennifer McFly", "account_number": "41111sdf11111111", "expire_month": "12", "expire_year": "2017", "card_verification_value": "123" } }),
};
$.ajax(settings).always(function (response) {
console.log(response);
});
}
PART 2: Console Response:
400 (Bad Request)
PART 3: Response Object in Browser:
{"location_id":"loc_241789","action":"sale","authorization_amount":102.45,"entered_by":"59ae172b3bd78bed493ecd5892975764","billing_address":{"first_name":"Jennifer","last_name":"McFly"},"card":{"name_on_card":"Jennifer McFly","last_4_account_number":"1111","masked_account_number":"****1111","expire_month":12,"expire_year":2017,"card_type":"visa"},"response":{"environment":"sandbox","response_type":"D","response_code":"U20","response_desc":"INVALID CREDIT CARD NUMBER"}}
Using error handler for the Ajax call and was able to get the error message with no issues.
var settings = {
"url": "https://sandbox.forte.net/api/v3/organizations/org_381529/locations/loc_241789/transactions",
"method": "POST",
"headers": {
"X-Forte-Auth-Organization-Id": "org_381529",
"Authorization": "Basic NTlhZTE3MmIzYmQ3OGJlZDQ5M2VjZDU4OTI5NzU3NjQ6ZWUwZTZiZDA4ZThlMWNhNWQ3MzUyNGU0ZWU5ZDFjNTg=",
"Content-Type": "application/json"
},
"data": JSON.stringify({
"action": "sale",
"authorization_amount": 102.45,
"subtotal_amount": 99.95,
"billing_address": {
"first_name": "Jennifer",
"last_name": "McFly"
},
"card": {
"card_type": "visa",
"name_on_card": "Jennifer McFly",
"account_number": "41111sdf11111111",
"expire_month": "12",
"expire_year": "2017",
"card_verification_value": "123"
}
}),
};
$.ajax(settings).error(function(xhr) {
console.log("Error", xhr.responseJSON.response.response_desc);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

firebase "long link is not parsable"

I want to shorten a longLink with firebase and the REST API but I get the following response and I don't know what is wrong:
Response:
{
"error": {
"code": 400,
"message": "Long link is not parsable: https://www.google.de [https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_parameters]",
"status": "INVALID_ARGUMENT"
}
}
And this is how I do it:
The Request: https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=(hereismyapikey)
the Body lookes like this:
{
"longDynamicLink": "https://www.google.de",
"suffix": {
"option": "SHORT"
}
}
I tried first with the real URL I want to shorten. Same error. Than with google and with and without the http(s). I'm out of options and hope somebody sees what I did wrong here.
EDIT: Full Postman request:
"item": [
{
"name": "shortLinks",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"longDynamicLink\": \"www.google.de\",\r\n \"suffix\": {\r\n \"option\": \"SHORT\"\r\n }\r\n}"
},
"url": {
"raw": "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=xxx",
"protocol": "https",
"host": [
"firebasedynamiclinks",
"googleapis",
"com"
],
"path": [
"v1",
"shortLinks"
],
"query": [
{
"key": "key",
"value": "xxx"
}
]
}
},
"response": []
}
]
You are using the simple method for creating dynamic link which is roughly equals to the manual creation of dynamic link : https://firebase.google.com/docs/dynamic-links/create-manually
In the docs if you see the link passed in example carefully you will see the pattern as below:
https://your_subdomain.page.link/?link=your_deep_link&apn=package_name[&amv=minimum_version][&afl=fallback_link]
So you should format the input link according to this or create using the parameters which has very good breakdown of parameters in json:
https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_parameters
Here is the api reference for firebase dynamic link creation from parameters:
https://firebase.google.com/docs/reference/dynamic-links/link-shortener#parameters
I find the JSON parameter method is easier.
var body = {
"dynamicLinkInfo": {
"dynamicLinkDomain": "yourcustom.page.link",
"link": fileUrl
},
"suffix": {
"option": "SHORT"
}
};
Then if you're using Node. The node-fetch package REST call would work like:
var fetchFileUrl = fetch(YOUR_SHORTLINK_URL, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
}).then(function(response){
return response.json();
});

Arrays in AJAX request JSON object data

I am sending a request to a Node/Express server using jQuery thats data is a JSON object containing an array:
var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}
var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: data,
dataType: 'json'
});
The request itself is working fine, however the server is reporting the data as:
{
name: 'James Jamesy',
'children[0][name]': 'Little James',
'children[0][age]': '4',
'children[1][name]': 'Medium James',
'children[1][age]': '6',
'children[2][name]': 'Graham',
'children[2][age]': '8'
}
Now I've figured out that I can get my desired result by instead stringifying the children array:
var data = {
"name": "James Jamesy",
"children": JSON.stringify([ ... ])
}
And then JSON.parse()ing it on the server.
However I am hoping someone can explain why the array is converted as it is in the request, and whether I should be handling this a different way? As in this instance converting the single array is fine, but going forward I might have semi-complex objects I'm looking to send to the server.
Thanks in advance!
EDIT: Additionally and strangely(?), if I send the JSON result back as the passed JSON, it works perfectly:
res.json(JSON.parse(req.body.categories));
The browser logs out the object and I can manipulate it perfectly fine.
You weren't passing a JSON string through ajax which is why you couldn't handle the data on the back end.
var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}
var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: JSON.stringify(data),
contentType: 'application/json', // for request
dataType: 'json' // for response
});

How to send JSON data to a java function from angularJS

I have a json like
var rules=[
{
"ruleId": "1234",
"version": "R1234",
"name": "Usage crossing 50MB",
"description": "Find usage more than 50mb",
"active": true,
"created_by": "Rahul",
"create_date": "2015-08-18",
"modified_date": "2015-08-22",
"modified_by": "Subho",
"category": {
"name": "High Usages Rule",
"id": "26"
}
]
Now I want to call a java page or function where i want to get these data so i put it on DB.
this is my controller
(function(){
"use strict";
angular
.module("RulesEngine")
.controller("RulesEditCtrl",
["rules","$state",RulesEditCtrl]);
function RulesEditCtrl(rules, $state){
var vm=this;
vm.rules=rules;
vm.submit=function(){
vm.rules.$save(function (data) {
toastr.success("Save Successful");
vm.ruleJson=data;
});
console.log(vm.ruleJson);
//in yhis vm.ruleJSON holds the the updated json. it prints fine in console.log
}
}
}());
I want to call a function using $ajax or $http.get() to call a function insertEntry() which is in a java page named ShowJson.java. please help me to call the function and send the data.
I tried
$.ajax({
url : "insertEntry?rule="+vm.ruleJson,
type: 'POST',
dataType : "json",
success : function(data) {
console.log("inserted");
},error : function(data) {
}
});
But its not working...

Correct way to write ColdFusion service to send json data and catch by angularjs

I'm Very stuck in this case when working all day :(. please help me.
I have website need using $http provider to call ColdFusion file from other domain.
let's say this is link to cfm file : http://xample.com/getStockCodesTest.cfm
this is may sample ColdFusion file:
<cfcontent
type="application/json"
/>
{
"items": [
{
"StockCode" : { "col": "Stock Code", "value": "0231" },
"Qty" : { "col": "Qty", "value": "DS" },
"QtyOn" : { "col": "Qty On", "value": "Branch" },
"QtyVal" : { "col": "Qty Val", "value": "200" },
"ReleasedDate" : { "col": "Released Date", "value": "0" },
"S" : { "col": "S", "value": "0" },
"Description" : { "col": "Description", "value": "adfasdf" },
}
]
}
this is angular code (i use coffeescript to write)
ajax = $http {
url: 'http://xample.com/getStockCodesTest.cfm'
method: 'JSONP'
params: {
callback: "JSON_CALLBACK"
}
}
ajax.success (data, status, headers, config) ->
console.log data
but when check firebug. it always return error:
so how can i have a correct way to write a test ColdFusion with content json like that and use angularjs to catch in to my web :(
I'm not exactly sure what you are asking. But I can tell you that you are getting the error because you have invalid JSON.
That comma, right there, remove it. It makes for invalid JSON.
You have to wrap your JSON with the input function name, when a JSONP call is made from AngularJS. That is the reason you see the error.
Example of JSONP response:
/xxx.cfm?_jsonp=angular.callbacks._0 --- request
//expected response is like this - a function from your coldfusion
angular.callbacks._0([{"StockCode" : { "col":...
Then it will work.

Categories

Resources