Sending and receiving data using Jquery - javascript

I am at basic level of application development.
I wanted to know how I can send and get this data with JQuery any new version.
I also want it to support all browsers.
I'm just using simple Ajax but I know it is possible with Jquery and im not able to figure it out.
function SendData() {
var data = "action=check&uid=" + uid + "&fbuid=" + fb_uid + ";
var url = "http://www.example.com/call.php";
var ajax = new AJAXInteraction(url, CheckRate);
ajax.doPost(data);
};
function CheckRate(Content) {
response = JSON.parse(Content);
Rate = response.stat.rate;
document['getElementById']('ERate')['value'] = Rate;
};
function AJAXInteraction(url, callback) {
var req = init();
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
if (callback) callback(req.responseText);
}
}
}
this.doGet = function () {
req.open("GET", url, true);
req.send(null);
}
this.doPost = function (str) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
req.send(str);
}
};
I am able to solve first part And still dont know rest:
function SendData(){
dataString = "action=check&uid=" + uid + "&fbuid=" + fb_uid + ";
url = "http://www.example.com/call.php";
jQuery.ajax({
type: "POST",
url: url,
data: dataString,
});
};
My problem is how i will read response
function CheckRate(Content) {
response = JSON.parse(Content);
Rate = response.stat.rate;
document['getElementById']('ERate')['value'] = Rate;
};

function SendData() {
dataString = "action=check&uid=" + uid + "&fbuid=" + fb_uid + ";
url = "http://www.example.com/call.php";
jQuery.ajax({
type: "POST",
url: url,
data: dataString, // sending data
success: function (data) {
CheckRate(data); // receiving data
}
});
};
// function body should looks like this
function CheckRate(Content) {
response = JSON.parse(Content);
Rate = response.stat.rate;
document['getElementById']('ERate')['value'] = Rate;
};

Related

Direct upload string to s3 from bootstrap modal not working

I observed a very strange behavior. If I set a button from web to upload string to S3, it works fine. But if I set a button from web to bring up a bootstrap modal, then from this modal I set a button to upload the string, it doesn't work.
Frontend is like below in both cases. The difference is whether clicking to run function 'saveToAWS' from web or from modal as 2-step-process, the latter returns xhr.status as 0.
function saveToAWS() {
var file = new File([jsonStr], "file.json", { type: "application/json" });
var xhr = new XMLHttpRequest();
var fn=file.name;
var ft = file.type;
xhr.open("GET", "/sign_s3_save?file-name=" + fn + "&file-type=" + ft);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log('signiture returned')
save_file(file, response.signed_request, response.url);
}
else {
alert("Could not get signed URL.");
}
}
};
xhr.send();
}
function save_file(file, signed_request, url) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', signed_request);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('200');
}
else {
alert('cannot upload file');
}
}
};
xhr.send(file);
}
Backend as Node.js, in order to get a signed URL:
app.get('/sign_s3_save', isLoggedIn, function (req, res) {
var fileName = req.query['file-name'];
var fileType = req.query['file-type'];
aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var ac = req.user._id;
var timenow = Date.now().toString();
var fileRename = ac + '/json/' + timenow + '.json';
var s3_params = {
Bucket: S3_BUCKET,
Key: fileRename,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function (err, data) {
if (err) {
console.log(err);
}
else {
var return_data = {
signed_request: data,
url: 'https://' + S3_BUCKET + '.s3.amazonaws.com/' + fileRename
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
Any suggestion, please?

How to write one javascript function to perform an ajax request without repeating to avoid code-smell without using JQuery library

i have a javascript code that uses objects and attributes to perform different ajax requests. i want to find a way that i can optimize my code to avoid repetition and code-smell. i have an object trip that has list which should fetch the details from the database and append to my servlet defined with a path ./trips/action/ . No JQuery needed
var trip = {
list: function(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
if(ajax.status == 200){
document.getElementById('ajax-content').innerHTML = ajax.responseText;
}
}
}
ajax.open("GET", "./trips/action", true);
ajax.send();
},
add: function(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
if(ajax.status == 200){
document.getElementById('ajax-content').innerHTML = ajax.responseText;
}
}
}
ajax.open("GET", "./trip/addTrip.jsp", true);
ajax.send();
},
save: function(){
var me = this;
var ajax = new XMLHttpRequest();
var depatureDate = document.getElementById('depatureDate').value;
var arrivalDate = document.getElementById('arrivalDate').value;
var route = document.getElementById('route').value;
var vehicle = document.getElementById('vehicle').value;
var price = document.getElementById('price').value;
var params = 'depatureDate=' + encodeURIComponent(depatureDate)
+ '&arrivalDate=' + encodeURIComponent(arrivalDate)
+ '&route=' + encodeURIComponent(route)
+ '&vehicle=' + encodeURIComponent(vehicle)
+ '&price=' + encodeURIComponent(price);
console.log(params);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
if(ajax.status == 200){
me.list();
}
}
}
ajax.open("POST", "./trips/action/add", true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(params);
}
}
You can create utility functions:
var utils = {
ajax: function(url, method, params, callback) {
if (typeof callback == 'undefined') {
callback = arguments[1];
params = null;
}
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4){
if (ajax.status == 200){
if (typeof callback == 'function') {
callback(ajax.responseText);
}
}
}
}
ajax.open(method, url, true);
if (params) {
ajax.send(params);
} else {
ajax.send();
}
},
get: function(url, params, callback) {
this.ajax(url, 'GET', params, callback);
},
post: function(url, params, callback) {
this.ajax(url, 'POST', params, callback);
}
};
and you can use it in your code:
var trip = {
list: function(){
util.get("./trips/action", function(data) {
document.getElementById('ajax-content').innerHTML = data;
});
},
...
};

