HTTP request through Parse Cloud code - javascript

So I am trying to get the cloud code to do an aftersave event that pings another location to do some data saving.
It has some data that needs to be sent as well.
Parse.Cloud.afterSave("ArtPiece", function(request) {
var artistURL = 'http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php';
var pieceName = "Robert Rauschenberg Quote";
var url = 'http://www.gilmancontemporary.com/wp-content/uploads/2015/06/Delicate_Garden.The_Bear.48x42.jpeg';
Parse.Cloud.httpRequest({
url: artistURL,
dataType : "text",
crossDomain: true,
type:"GET",
data : {
pieceName : pieceName,
url : url
},
success: function(httpResponse) {
response(httpResponse.text);
},
error: function(httpResponse) {
response('Request failed with response code ' + httpResponse.status)
}
});
});
The code does not give an error, or any warnings. Me saving/creating entries works fine.
Cors is already handled, as I can successfully make this call with an ajax script.
Any clue why this is not sending?
Can I not have data in a parse httpRequest?
Can it not be crossdomain?
Alternatively
Is there a way to test this code outside of the Parse Cloud???

The way you call httpRequest function is not correct in cloud. You also do not need to worry about CORS as you are not working in a browser environment. Try this instead:
Parse.Cloud.httpRequest({
url: artistURL,
params: {
pieceName : pieceName,
url : url
},
success: function(httpResponse) {
response(httpResponse.text);
},
error: function(httpResponse) {
response('Request failed with response code ' + httpResponse.status)
}
});
To test this outside cloud environment you can use the curl command. It will be something like:
curl -G -v "http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php" --data-urlencode "pieceName=Robert Rauschenberg Quote,url=http://www.gilmancontemporary.com/wp-content/uploads/2015/06/Delicate_Garden.The_Bear.48x42.jpeg"

Related

Create a gist using GitHub API

I wanna create a gist using GitHub API. I tried an POST ajax request:
var gist = {
"description": "Avatars",
"public": true,
"files": {
"check.txt": {
"content": "Avatars list..."
}
}
};
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
dataType: 'json',
data: JSON.stringify(gist),
success: function(e) {
console.log(e);
},
error: function(e) {
console.error("Error!: ", e);
}
});
But I always get the following error:
jquery-3.1.1.min.js:4 POST https://api.github.com/gists 401 (Unauthorized)
Can anyone help me?
Thanks
When you want to edit things on Github, you need to authorize your request. Either by adding a username and password to the request or an oauth token.
More information can be found in the authorization documentation: https://developer.github.com/v3/auth/
Since I ran across the same problem recently, let me add the examples requested by T.Todua
If you want to authenticate with username and password, add the following lines to your $.ajax request:
crossDomain: true,
beforeSend: function (XHR) {
XHR.setRequestHeader(
'Authorization','Basic ' + btoa(Username + ':' + Password)
);
},
If, however, you created an access token for your gists (see Github help and don't forget to check the "Gist" permission!) then add the following lines instead
crossDomain: true,
headers: {
'Authorization':'bearer ' + GitHubAccessToken
},
The GitHubAccessToken will be shown once (and only once!) immediately after creation, so make sure to store it in a safe location as everybody knowing this access token will be able to modify your gists (until you revoke it again).

How to use an API with an app Fiori (SAPUI5)

I am trying to use this Mercedes Benz API in my app. Inside controller I have a ajax request:
onInit : function () {
var oModel = new JSONModel();
var url = 'https://api.mercedes-benz.com/image/v1/vehicles/WDDZH3HB8JA394212/components?apikey=my_apikey';
$.ajax({
beforeSend: function() {
//armamos la url y la asignamos a una var
},
url: url,
type: 'GET',
accepts: "application/json",
success: function (resp) {
console.log(resp)
},
error: function (jqXHR, estado, error) {
console.log(error +":" + " " + estado)
},
timeout: 10000
});
},
I just want response as OK but getting some error:
Request header field X-XHR-Logon is not allowed by
Access-Control-Allow-Headers in preflight response.
Responses
If you take a look to the documentation API I just need the API key. Maybe I am doing something wrong? Guide me if you has use an API inside a FIORI app it will be thankful
NOTE: my fiori server is on premise so we don't use SCP
If you really want to do an XHR you need to whitelist APIKEY in neo-app.json like this
{
"welcomeFile": "/webapp/index.html",
"routes": [{
...
],
"sendWelcomeFileRedirect": true,
"headerWhiteList": [
"APIKey"
]
}
Otherwise I strictly recommend using destinations, explained in here:
SAPUI5 / AJAX, submitting Basic Authentication Details (solved)
Authentication API in SAPUI5 without SAP Cloud Platform and Destinations (not solved)

Ajax and PHP, post request not working

So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});

