Setting the request URL of a Suitelet form - javascript

I have a form with text fields that I want to send to another server. The problem I am having is that I don't know how I set the request URL. I want to send the contents of the form to another URL and then process the response into Netsuite records. Below is the format of how the code will look. Any ideas on how I'm supposed to set that URL? Should I be using nlapiRequestURL()?
function mainFunction(request, response){
if (request.getMethod() == 'POST'){
var form = nlapiCreateForm('Form');
form.addField('field_one', 'text', 'value 1');
...
...
form.addSubmitButton('Submit');
// on submit send to specified URL
// response processed
}
}

By using form.addSubmitButton, whenever that is clicked, NetSuite will POST the request back to the same Suitelet that drew the form. This POST request should contain all of the field values from your Suitelet form.
Since you are already rendering your form when the Suitelet receives a POST request, you'll have to decide how to differentiate between the initial POST to render the form, and the POST from the submit button.
If you are sending a request to a different URL (e.g. another Suitelet, or a web service somewhere), then you are correct that you would use nlapiRequestURL.

If you use addSubmitButton, the Suitelet will use the same URL passing the field values to the same url. If you want to send the data to a different URL you can use addButton and put a custom function that will send the data to that URL.

Related

Passing credentials or token from JS to PHP in google calendar API

I am not sure if this is even possible. I am trying to add events to a google calendar. Authorization via Javascript is working. I am able to get authorization from user. The user will sign in when they are filling out the form then submit the form for processing in the server. I need to insert the event after the form is submitting. This is because there are many validations before the form is processed. I would like to know if it is possible to pass access token or some validation so that the event can be added on server side with google api. So user logs in with JS but event is inserted with PHP. This is what I have so far.
token = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;
///user is logged in and I can get access token
$.ajax({
url : 'aa_calendar.php',
type : 'post',
data : 'token='+token,
dataType:'json',
success : function(result) {
console.log(result);
$("#content").html(result.msg);
}
});
Now in aa_calendar.php
$client = new Google_Client();
$client->setApplicationName('Remote Sessions');
$client->setClientId('xxxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxxxx');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxxxxx');
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));
$client->setAccessToken($_POST['token']);
this is the error I am getting
Uncaught Google_Auth_Exception: Could not json decode the token
I assume is not as easy as just passing a token :/
Thank you all for the help

CakePHP 3 Json response instead of redirect ( if ext = json )

