I need to call a cloud call in one parse application from the cloud of another parse application through the Rest API.
For this I have this code now. However, I always get the error: com.parse.ParseException: ReferenceError: XMLHttpRequest is not defined at main.js:12:20. (this line is referring to the line where the XMLHttpRequest is initialized). My code for this is:
var url = "https://api.parse.com/1/functions/signUp";
var myObj = new Object();
myObj.age = 45;
myObj.email = "test#gmail.com";
myObj.password = "testpw";
var client = new XMLHttpRequest();
client.open("POST", url);
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.setRequestHeader("X-Parse-Application-Id", "xxx");
client.setRequestHeader("X-Parse-REST-API-Key", "xxx");
client.send(JSON.stringify(myObj));
Since this code is executed in the Parse cloud, I think the problem is that the XMLHttpRequest isn't constructed correctly. Could that be?
Is this even possible with Parse, calling a cloud call from a parse application through the rest-api from the cloud from another parse application?
You can make http calls with Parse.Cloud.httpRequest()
Parse.Cloud.httpRequest({
url: 'https://api.parse.com/...',
headers: {
'Content-Type':'application/json',
'X-Parse-Application-Id':'...',
'X-Parse-REST-API-Key':'...'
},
method: 'POST',
body: JSON.stringify(myObj)
}).then(function(response) {
console.log(response);
}, function(err) {
console.log(err);
});
Give that a shot. re: https://parse.com/docs/cloud_code_guide#networking
You can probably skip the JSON stringify and just pass in myObj.
Related
I've designed a web app that posts order information to Google Sheets via HTTP POST and Google Apps Script. However, I am struggling to POST and extract the order information from the body JSON. I have tried 2 different methods and they both output the similar information but with the same data type - FileUpload. I've even attempted to import it as parameters as FormData() but repeatedly appending parameters didn't feel quite right.
Method 1
function method1() {
var xml = new XMLHttpRequest();
var data = JSON.stringify({ firstName: "Jay", lastName: "Smith" });
xml.open("POST", url, true);
/* xml.setRequestHeader("Content-type", "application/json"); */
xml.onreadystatechange = function () {
if (xml.readyState === 4 && xml.status === 200) {
alert(xml.responseText);
}
};
xml.send(data);
}
Output
{postData=FileUpload, contextPath=, contentLength=38.0, parameters={}, parameter={}, queryString=}
Notice how the setRequestHeader() function is commented. No output would occur if it was uncommented making the content type set to JSON. Why will it not work?
Method 2
function method2() {
const body = {
firstName: "Jay",
lastName: "Smith",
};
const options = {
method: "POST",
body: JSON.stringify(body),
};
fetch(url, options).then((res) => res.json());
}
Output
{contextPath=, parameters={}, parameter={}, queryString=, postData=FileUpload, contentLength=38.0}
Method 3 (Should I even consider this?)
function method3() {
const formData = new FormData();
formData.append("firstName", "Jay");
formData.append("lastName", "Smith");
fetch(url, {
method: "POST",
body: formData,
}).then((res) => res.json());
}
Output
{contentLength=243.0, parameter={firstName=Jay, lastName=Smith}, queryString=, contextPath=, parameters={lastName=[Ljava.lang.Object;#6c4aece6, firstName=[Ljava.lang.Object;#3c461e46}}
The content length is considerably larger... this does not seem like an effective concept.
Google Apps Script doPost() Function
function doPost(e) {
const sheet = SpreadsheetApp.openById(SHEETID).getSheetByName('Testing Inputs');
sheet.getRange(3,1).setValue(e); // To display POST output
const data = JSON.parse(request.postData.contents)
sheet.getRange(5,1).setValue(data['firstName']) // Not writing "Jay"?
sheet.getRange(5,2).setValue(data['lastName']) // Not writing "Smith"?
}
In general, it appears data is coming through as body message content judging by the contentLength output but is it not JSON considering the postData is FileUpload? That may cause my Apps Script nor to be able to extract it right? Also, I thought I read that using fetch() is considerably better than using XMLHttpRequest() so should I be using my Method 2? Still not sure what am I doing wrong to populate it in individual cells in sheets using Apps Script?
Any help is appreciated!
Output Using sheet.getRange(3,1).setValue(JSON.stringify(e))
{"parameter":{},"postData":{"contents":"{\"firstName\":\"Jay\",\"lastName\":\"Smith\"}","length":38,"name":"postData","type":"text/plain"},"parameters":{},"contentLength":38,"queryString":"","contextPath":""}
Based on the output provided by sheet.getRange(3,1).setValue(JSON.stringify(e)) (I'm not sure which of your methods generated this, but that method looks like it's the right one), your doPost as written should work, with one modification: I don't see a variable request defined, so I assume you intend request to be the http request object, which in an Apps Script web app is defined by the e parameter passed to the doPost (documentation). Therefore change this line
const data = JSON.parse(request.postData.contents)
to this one
const data = JSON.parse(e.postData.contents)
I'm new to using RapidAPI. I want to pull live Cricket Scores from RapidAPI with Excel VBA, but the programming language isn't available on the platform.
I would like to know if there is anyway I can view the json results directly through a browser. This is what I read in their documentation https://docs.rapidapi.com/docs/getting-started-with-rapidapi-sdks but doesn't seem to solve my problem
"What If the Programming Language I'm Using Isn't Available?
Whether the programming language you're using isn't available or you prefer to use another request library, have no fear! All of the APIs available on RapidAPI are exposed through a REST API endpoint. All you'll need to do is take the information provided on the documentation provided. Here's an example of what that would look like using the 'request' npm module"
var options = {
method: 'POST',
url: API_URL,
headers: {
'cache-control': 'no-cache',
'Content-Type': 'application/json',
'X-RapidAPI-Key': API_KEY,
'header1': 'header-value-1'
},
qs: {
parameter1: 'parameter-value-1'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
I'm looking for a better idea of working with RapidAPI in Excel VBA. If I can get the json response directly in a browser that solves my problem. But if that's not possible, any example to setup a Node.JS server offline and possibly display the json response in a browser may also work. Thanks in advance
Const Covid19URL As String = "https://covid-193.p.rapidapi.com/history?day=2020-03-25&country=Malaysia"
Const APIKey As String = "brx2HKOJvP6iQ14WxeumLmnhx2L2MAZz"
Sub Main()
Dim xmlhttp As New MSXML2.XMLHTTP60
Dim xmlresponse As New DOMDocument60
xmlhttp.Open "GET", Covid19URL, False
xmlhttp.setRequestHeader "x-rapidapi-host", "covid-193.p.rapidapi.com"
xmlhttp.setRequestHeader "x-rapidapi-key", APIKey
xmlhttp.send
Cells(2, 12).Value = xmlhttp.responseText
'xmlresponse.LoadXML (xmlhttp.responseText)
'"response":[
'{"country":"Malaysia","cases":{"new":"+172","active":1596,"critical":64,"recovered":183,"total":1796},"deaths":{"new":"+1","total":17},"day":"2020-03-25","time":"2020-03-25T09:15:07+00:00"},
'{"country":"Malaysia","cases":{"new":"+172","active":1597,"critical":64,"recovered":183,"total":1796},"deaths":{"new":null,"total":16},"day":"2020-03-25","time":"2020-03-25T07:15:06+00:00"},
'{"country":"Malaysia","cases":{"new":"+106","active":1425,"critical":64,"recovered":183,"total":1624},"deaths":{"new":"+2","total":16},"day":"2020-03-25","time":"2020-03-25T06:15:05+00:00"}
Set xmlresponse = Nothing
Set xmlhttp = Nothing
End Sub
I'm currently developing a intranet application for my company. Within my application i would like to fetch some variables with javascript and send them to a MySql database through php.
I know that javascript is a client-side and php is server-side so I'm not sure if it's even possible to transfer the variables through.
Goal is to get the current users computer name and store it in a SQL database whenever they are opening the intranet site.
<?php
<script type="javascript">
var network = new ActiveXObject('WScript.network');
<?php $pcName = "<script>document.write(network.computername)</script>";
</script>
?>
This part works perfectly. The computername is stored in the php variable $pcName and it shows fine on the intranet site when I try to echo the variable.
$sql = "INSERT INTO t1 (pcName) VALUES ('".$pcName."')";
But when I insert it into my sql table the value is "<script>document.write(network.computername)</script>".
Am I missing something? Or is it as I assumed that the variable is available on the clint, and the client only.
You will probably have to create and call an "API" of some sort. For example, you could have something like this on the client:
<script type="javascript">
var network = new ActiveXObject('WScript.network');
var pcName = network.computername;
fetch('storeComputer.php', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
pcName: pcName
})
});
</script>
And then on PHP side:
// storeComputer.php
$json = json_decode(file_get_contents('php://input'));
$pcName = $json['pcName'];
// do what you want with $pcName..
There are many ways, but i use jquery inside javascript to send the parameter to php. Its works for me very well
try this
$('.add_item').click(function(){
var responsecontainer=$('#responsecontainer').val();
var ProductName=$('#ProductTable').val();
$.ajax({
url:"sample.php"
, method:"POST"
, data: {
ProductName: ProductName,
}
, success: function(result){
// do some thing here
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
use can use some other method too.
Yes, it's possible.
Javascript can launch any URL with parameters, notably including JSON encoded parameters; the URL can launch a CGI script; the CGI script can catch the JSON and interact with the MySQl; and then return the result to javascript, either asynchronously or synchronously. Here's an asynch URL launch:
// this is asynchronous - result comes back to callback later, while this returns immediately
// -----------------------------------------------------------------------=======------------
function callAjax(url, callback)
{
var xmlhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
.
Here's a callback:
function cb_myCallback(theStuff)
{
// process theStuff here. If it's JSON data, you can unpack it trivially in Javascript,
// as I will describe later. For this example, it's just text. You're going to get
// back "hello, Ben"
console.log(theStuff);
}
.
So here's how I might use that to call a script that can access the database:
function pyRequest(upd_data,upd_callback)
{
var cd_url;
cd_url = '/cgi-bin/myPython.py?myData=' + encodeURIComponent(upd_data);
callAjax(cd_url,upd_callback);
}
pyRequest("Ben",cb_myCallback);
.
So here’s what happens. pyRequest() builds a URL that can call the Python (or whatever you like to use) script. callAjax() actually does the calling. This all returns immediately to the calling code. Later, when the script has completed whatever its task is, the callback, in the example cb_myCallback(), is sent whatever the script emitted.
Synchronous Approach
There may be times when you won’t want to use an asynchronous callback, because you can’t proceed until you have the data you asked for. In such cases, you need to use a synchronous request, which will not return (with the actual response) until the response has been received from the script. Note that in this function, I embed the URL to demonstrate a little variety in possible structuring of these types of usages:
// this is synchronous - result returns only when called script provides it
// ------------------------------------------------------------------------
function syncCallAjax(spdq_myData)
{
var remote = '__Unset__';
var request = new XMLHttpRequest();
var remote_url;
remote_url = '/cgi-bin/myPython.py?myData=' + encodeURIComponent(spdq_myData);
request.open('GET', remote_url, false); // false makes the request synchronous
request.send(null);
if (request.status === 200)
{
remote = request.responseText;
}
return(remote);
}
I am trying to update my kimono API via Google Script in Sheets. There are many urls in the sheet, but I've only shown 2 for this example.
I am receiving HTTP error 404. I've checked, and the apikey and id are fine.
How can I determine what's really wrong?
function PostParameters2() {
var parameters = {
apikey: "--apikey--",
urls: [
"https://twitter.com/search?q=%23running",
"https://twitter.com/search?q=%23swimming"
]
};
var data = JSON.stringify(parameters);
var url = 'https://kimonolabs.com/kimonoapis/--apiId--/update';
var options = {
'method': 'POST',
'content-Type': 'application/json',
'payload': data
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getResponseCode());
}
When debugging external host communication with UrlFetchApp, there are a few tools available to you.
It helps to muteHttpExceptions so you can view them. (In fact, you can simply write your code to handle them yourself, and only throw for exceptions you really don't expect.)
This is done by adding 'muteHttpExceptions' : true to your fetch parameters.
With exceptions muted, fetch won't throw an exception, instead it will pass failure response codes in the HTTPResponse. From there, you can extract the response code and content text for debugging (or automatic handling).
Modify your code like this, to log errors:
var response = UrlFetchApp.fetch(url, options);
var rc = response.getResponseCode();
if (rc !== 200) {
// HTTP Error
Logger.log("Response (%s) %s",
rc,
response.getContentText() );
// Could throw an exception yourself, if appropriate
}
Run, and here's what we see:
[15-08-27 11:18:06:688 EDT] Response (404.0) {
"error": true,
"message": "Could not find API"
}
Some APIs give very rich error messages. This one, not so much. But it does tell us that we have the URL correct, but that the service couldn't find the API we want. Next, dig into why that is so.
We can examine the fetch options and parameters by using getRequest(). Add this line just above the existing fetch() call, and put a breakpoint on the fetch().
var test = UrlFetchApp.getRequest(url, options);
Start the function in the debugger, and when the breakpoint is hit, examine the contents of test carefully.
A common problem is with the encoding of the POST payload. You hand-encoded # to %23 and used JSON.stringify(), so no problem there.
Checking the remaining options, we see that the contentType isn't 'application/json'.
So now you look at your code and find that the name for contentType was mis-typed as content-Type. Remove the hyphen, and try again.
Keep going until you've identified and fixed any other bugs.
Another tip is to use encodeURIComponent() to escape restricted characters in your fetch parameters, rather than hand-encoding them. It simplifies your code, because you can write the "real" characters like # instead of their UTF-8 escape sequences like %23.
Updated code:
function PostParameters2() {
var parameters = {
apikey: "--apikey--",
urls: [
encodeURIComponent("https://twitter.com/search?q=#running"),
encodeURIComponent("https://twitter.com/search?q=#swimming")
]
};
var data = JSON.stringify(parameters);
var url = 'https://kimonolabs.com/kimonoapis/--apiId--/update';
var options = {
'method': 'POST',
'contentType': 'application/json',
'payload': data,
'muteHttpExceptions' : true
};
var test = UrlFetchApp.getRequest(url, options);
var response = UrlFetchApp.fetch(url, options);
var rc = response.getResponseCode();
if (rc !== 200) {
// HTTP Error
Logger.log("Response (%s) %s",
rc,
response.getContentText() );
// Could throw an exception yourself, if appropriate
}
else {
// Successful POST, handle response normally
var responseText = response.getContentText();
Logger.log(responseText);
}
}
I am attempting to download a file from Google Storage using the Javascript json api. I am able to retreive the object info by using the code below, however I'm not sure how to get the actual media. I'm familiar with the Java library method getMediaHttpDownloader, but I do not see an equivalent in JS. Any help would be appreciated!
gapi.client.storage.objects.get({"bucket":"bucketName","object":"objectName"});
The Javascript library does not currently support directly downloading media. You can still get to the data, but you'll have to access it another way.
Depending on the domain your website is hosted on and the bucket you're reading from, you'll need to set up CORS: https://developers.google.com/storage/docs/cross-origin
Then, you'll need to request the object directly via the XML API. For example, you could do something like this:
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://'+bucket+'.storage.googleapis.com/'+object);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.send();
I've ended up not using the api(not sure that you can download using api, interested if you do know how) and using XmlHttpRequest instead. To do this I had to setup CORS for my google storage bucket to allow my site cross domain access. Below is my code:
var myToken = gapi.auth.getToken();
var req = new XMLHttpRequest;
req.open('GET','https://storage.googleapis.com/bucket/object',
true);
req.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
req.send(null);
I did it using gapi and jQuery.
In my case object is public. (pulbic link in storage browser must be checked). In case you don't want your object to be public, use $.post instead of $.get and provide assess_token as header exactly as it is done in other answers.
Storage.getObjectInfo retrieves object metadata.
Storage.getObjectMedia retrieves object content.
var Storage = function() {};
Storage.bucket = 'mybucket';
Storage.object = 'myfolder/myobject'; //object name, got by gapi.objects.list
Storage.getObjectMedia = function(object, callback) {
function loadObject(objectInfo) {
var mediaLink = objectInfo.mediaLink;
$.get(mediaLink, function(data) { //data is actually object content
console.log(data);
callback(data);
});
}
Storage.getObjectInfo(object, loadObject);
};
Storage.getObjectInfo = function(object, callback) {
var request = gapi.client.storage.objects.get({
'bucket' : Storage.bucket,
'object' : Storage.object
});
request.execute(function(resp) {
console.log(resp);
callback(resp);
});
};
It is also relatively rare case when we need to download the content of object. In most cases objects stored in Storage are media files like images and sounds and then all what we need is actually mediaLink, which must be inserted to src attribute value of appropriate dom element (img or audio).