I have searched the whole internet and I can't find a working way to log in to SugarCRM with Javascript. This is as close as I've gotten:
var params = {
user_auth:{
user_name:'jim',
password:'jim',
encryption:'PLAIN'
},
application_name: 'SugarCRM RestAPI Example'
}
var restdata = JSON.stringify(params);
$.ajax({
type: "POST",
url: "http://alzjgk0569.trial.sugarcrm.com/service/v4/rest.php?jsoncallback=?",
data: {
method: "login",
input_type: "JSON",
response_type: "JSON",
rest_data: restData
},
dataType:"jsonp",
success: function(result) {alert("result: " + JSON.stringify(result));},
failure: function() {alert("failed");}
});
Anyone have any ideas?
Thanks.
p.s. I should mention that the following works just fine:
<form action="https://alzjgk0569.trial.sugarcrm.com/rest/v10/oauth2/token" method="post">
grant_type: <input type="text" name="grant_type" value="password"><br>
client_id: <input type="text" name="client_id" value="sugar"><br>
client_secret: <input type="text" name="client_secret" value=""><br>
username: <input type="text" name="username" value="jim"><br>
password: <input type="text" name="password" value="jim"><br>
platform: <input type="text" name="platform" value="base"><br>
<input type="submit" value="Submit">
</form>
Edit:
I got it working by changing the url to begin with "https://" when this page is served with "https". But the response is this:
{\"user_auth\":{\"user_name\":\"jim\",\"password\":\"jim\",\"encryption\":\"PLAIN\"},\"application_name\":\"SugarCRM RestAPI Example\"}" = {"id":"1cg0ji99ouq0st6jndlcbo3075","module_name":"Users","name_value_list":{"user_id":{"name":"user_id","value":"seed_jim_id"},"user_name":{"name":"user_name","value":"jim"},"user_language":{"name":"user_language","value":"en_us"},"user_currency_id":{"name":"user_currency_id","value":"-99"},"user_is_admin":{"name":"user_is_admin","value":false},"user_default_team_id":{"name":"user_default_team_id","value":"1"},"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"},"user_default_timeformat":{"name":"user_default_timeformat","value":"h:ia"},"user_number_seperator":{"name":"user_number_seperator","value":","},"user_decimal_seperator":{"name":"user_decimal_seperator","value":"."},"mobile_max_list_entries":{"name":"mobile_max_list_entries","value":10},"mobile_max_subpanel_entries":{"name":"mobile_max_subpanel_entries","value":3},"user_currency_name":{"name":"user_currency_name","value":"US Dollar"}}}
This is completely useless information. It has no token, so it's not really even a real login. I'm giving up on client side SugarCRM login, and going back to server side with PHP, which I know works.
You actually have the answer here. Your login token is the id value in the response you posted.
SugarCRM API calls are better on the server side:
1. More secure
2. Does not have cross domain request issue due to the Same Origin Policy enforced by browsers. So JSONP is not needed.
Related
I am using Google reCaptcha v3. i am trying to implement it onto my aspx page.When i first load my page i can get a token back. However when i click on a button to process my page it comes back with a "No reCaptcha clients exits".
I did do a google search for this and nothing has came up to solve my issue. How can i verify a human or bot interaction?
this is what i have on my aspx page:
<div id="RegistrationForm">
<input type="text" id="FirstName" runat="server" value="" valtype="required" maxlength="150" />
<input type="text" id="LastName" runat="server" value="" valtype="required" maxlength="150" />
<input runat="server" id="Email" type="text" value="" valtype="required;regex:email" maxlength="350"/>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"/> <br />
<div class="g-recaptcha" data-sitekey="SiteKey" data-callback="submit"></div>
<input id="btnProcessOrder" type="button" name="ProcessOrder" onclick="confirmed = false;capt();" value="Save" />
</div>
this is What i tried
<script src="https://www.google.com/recaptcha/api.js?render=SiteKey"></script>
<script type="text/javascript">
//so when i load the page it gets my token and i can assign the value to g-recaptcha-response
grecaptcha.ready(function() {
grecaptcha.execute('SiteKey', { action: 'homepage' }).then(function (token) {
console.log(token);
document.getElementById('g-recaptcha-response').value = token;
});
});
Then when i try to verify the response as follows i get the error or it just does nothing:
function capt() {
var response = grecaptcha.getResponse();
$.ajax({
type: "POST",
url: 'https://www.google.com/recaptcha/api/siteverify',
data: {"secret" : "SecretKey", "response" : response, "remoteip":"localhost"},
contentType: 'application/x-www-form-urlencoded',
success: function(data) { console.log(data); }
});// i call this function on my button
}
</script>
Most of the code i found is for php and i can not use that.How do i get this to work correctly?.
Your response is highly appreciated
According to the above comments:
You create a render function as following
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
});
Then to get the response from the captcha you create a variable which will store the data as such:
var verifyCallBack = function(response) {
console.log(response);
};
Here we already have a same type of question :
How to implement reCaptcha V3 in ASP.NET
Please check these answers .
Also you can check this demo project for reference .https://github.com/NIHAR-SARKAR/GoogleRecaptchav3-example-In-asp.net
I am creating a webform in Visual Studio and I need to send the data from the form fields to a 3rd party API using POST. I have tried using json to capture the form fields and send the json object, but I am not able to do so. I get the error, "Authorization has been denied for this request.". I am new to ASP and json.This is a sample of my code, not the actual code(unfortunately I cannot provide the exact code). When I run this POST request using an application like Advanced REST Client, I am able to successfully send the request.
My sample code:
<form action='https://test' method="post" name="MY Form">
<input id="username" name="username" type="text" /><br />
<input id="password" name="password" type="password" /><br />
<input id="button1" name="button1" type="submit" value="login" />
</form>
JavaScript:
$('#button1').click(function() {
formData = {
username: username,
password: password
};
$.ajax({
type: 'POST',
contentType: 'application/json',
accept: 'application/json',
authorization: 'Bearer <token>',
url: 'https://test',
dataType: 'json',
data: formData
});
});
formData = json.stringfy({
'username': $('#username').val(),
'password': $('#password').val()
};
I have client side code that looks like this:
<form name="sendCoordinates" action="http://localhost:8080/geodata" method="post">
<label> MinLat: </label>
<input type="text" name="MinLat" value="0"><br>
<label> MaxLat: </label>
<input type="text" name="MaxLat" value="1"><br>
<label> MinLong: </label>
<input type="text" name="MinLong" value="0"><br>
<label> MaxLong: </label>
<input type="text" name="MaxLong" value="1"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$("#sendCoordinates")
.on('submit', function(e) {
e.preventDefault();
var $form = $(e.target),
formData = new FormData();
params = $form.serializeArray();
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
console.log(result + "you");
}
});
});
</script>
I am sending this form data to an endpoint /geodata.
app.post("/geodata", function(req, res) {
console.log(req.body);
});
My question is, under a successful post, what would console.log(req.body) print on the server side? I am unable to tell yet as my client is not sending any information yet due to some bug. This will help me write my server side code according to the data I receive in the post request.
Looks like you're using Express. In general practice, request bodies are parsed as JSON (see Express req.body docs), but it depends on the parsing middleware you're using (body-parser is the common one in Express apps).
It also depends on the Content-Type header of the request. From the Express docs I mentioned above, they give an example:
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
It looks like you currently set contentType: false in your AJAX request, so that will just send raw data to your server.
To answer your question more concretely
My question is, under a successful post, what would console.log(req.body) print on the server side?
It depends on the Content-Type and what middleware (if any) you are using the parse request bodies.
I have a basic script that is as follows:
$(".submit").click(function(){
var fd = new FormData();
fd.append('username', 'Bob');
$.ajax({
url: '/signup',
type: 'post',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log("Success: ", data);
}
});
});
When the request hits my server, I receive a req.body of {} (empty) and there is nothing in req that points to data being sent. Whats going on here? How can I send data with FormData?
I wanted to test getting basic preset data from FormData and was unsuccessful. The values console logged in Chrome show an empty formData object, with only its constructor and the available 'append' method.
I am using jQuery v 2.1.4 and HTML5 and have confirmed that window.FormData is a valid object in Google Chrome.
My goal is to have a form that a user can enter an email, password, avatar, and a profile background image with the following form:
<form id="msform" enctype="multipart/form-data" name="msform">
<!-- Progress Bar -->
<ul id="progressbar">
<li class="active">Basic Information</li>
<li>Profile Customization</li>
</ul>
<!-- Step One -->
<fieldset>
<h2 class="title">Basic Information</h2>
<input type="text" name="username" placeholder="Username" />
<input type="text" name="password" placeholder="Password" />
Avatar Image <input type='file' id='avatarImage' accept="image/*" name='avatarImage'>
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<!-- Step Two -->
<fieldset>
<h2 class="title">Profile Customization</h2>
<select id="dropdown" name="profileColor">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
Background Photo <input type='file' id='bgPhoto' accept="image/*" name='bgPhoto'> </div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit action-button" value="Submit" />
</fieldset>
</form>
Whats going on with FormData, it seems like a valid object, but I'm unable to append anything to it. I've looked, and it appears that others have seen an empty object in their console, but the data 'automagically(?)' appears on their server? My first code block is basically a copy for the docs and I'm having trouble with it. Would and CORS issues or CDN errors be the case? Something maybe not able to access as it should? No errors print in the log, only a blank object on my post request.
Thanks for the help!
If you are using Express as the backend, body-parser does not handle multipart/form-data, and you are referred to using multiparty instead. You can integrate Express with multiparty like so :
var express = require('express');
var multiparty = require('multiparty');
var app = express();
var data = new multiparty.Form();
app.post('/signup', function(req, res) {
data.parse(req, function(err, fields, files) {
if(err) throw err;
Object.keys(fields).forEach(function(name) {
console.log('got field named : ' + name + ', value : ' + fields[name]);
});
Object.keys(files).forEach(function(name) {
console.log('got file named : ' + name);
});
});
});
Do include event.preventDefault() in your click event handler
$(".submit").click(function(e){
e.preventDefault();
var fd = new FormData();
fd.append('username', 'Bob');
...
});
You aren't preventing the default form submit event and neither are you catching a submit by keyboard if user hits enter.
Try:
$("#msform").submit(function(e){
e.preventDefault();
var fd = new FormData();
fd.append('username', 'Bob');
$.ajax({
url: '/signup',
type: 'post',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log("Success: ", data);
}
});
});
If you aren't sending files I would suggest using the simpler approach of removing the processData and contentType options and using $(this).serialize() for the data value
I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.