Is there any easy way to configure CakePHP auth component to send out a json response instead of normal redirect to login url.
Im using many ajax requests, and when the session expires, the ajax request will get a response of my home page's html instead of json encoded status.
I would like CakePHP to send out the following json response, if user is not logged in, and the query was made using json extension.
{status: false, message: "Please log in"}
Non-ajax page loads would still need to redirect as usual.
You should look upon where is the system checking whether you are logged in and see the case where it is not logged in. Wrap the following if around it:
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
//put here the html for the log in screen
} else {
$response = '{status: false, message: "Please log in"}';
echo json_encode($response);
}
Since it is hard to determine if you are making an ajax request, Cake 3 uses X-Requested-With = XMLHttpRequest. It seems this is a default for jquery (but who uses that anymore? seriously.).
You will need to set that header manually to allow cakephp to detect that your request is indeed ajax.
Your ajax requests may work on other pages because you are probably setting the _serialize var and setting the Accept Header or using the .json extensions to force json. However, the auth function does not check the Accept Header it only checks the X-Requested-With header.
So verify in your xhr request that X-Requested-With is XMLHttpRequest and you should receive a 403.
If you want to further customize the element or data that is returned, checkout the AuthComponent ajaxLogin param.
Handle Ajax Unauthorized
Basically, you will need to set the value to an element you want rendered.
Cake will look in your Element Template path and load that element.
// In your AppController
$this->loadComponent('Auth', [
'ajaxLogin' => 'yourAjaxElement', // This is what is important
// Optional stuff....
'authenticate' => [
'Form' => [
'finder' => 'AuthUser'
]
],
'authorize' => ['Controller'],
// More settings...
Then create this element
Template/Element/yourAjaxElement.ctp
Happy coding.

jQuery submit preventDefault

I load a page from example.com on port 80, then from the loaded page, submit a form to the same server on a different port (as defined in the form action attribute).
(html)
<form id="enabledForm" action="http://example.com:39991/updateEnabled" method="POST">
(javascript)
$('#enabledForm').submit()
This works fine and the data is delivered as expected to the form action url, but the browser is redirected to the address of the POST request instead of staying on the requesting page.
If I use
$('#enabledForm').submit(function (event) {
event.preventDefault();
});
or
$('#enabledForm').submit(function (event) {
return false;
});
then the server receives no data but the page is not redirected.
if I add an alert within the event handler then the alert is not shown.
$('#enabledForm').submit(function (event) {
alert('inside submit event handler');
return false;
});
Clearly I'm soing something wrong but after hours of headbanging and trying everything I can think of I'm stuck.
What to do?
You have two basic options here:
Have the server return a 204 No Content response and forget about using JS entirely
Prevent the submission of the form with JS and send the data to the URL with Ajax instead
No content:
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent.
How you set the HTTP response status code depends on your server side language / framework. For example:
In Catalyst it would be something like:
$c->response->status(204);
In PHP it would be:
http_response_code(204);
There are many Ajax tutorials out there, so I'm not going to provide another one. The jQuery documentation has a detailed section on Ajax.
Note that since you are working across origins (different ports), you will need to circumvent the Same Origin Policy. The standard way to do that is with CORS.
Sending a form would automatically change your browser URL (and refresh view).You should use an Ajax request to send informations to your server and eventually retrieve completion (success, error, informations...).
Extract your inputs' values to an object via Jquery and send your request via Jquery.post or Jquery.get
$('#enabledForm').submit(function (event) {
//Prevent natual post
event.preventDefault();
//Retrieve inputs values
var data = {}
$('#enabledForm input,textarea').each(function(index){
data[$(this).attr('name')] = $(this).val();
});
//Send request
$.post('http://example.com:3999/updateEnabled',data,function(response){
//Parse response if you want to inform user about success of operation
});
});
I don't know if val() is usable with all of yout inputs, but it's easy to adapt...

Parse.com getting data from callback URL

I'm currently trying to use an API and for the API, the developer console of that app asks the developer to submit a callback URL. Whenever the user of the app does something, it submits a GET request to the callback URL and I can retrieve data from that request. The current url I am using is https://appId:javascript-key=myJavascriptKey#api.parse.com/1/functions/receiveInfo. How can I handle the data, a.k.a the GET parameters, from the GET request? I found an answer on Parse.com that says how to retrieve data from a POST request, but all it says is that data = request.body. Do I do the same for GET requests and if so what do I do after that? Is request.body a json value?
Parse.Cloud.define("receiveInfo", function(request,response){
var params = request.body;//is this right to get the GET parameters they send? if so what do I do next?
});
The documentation has your solution at: https://parse.com/docs/cloud_code_guide#functions
For GET requests you have to use the request.params object which has all your request parameters for a GET are there. POSTS are sent in the request body, GET in the request parameters.
It looks like you are trying to get the params you can use something similar to:
Parse.Cloud.define("myMethod", function(request, response) {
if(request.params.myparam == "moo") {
response.success("Cow!");
}
else {
response.error("Unknown type of animal");
}
});

Using one and all chaining in Restangular post requests

I have an issue where I'm trying to make a post request using Restangular:
I'll setup the query like so:
var auth = Restangular.all('auth');
var check = auth.one('check');
Then I'll do the post request like so:
var user = {
email: 'randomemail#gmail.com',
pass: 'randompass'
}
check.post(user)
However, the request shows an error, when I check the network, the request is sent as so :
http://localhost/auth/check/[object object]
Why does the post request attach the object like a query parameter instead of sending it in the request body?
If i'm formatting this post request incorrectly, can someone point out the correct way to format a post request using one and all in Restangular.
Thanks!
When you post to a one(), post() is actually expecting a subElement as the first argument, which is why it's attaching the object passed to the path...
(from documentation)
post(subElement, elementToPost, [queryParams, headers]): Does a POST
and creates a subElement. Subelement is mandatory and is the nested
resource. Element to post is the object to post to the server
To post to /auth/check, you can use customPOST()...
auth.customPOST(user, 'check');
Edit - Here are a couple of examples if you are set on using post()...
Restangular.one('auth').post('check', user);
Or
auth.all('check').post(user);

Categories