consuming API JSon calls through TVJS-tvOS

I am trying to play with tvOS, and I have small question regarding handling json call. I have to get some data through an API, let's say for sake of test that I am calling this link
http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json
I tried to use this function with some modification
function getDocument(url) {
var templateXHR = new XMLHttpRequest();
templateXHR.responseType = "json";
templateXHR.open("GET", url, true);
templateXHR.send();
return templateXHR;
}
but didn't work out. Any hints or help ?
If I need to use NodeJS, how can I do that ?
This is one that I got working. It's not ideal in many respects, but shows you something to get started with.
function jsonRequest(options) {
var url = options.url;
var method = options.method || 'GET';
var headers = options.headers || {} ;
var body = options.body || '';
var callback = options.callback || function(err, data) {
console.error("options.callback was missing for this request");
};
if (!url) {
throw 'loadURL requires a url argument';
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
try {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback(null, JSON.parse(xhr.responseText));
} else {
callback(new Error("Error [" + xhr.status + "] making http request: " + url));
}
}
} catch (err) {
console.error('Aborting request ' + url + '. Error: ' + err);
xhr.abort();
callback(new Error("Error making request to: " + url + " error: " + err));
}
};
xhr.open(method, url, true);
Object.keys(headers).forEach(function(key) {
xhr.setRequestHeader(key, headers[key]);
});
xhr.send();
return xhr;
}
And you can call it with the following example:
jsonRequest({
url: 'https://api.github.com/users/staxmanade/repos',
callback: function(err, data) {
console.log(JSON.stringify(data[0], null, ' '));
}
});
Hope this helps.
I tested this one out on the tvOS - works like a charm with jQuery's syntax (basic tests pass):
var $ = {};
$.ajax = function(options) {
var url = options.url;
var type = options.type || 'GET';
var headers = options.headers || {} ;
var body = options.data || null;
var timeout = options.timeout || null;
var success = options.success || function(err, data) {
console.log("options.success was missing for this request");
};
var contentType = options.contentType || 'application/json';
var error = options.error || function(err, data) {
console.log("options.error was missing for this request");
};
if (!url) {
throw 'loadURL requires a url argument';
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.timeout = timeout;
xhr.onreadystatechange = function() {
try {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (xhr.responseType === 'json') {
success(null, xhr.response);
} else {
success(null, JSON.parse(xhr.responseText));
}
} else {
success(new Error("Error [" + xhr.status + "] making http request: " + url));
}
}
} catch (err) {
console.error('Aborting request ' + url + '. Error: ' + err);
xhr.abort();
error(new Error("Error making request to: " + url + " error: " + err));
}
};
xhr.open(type, url, true);
xhr.setRequestHeader("Content-Type", contentType);
xhr.setRequestHeader("Accept", 'application/json, text/javascript, */*');
Object.keys(headers).forEach(function(key) {
xhr.setRequestHeader(key, headers[key]);
});
if(!body) {
xhr.send();
} else {
xhr.send(body);
}
return xhr;
}
Example queries working on Apple TV:
var testPut = function(){
$.ajax({
type: 'PUT',
url: url,
success: successFunc,
error: errFunc,
dataType: 'json',
contentType: 'application/json',
data: data2
});
}
var testGet = function(){
$.ajax({
dataType: 'json',
url: url,
success: successFunc,
error: errFunc,
timeout: 2000
});
}
var getLarge = function(){
$.ajax({
dataType: 'json',
url: url,
success: successFunc,
error: errFunc,
timeout: 2000
});
}
Did you call your function in the 'App.onLaunch'
App.onLaunch = function(options) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json';
var doc = getDocument(url);
console.log(doc);
}
Might be worth looking at https://mathiasbynens.be/notes/xhr-responsetype-json
I came across this question looking to accomplish the same thing, and was inspired by #JasonJerrett's answer, but found it a bit lacking because in my instance I am using an XML template built in Javascript like this:
// Index.xml.js
var Template = function() {
return `very long xml string`;
};
The issue is that you can't perform the XHR request inside the template itself, because the template string will be returned back before the XHR request actually completes (there's no way to return data from inside an asynchronous callback). My solution was to modify the resource loader and perform the XHR request there, prior to calling the template and passing the data into the template function:
ResourceLoader.prototype.loadResource = function(resource, dataEndpoint, callback) {
var self = this;
evaluateScripts([resource], function(success) {
if (success) {
// Here's the magic. Perform the API call and once it's complete,
// call template constructor and pass in API data
self.getJSON(dataEndpoint, function(data) {
var resource = Template.call(self, data);
callback.call(self, resource);
});
} else {
var title = "Failed to load resources",
description = `There was an error attempting to load the resource. \n\n Please try again later.`,
alert = createAlert(title, description);
Presenter.removeLoadingIndicator();
navigationDocument.presentModal(alert);
}
});
}
// From: https://mathiasbynens.be/notes/xhr-responsetype-json
ResourceLoader.prototype.getJSON = function(url, successHandler, errorHandler) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
Then the template function needs to be modified to accept the incoming API data as a parameter:
// Index.xml.js
var Template = function(data) {
return 'really long xml string with injected ${data}';
};
You need to implement the onreadystatechange event on the XHR object to handle the response:
templateXHR.onreadystatechange = function() {
var status;
var data;
if (templateXHR.readyState == 4) { //request finished and response is ready
status = templateXHR.status;
if (status == 200) {
data = JSON.parse(templateXHR.responseText);
// pass the data to a handler
} else {
// handle the error
}
}
};
If you want to call the request on app launch, just add in application.js:
App.onLaunch = function(options) {
var javascriptFiles = [
`${options.BASEURL}js/resourceLoader.js`,
`${options.BASEURL}js/presenter.js`
];
evaluateScripts(javascriptFiles, function(success) {
if(success) {
resourceLoader = new ResourceLoader(options.BASEURL);
var index = resourceLoader.loadResource(`${options.BASEURL}templates/weatherTemplate.xml.js`, function(resource) {
var doc = Presenter.makeDocument(resource);
doc.addEventListener("select", Presenter.load.bind(Presenter));
doc.addEventListener('load', Presenter.request);
navigationDocument.pushDocument(doc);
});
} else {
var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files.");
navigationDocument.presentModal(errorDoc);
}
});
}
In presenter.js add a method:
request: function() {
var xmlhttp = new XMLHttpRequest() , method = 'GET' , url = 'your Api url';
xmlhttp.open( method , url , true );
xmlhttp.onreadystatechange = function () {
var status;
var data;
if (xmlhttp.readyState == 4) {
status = xmlhttp.status;
if (status == 200) {
data = JSON.parse(xmlhttp.responseText);
console.log(data);
} else {
var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files.");
navigationDocument.presentModal(errorDoc);
}
}
};
xmlhttp.send();
},

