RESOLVED! see solution at bottom of this post...I have been stuck on this problem for about 2 days now and it's starting to get to me. I am trying to POST a Json array to my node server (cross-domain) and insert it to a cloudant db. This question is more about just getting the json over in the correct format. Here is my client side json and ajax:
function stress(){
var start = new Date().getTime();
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: JSON.stringify(products),
dataType: 'json',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
}
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
My Node.js server side:
exports.create = function(req, res) {
var data = req.body;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
//var parsed = JSON.parse(data);
var msg = {};
for(product in data){
db.insert(data[product], function (err, body, headers) {
if (!err) {
msg.msg = 'success!';
console.log(JSON.stringify(msg);
}
else {
msg.msg = 'Error on insert, maybe the item already exists: ' + err
console.log(JSON.stringify(msg);
}
});
}
}
I have tried a multitude of different things. What I basically want is a object on the server side that I can iterate through and insert to the cloudant database, each as a separate doc. I have tried many combinations of JSON.stringify and JSON.parse. using parse has given no luck as I get an error saying SyntaxError: Unexpected token o which I read that means it is already an object, but I cannot access data in any way ( data[0], data.name, data[0].name, nothing on the server side). I have also tried sending the json from the client side in different ways (in ajax - data: JSON.stringify({prod:products}) and still no luck.
Having the json on the server side (same as products above) inserts the docs in the correct order, the problem is when I sent that same json over a ajax post and to a cross-domain server. I cannot get that json out. Any idea or help would be very appreciated, thanks
Solution:
I ended up putting the object into another array and using that to be sent to the server. Here is the working ajax in the client side, notice the data:{data:products} that's what did it for me. Also below is the products json and also how to access it on the nodejs server side.
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: {data:products},
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
Here is how to access it on the server side. Keep in mind this is all for cross-domain Post, but should work otherwise.
exports.create = function(req, res) {
var body = req.body;
//body.data[0] will get you the first object in the json, in this case it will be the war room table.
//If you use console.log to see it make sure you JSON.stringify(body.data[0]) or else you wil see [Object] [Object]
Also very important to include this in your server/app.js The extended: true part is important. Example
app.use(bodyParser.urlencoded({ extended: true }));
You are stringifying the json data before sending it to the node server, try only
data:products You will also need the node module body-parser using it you will be able to access POSTed data through ajax, see this answer also
I am new to ajax. Please check if this helps. I think I had a similar problem which is solved now.
Please see the answer posted by me
How to send array of arrays as data in $.ajax()?
Related
I'm using this code to create a Twitter Insight app in Bluemix. However, I can't find any documentation on how to increase the number of tweets retrieved by the API. I tried using size and count as parameter in the query but without result. Is it possible to get more tweets?
$.ajax({
url:'/api/search/',
type: 'GET',
contentType:'application/json',
data: {
q: term,
size: 100
},
success: function(data) {
// do stuff
},
error: function(xhr, textStatus, thrownError) {
// do error stuff
}
});
The server side code you are using has a hard coded value of 20 for the number of tweets returned in the app.js file:
var MAX_TWEETS = 20;
// callback - done(err, data)
function insightRequest(path, query, done) {
request({
method: "GET",
url: insight_host + '/api/v1/messages' + path,
qs: {
q: query,
size: MAX_TWEETS
}
}, function(err, response, data) {
You have to modify that value for the max number you want to return, or make a parameter you can pass to function.
I have a JSON File, giving by vendor
{"html": "\n<link href=\"//apply.fundingoptions.com/static/msmclone/css/oembed-v3.css\" rel=\"stylesheet\">\n<script type=\"text/javascript\">\n var __raconfig = __raconfig || {};\n __raconfig.uid = '53302e56328ff';\n __raconfig.action = 'track';\n (function () {\n var ra = document.createElement('script');\n ra.type = 'text/javascript';\n ra.src = ('https:'==document.location.protocol?'https://':'http://')\n +'www.ruleranalytics.com/lib/1.0/ra-bootstrap.min.js';\n var s = document.getElementsByTagName('script')[0];\n s.parentNode.insertBefore(ra, s);\n }());\n</script>\n\n<div id=\"oembed-widget-container\" class=\"oembed-widget-container\">\n <div class=\"callout\">Initialising Finance Finder...</div>\n</div>\n<script type=\"text/javascript\">\n \n var widget_affiliate_id = 10;\n \n \n var widget_continue_url = \"//apply.fundingoptions.com/continue/\";\n \n \n var widget_submission_url = \"//apply.fundingoptions.com/oembed/submit/\";\n \n \n var widget_match_url = \"//apply.fundingoptions.com/match/\";\n \n \n var widget_title = \"Your funding options\";\n \n</script>\n<script src=\"//apply.fundingoptions.com/static/oembed/oembed-v4.js\"></script>\n\n",
"title": "Funding Options Finance Finder",
"version": 0,
"type": "rich",
"width": 500,
"height": 400
}
and I am parsing it on a webpage using this method
$.ajax({
type: 'GET',
url: 'json/data.json',
data: { get_param: 'value' },
dataType:'json',
success: function (data) {
var names = data
$('#summary').html(data.html);
}
});
But in the end , its show something like that on webpage:
as I am implementing it first time , I am not sure its my bad or json is corrupt or what else.
Looks like this is a Cross Origin Resource Sharing issue.
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Check your browser console and look at the error you are getting when you try to load the page. It should say something similar to:
XMLHttpRequest cannot load http://apply.fundingoptions.com/match/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Because the data you are requesting is not on the same server as you you are being denied access.
It looks like the error is happening when the following request is made in the oembed-v4.js library:
jQuery.ajax({
url: that.match_url,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR) {
that.data = data;
if (data['next_question'] == null) {
that.showActions();
that.$spinnerElement.removeClass('fa-cog');
that.$spinnerElement.addClass('fa-check');
} else {
that.drawQuestion();
}
},
error: function(jqXHR, textStatus, errorThrown) {
that.displayError();
},
complete: function() {
that.toggleSpinner(false);
}
});
The vendor may need to enable Cross Origin Resource Sharing on their end from your domain.
Here is a working example of the jQuery Ajax call:
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
dataType:'json',
success: function (resp) {
console.log(resp)
var names = resp.title
$('#summary').html(names);
},
error: function (resp) {
console.log('error')
}
});
You can edit this to match your data. Make sure that the url is correct, you can try:
'./json/data.json'
You JSON is parsed correctly according to: https://jsonlint.com/
So it must be the URL.
I am making an AJAX post to a Jersey Resource. I build an image and return it. The issue is, no matter what status I return, Ajax thinks it is an error. I can actually use the error message (via error.responseTest) and it works fine. But it is ugly. What do I return to make it a success? I have returned OK(200), Accepted(202) and Created(201). All of them give me an error message but in my Console Network tab, I get a success (green with the proper status).
I am returning it like this:
return Response.status(Response.Status.ACCEPTED).entity(image).header('Content-Type',"image/png").build();
My JS code:
$.ajax( Monocle.config.Sightline.jobUrl + "/sightline", {
type: "POST",
processData: false,
data: JSON.stringify({
Lat1: Monocle.Sightline.BBOX(feature,2),
Long1: Monocle.Sightline.BBOX(feature,1),
Lat2: Monocle.Sightline.BBOX(feature,4),
Long2: Monocle.Sightline.BBOX(feature,3),
OrgLat:observerCoords[0].lat,
OrgLong:observerCoords[0].lon,
ObHeight: feature.attributes.observerHeight,
TargHeight: feature.attributes.targetHeight,
OuterRadius: feature.attributes.outerRadius,
LVA: feature.attributes.lowerVertAngle,
UVA: feature.attributes.upperVertAngle,
sAzimuth: feature.attributes.startAzimuth,
eAzimuth: feature.attributes.endAzimuth,
outputType: "MAX"
}),
contentType: "application/json",
dataType: "json",
success: function( results ){
var graphic = new OpenLayers.Layer.Image(
Monocle.currentWidget.name + " Destination " + featurenum,
"data:image/png;base64," + results,
new OpenLayers.Bounds(Monocle.Sightline.BBOX(feature,1), Monocle.Sightline.BBOX(feature,2), Monocle.Sightline.BBOX(feature,3),Monocle.Sightline.BBOX(feature,4)),
new OpenLayers.Size(580, 288),
{ isBaseLayer: false,
opacity: 0.3,
displayOutsideMaxExtent: true
});
feature.legionObject = graphic;
graphic.relatedlayer = Monocle.currentWidget.name + " Destination " + featurenum;
Monocle.Map.map.addLayer(graphic);
},
error: function(errMsg) {
// TODO: really handle any errors
}
});
Setting dataType: "json", means that your response is to be json which it isn't that would cause the error so just remove it.
Also is your image data has to be base64 encoded to make a data uri.
My question is when I use jQuery ajax get, I am getting data at response body however it doesn't pass into success function. How can I make it work?
I am making an ajax put but it doesn't work at ie9 (works on other browsers) so I changed it like that just for test:
$.ajax({
async : false,
type: 'PUT',
contentType: 'application/json',
url:updateUrl + "?_" + new Date().getTime(),
data: JSON.stringify(model),
cache: false,
dataType: "json",
dataFilter: function(data) {
var resp = eval('(' + data + ')');
return resp;
},
success: function(data, status, xhr) {
alert("success> " + data.property);
alert(typeof data);
r = resultResponse(data);
},
error: function(data, status, xhr) {
alert("error> " + data.responseText);
try {
r = error($.parseJSON(data.responseText));
} catch (err) {
//Handle error
}
}
});
data is alerting as undefined. My put data is sending correctly, my server side works well and send response to client however I get undefined instead of data. After some tests I realized the problem:
When I capture network communication packets at ie 9 response body is what I want. However success function can not handle it. If needed, I can give more information about my server(I could make it work when I write the data to response instead of using jackson json mapper at Java - it was working and the only difference was that was not included ta working version at response headers:
Key Value
Content-Type application/json;charset=UTF8 )
I think that the problem can be handle at client side, I think not with server side.
Any ideas?
EDIT: I tried that style:
$.ajax({url: "/url",
dataType: "text",
success: function(text) {
json = eval("(" + text + ")");
// do something with JSON
}
});
However response header is still:
Key Value
Content-Type application/json;charset=UTF8
The problem was wrong charset. It was UTF( instead of UTF-8).
What are my mistakes, why do I get the "object expected" error, and, eventually, how does one debug jScript ?
I am new to Dynamics CRM and I would like to do a small customisation, which seem to require jScript. The instance (version 2011) is used mostly to manage client support.
There are 2 custom entities with relationships: FundLegalEntity --> SubFund
The Case (Incident) form is linked to the FundLegalEntity and the SubFund.
When user enters a SubFund I would like to have the FundLegalEntity filled automatically (if empty).
My question was: how do I code that ?
With the help of this great tutorial, and the very usefull oData Tool, and great help (below) from user #dub, here is my latest code:
function recalcParent()
{
var lookupValue = Xrm.Page.getAttribute("new_subfundid").getValue();
var subFundId= lookupValue[0].id;
// alert(subFundId);
var request = Xrm.Page.context.getServerUrl() +
"/xrmServices/2011/OrganizationData.svc/new_subfundSet?" +
"$select=new_LegalEntityId&" +
"$filter=new_subfundId eq guid'"+ subFundId+ "'";
// alert(request);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend:
function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
alert(result);
var parentFundLookup = [{ entityType : "new_fund", id : result.LegalEntityId, name : result.FundLegalEntity}];
// Set the value of the parent fund lookup
},
error:
function (XmlHttpRequest, textStatus, errorThrown)
{
alert('Failed');
}
});
}
I have no more errors, the first 2 alerts (commente out) are giving me correct results.
THe 3rd alert displays "object Object", and the control I expect to update is not updated.
Any hint please ? I suppose the last problem is in the var parentFundLookup = line...
I am a bit confused by all these different names.
Thanks !
Edit:
It's nearly working now: when I modify the sub-fund in the Incident, the Legal Entity gets updated with the correct legal entity name, but the text box has a strange aspect, and the icon at the left of the text box is strange as well. Here is the latest bit of code:
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
//alert(result.new_LegalEntityId.Name);
var parentFundLookup = [{ entityType : "new_LegalEntity", id : result.new_LegalEntityId.Id, name : result.new_LegalEntityId.Name}];
Xrm.Page.getAttribute("new_fundlegalentityid").setValue(parentFundLookup);
},
I suspect that the problem lies in the entityType : "new_LegalEntity", but I don't know what to put in there. Any clue on this ? What does that represent ?
Here is a screenshot of the Legal Entity after the Sub-Fund is updated and the script has run.
You can use the Rest endpoint from your script to retrieve data from the organization service. Here's an example to get you started. You can also look at the SDK documentation there's a lot of useful information there.
var subfundid; // get the id from the lookup
var request =
Xrm.Page.context.getServerUrl() +
"/XRMServices/2011/OrganizationData.svc/new_subfundSet?" +
"$select=ParentId&" +
"$top=1&" +
"$filter=new_subfundId eq guid'"+ subfundid + "'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend:
function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
var parentFundLookup = [{ entityType : "new_fund", id : result.ParentId, name : result.FundName}];
// Set the value of the parent fund lookup
},
error:
function (XmlHttpRequest, textStatus, errorThrown)
{
alert('Failed');
}
});
Since this code uses JQuery, you'll need to add the JQuery library as a web resource and include it in your form. See CRM 2011 "$ is undefined"