How to run Twilio API code using Javascript?

I am using twilio api code in jquery,its working fine.
but i want to implement it in pure javascript,how can i do that with only javascript?
My code is here.
$(document).ready(function() {
$("#btnSubmit").click(function(){
var SID = "AC654656****************"
var Key = "df5456**************"
$.ajax({
type: 'POST',
url: 'https://api.twilio.com/2010-04-01/Accounts/' + SID +'/Messages.json',
data: {
"To" : "+919580834781",
"From" : "+12018647238",
"Body" : "Test"
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(SID + ':' + Key));
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
});
can anyone please suggest me the solution?
Twilio developer evangelist here.
We do not recommend you use front end JavaScript to make calls to the Twilio API. It requires you to embed your Account Sid and Auth Token in your front end (or make it accessible from your front end) which means that an attacker could steal your credentials and use them to abuse your account.
We recommend you perform any actions with the Twilio API on the server. We do have a Node.js module on npm to make that easy to work with. Here's an example of sending an SMS message with the Node.js module:
var client = require("twilio")(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN);
client.messages.create({
body: "Hello",
to: TO_NUMBER,
from: FROM_NUMBER
}).
then(function(result) {
console.log("Message sent!");
}).
catch(function(err) {
console.log("Error sending message: ", err);
})
Check out this blog post introducing the Twilio Node.js module for more information.
Let me know if that helps at all.

Impossible to create a new account on prestashop

I am currently developping a new website
When I am trying to create an account, I get an error like this :
Uncaught TypeError: Cannot read property 'hasError' of null.
And this is the code
function submitFunction()
{
$('#create_account_error').html('').hide();
//send the ajax request to the server
$.ajax({
type: 'POST',
url: baseUri,
async: true,
cache: false,
dataType : "json",
data: {
controller: 'authentication',
SubmitCreate: 1,
ajax: true,
email_create: $('#email_create').val(),
back: $('input[name=back]').val(),
token: token
},
success: function(jsonData)
{
if (jsonData.hasError())
{
var errors = '';
for(error in jsonData.errors)
//IE6 bug fix
if(error != 'indexOf')
errors += '<li>'+jsonData.errors[error]+'</li>';
$('#create_account_error').html('<ol>'+errors+'</ol>').show();
}
else
{
// adding a div to display a transition
$('#center_column').html('<div id="noSlide">'+$('#center_column').html()+'</div>');
$('#noSlide').fadeOut('slow', function(){
$('#noSlide').html(jsonData.page);
// update the state (when this file is called from AJAX you still need to update the state)
bindStateInputAndUpdate();
$(this).fadeIn('slow', function(){
document.location = '#account-creation';
});
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
It seems to be the jsonData, on the function, which is not working as well. Any idea or suggestions?
The success handler will be passed the data returned from the ajax request.
It will not have a function called hasError() because it is just a json object it will not have any functions.
The error handler should be fired if there is an http error i.e. if the ajax call returns an http 500.
I'm not familiar with prestashop, but looking over the prestashop documentation hasError is returned as a bool (not a function), so instead try (without the parenthesis).
if (jsonData.hasError)
You may also want to check if any data is returned first.
if (jsonData)

Categories