Dynamically Hide Home Button in CRM 2015 using Ribbon Workbench not Working

I am creating a custom Enable Rule to hide "Import" button in my custom entity in Ribbon Workbench. Here is my JS code:
function ShowHideButton() {
var context;
var serverUrl;
var UserID;
var ODataPath;
var toReturn;
context = Xrm.Page.context;
serverUrl = context.getClientUrl();
UserID = context.getUserId();
ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var retrieveUserReq = new XMLHttpRequest();
retrieveUserReq.open("GET", ODataPath + "/SystemUserSet(guid'" + UserID + "')", true);
retrieveUserReq.setRequestHeader("Accept", "application/json");
retrieveUserReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveUserReq.onreadystatechange = function () {
toReturn = retrieveUserReqCallBack(this);
};
retrieveUserReq.send();
return toReturn;
}
function retrieveUserReqCallBack(retrieveUserReq) {
var retrievedUser = this.parent.JSON.parse(retrieveUserReq.responseText).d;
var retrievedValue = retrievedUser.BusinessUnitId;
var id = retrievedValue.Id;
var refIdAdmin;
var refIdTL;
var refMember;
refIdAdmin = "6EF4BCC3-5608-E511-9415-22000A93809E";
refIdTL = "CCFE0C41-D208-E511-9416-22000A93809E";
refMember = "1010FC5F-2D2C-E511-941A-22000AA400C9";
if (id.toUpperCase() == refIdAdmin) {
return true;
}
else if (id.toUpperCase() == refIdTL) {
return true;
}
else if (id.toUpperCase() == refMember) {
return true;
}
else {
return false;
}
}
can you please help me fix the code so that Ribbon Workbench is able to read what I want to return?
You're making async request and that is the problem your toReturn is null when the rule is validated
var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false); // false makes the request synchronous
request.send(null);
if (request.status === 200) {
console.log(request.responseText);
}

How to query for Image saved in records Annotation using Javascript in CRM Online 2013

I have one image attached with each record in my entity. I want to show these images in the records in a web resource just like a record picture. I am using the following code:
function GetData(){
// var base64image = document.getElementById('image').src.substr(document.getElementById('image').src.indexOf('base64')+7);
var recordId = window.parent.Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "XRMServices/2011/OrganizationData.svc";
var objAnnotation = new Object();
var ODATA_EntityCollection = "/AnnotationSet";
var temp= "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
var result =serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + temp;
// Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(objAnnotation);
// Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: result ,
//data: jsonEntity,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function(status){
alert("success paa jee!!");
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
}
});
}
</script>
But I get an error $ is undefined when I reach the Ajax part. Basically every record has one Image in its notes attached to the entity's record and I want to show this image in a web resource as a record picture.
I am open to suggestions if there is a better/another way.
EDIT: I have edited the code and have updated the ODATA url.
In CRM 2011, I have used two Custom Aspx pages to show, the attached image.
Page 1: AccountImage.aspx have the following Control:
<asp:Image ID="IMG_Logo" runat="server" Height="50px" ImageUrl="AccountImageForm.aspx" Visible="false" />
In AccountImage.aspx On PageLoad
if (Request.QueryString["id"] != null)
{
Id = new Guid(Request.QueryString["id"]);
if (!IsPostBack)
{
ResetCache();
}
ShowImages();
}
The ShowImages() functions has below code:
function ShowImages()
{
IMG_Logo.Visible = false;
QueryExpression query = new QueryExpression("annotation");
query.Criteria.AddCondition("objectid", ConditionOperator.Equal, Id);
query.Criteria.AddCondition("mimetype", ConditionOperator.In, new string[] { "image/x-png", "image/pjpeg", "image/png", "image/jpeg" });
query.Criteria.AddCondition("subject", ConditionOperator.NotEqual, "membershipcardthumbnail");
query.Criteria.AddCondition("subject", ConditionOperator.NotEqual, "membershipcardimage");
query.ColumnSet = new ColumnSet(true);
EntityCollection AllLogoImageNotes = Common.Common.RetrieveMultiple(query);
if (AllLogoImageNotes.Entities.Count > 0)
{
foreach (Entity Note in AllLogoImageNotes.Entities)
{
if (Note.Attributes.Contains("subject") && Note.Attributes.Contains("documentbody"))
{
if (Note["subject"].ToString().ToLower() == "accountlogoimage")
{
HttpRuntime.Cache.Remove("AccountLogoImage");
HttpRuntime.Cache.Remove("AccountLogoImageType");
HttpRuntime.Cache.Add("AccountLogoImage", Convert.FromBase64String(Note["documentbody"].ToString()), null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.Normal, null);
HttpRuntime.Cache.Add("AccountLogoImageType", Note["mimetype"].ToString(), null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.Normal, null);
IMG_Logo.ImageUrl = "AccountImageForm.aspx" + "?time=" + DateTime.Now.ToString();
IMG_Logo.Visible = true;
}
}
}
}
}
As you can see, the line below:
IMG_Logo.ImageUrl = "AccountImageForm.aspx" + "?time=" + DateTime.Now.ToString();
In AccountImageForm.aspx write below code:
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
if (HttpRuntime.Cache["AccountLogoImage"] != null)
{
Response.ContentType = HttpRuntime.Cache["AccountLogoImageType"].ToString();
byte[] data = (byte[])HttpRuntime.Cache["AccountLogoImage"];
Response.BinaryWrite(data);
}
}
In ODATA you can do the following:
retrieveImages("/AnnotationSet?$select=DocumentBody,MimeType&$filter=ObjectId/Id eq guid'" + Xrm.Page.data.entity.getId()+ "'", function (JsonObject) {
if (JsonObject != null) {
// debugger;
var ByteString= JsonObject[0].DocumentBody;
var MimeType = JsonObject[0].MimeType
}
function retrieveImages(query, SuccessFunc) {
var retrieveRecordsReq = new XMLHttpRequest();
var ODataPath = Xrm.Page.context.getServerUrl() + "/xrmservices/2011/OrganizationData.svc";
retrieveRecordsReq.open('GET', ODataPath + query, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
if (this.status == 200) {
this.onreadystatechange = null; //avoids memory leaks
var data = JSON.parse(this.responseText, SDK.REST._dateReviver);
if (data && data.d && data.d.results)
SuccessFunc(JSON.parse(this.responseText, SDK.REST._dateReviver).d.results);
}
else {
alert(SDK.REST._errorHandler(this));
}
}
};
retrieveRecordsReq.send();
}

Categories

Resources