I am trying to go through this sample https://github.com/blackberry/BB10-WebWorks-Samples/blob/master/Twitter-OAuth-1/README.md
Although, I keep getting the following error:
Error in getAuthorization: ReferenceError:Can't find variable: facebookOptions
Here is my code for my javascript OAuth.js
function initApp() {
try {
// facebook oauth setup
facebookOptions = {
clientId: '############',
clientSecret: '######################',
// we use a php script on a server because facebook doesn't allow for local:/// callbacks
// at this time. the php simply redirects us back to 'local:///index.html'
redirectUri: 'http://###########.com/redirect.php'
};
// here we check for query strings in window.location when the app loads. This is because facebook is calling back
// to our callbackUrl. When the app initializes, and there is a query string, it checks if the user
// authorized the app or not
var query = window.location.search;
authCode = null;
authCode = query.split('code=');
authCode = authCode[1] || null;
// we've got an auth code, let's exchange that for an access token
if (authCode !== null) {
getAccessToken();
}
} catch (e) {
alert('Error in initApp: ' + e);
}
}
// first, we get the user to authorize with the service and allow our app access
function getAuthorization() {
try {
showMessage('Contacting Facebook...');
window.location.replace('https://www.facebook.com/dialog/oauth?client_id=' + facebookOptions.clientId + '&redirect_uri=' + facebookOptions.redirectUri + '&scope=publish_stream,read_stream');
} catch (e) {
alert('Error in getAuthorization: ' + e);
}
}
// exchange our 'access code' for an 'access_token'
function getAccessToken() {
try {
var url = 'https://graph.facebook.com/oauth/access_token?client_id=' + facebookOptions.clientId + '&redirect_uri=' + facebookOptions.redirectUri + '&client_secret=' + facebookOptions.clientSecret + '&code=' + authCode;
$.ajax({
type: 'GET',
url: url,
success: function(data) {
var response = data;
// parse 'access_token' from the response
response = response.split('&');
accessToken = response[0].split('=');
accessToken = accessToken[1];
// get authenticated users' info for future use
getUserInfo();
},
error: function(data) {
alert('Error getting access_token: ' + data.responseText);
return false;
}
});
} catch (e) {
alert('Error in getAccessToken: ' + e);
}
}
// get users info (we're grabbing their full name for this sample)
function getUserInfo() {
try {
var url = 'https://graph.facebook.com/me?access_token=' + accessToken;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
// data.name = users full name
showMessage('Hello ' + data.name + '!');
$('#buttonSetup').hide();
$('#afterAuth').show();
},
error: function(data) {
alert('Error getting users info: ' + data.responseText);
return false;
}
});
} catch (e) {
alert('Error in getUserInfo: ' + e);
}
}
// update the users status
function postToService() {
try {
var status = $('#inputBox').val();
if (status === '' || status === 'enter your status...') {
showMessage('You didn\'t enter anything to post :(');
return false;
} else {
showMessage('Updating status...');
var url = 'https://graph.facebook.com/me/feed?message=' + status + '&access_token=' + accessToken;
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
success: function(data) {
showMessage('Status updated!!');
$('#inputBox').val('enter your status...');
// display the updated news feed to the user
setTimeout(function() {
getFeed();
}, 200);
},
error: function(data) {
alert('Error updating status: ' + data.responseText);
return false;
}
});
}
} catch (e) {
alert('Error in postToService: ' + e);
}
}
// get users news feed
function getFeed() {
try {
showMessage('Getting news feed...');
var url = 'https://graph.facebook.com/me/feed?access_token=' + accessToken;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
showMessage('Your news feed...');
var feed = data.data;
// clear the content div, and prepare to add new data to it
$('#content p').remove();
// show the last 4 items from the users news feed
// note: there are several objects that could be posted in a news feed. for simplicity
// we're only showing objects with a 'story' attribute
for (var i = 0; $('#content p').size() < 4; i++) {
if (typeof feed[i].story !== 'undefined') {
$('#content').append('<p>' + feed[i].story + '</p>');
}
}
// display the feed, after it's been parsed
$('#content').fadeIn();
},
error: function(data) {
alert('Error loading news feed: ' + data.responseText);
return false;
}
});
} catch (e) {
alert('Error in getFeed: ' + e);
}
}
// helper function for displaying a message to the user
function showMessage(msg) {
try {
if (!$('#message').is(':visible')) {
$('#message').show();
}
setTimeout(function() {
$('#message').html(msg);
}, 500);
setTimeout(function() {
$('#message').fadeOut(500, function() {
$('#message').html('');
});
}, 8000);
} catch (e) {
alert('Error in showMessage: ' + e);
}
}
the php redirect file on my web server is this:
<?php
$queryString = $_SERVER['QUERY_STRING'];
header("location: local:///index.html" . $queryString);
?>
I am not sure whether the problem is with the authorization in oauth.js or in the local redirect php file.
I have just updates all the OAuth samples to work in the newest SDK.
Get the updated sample from: https://github.com/blackberry/BB10-WebWorks-Samples
The problem is that the initApp function wasn't being executed. This is because the webworksready event wasn't being fired. Now that the samples have been update to reflect the new way of including the webworks.js file, this should no longer be an issue.
Related
I'm using formstone drag and drop file upload in my ajax powered form. using $(".uploadImage").upload("start") and $(".uploadDocs").upload("start") for initializing upload section for image and document separately after ajax function response. Each function working but I want to pass a custom variable, something like folder name to formstone and create a folder with that name and upload image and doc to that folder. how to do that?
Ajax function in which the insertion happens and return the id
$.ajax({
type: 'POST',
url: base_url + 'innovation/addProcess',
dataType: "html",
data: $('#add_innovation').serialize(),
success: function(result) {
var res = result.split("#");
if (res[0] == 'success') {
$(".uploadImage").upload("start",postData: {"ideaId":10});// sending custom value to formstone, which is not working as of now
$(".uploadDocs").upload("start",postData: {"ideaId":10});
} else {
showNotification('alert-danger', result);
}
},
error: function(error) {
console.log('error');
}
});
Formstone initialization
Formstone.Ready(function() {
$(".uploadImage").upload({
maxSize: 1073741824,
beforeSend: onBeforeSend,
autoUpload: false,
//postData: {"ideaId":50} // this is working. but don't want this here
}).on("start.upload", onStart)
.on("complete.upload", onComplete)
.on("filestart.upload", onFileStart)
.on("fileprogress.upload", onFileProgress)
.on("filecomplete.upload", onFileComplete)
.on("fileerror.upload", onFileError)
.on("queued.upload", onQueued);
$(".uploadDocs").upload({
maxSize: 1073741824,
beforeSend: onBeforeSend,
autoUpload: false,
}).on("start.upload", onStart)
.on("complete.upload", onComplete)
.on("filestart.upload", onFileStart)
.on("fileprogress.upload", onFileProgress)
.on("filecomplete.upload", onFileComplete)
.on("fileerror.upload", onFileError)
.on("queued.upload", onQueued);
});
function onCancel(e) {
console.log("Cancel");
var index = $(this).parents("li").data("index");
$(this).parents("form").find(".upload").upload("abort",
parseInt(index, 10));
}
function onCancelAll(e) {
console.log("Cancel All");
$(this).parents("form").find(".upload").upload("abort");
}
function onBeforeSend(formData, file) {
console.log(formData.get("ideaId")); // here i need the posted data. currently its not getting here
formData.append("ideaId", ideaId);
return ((file.name.indexOf(".jpg") <= -1) && (file.name.indexOf(".png") <= -1)) ? false : formData; // cancel all jpgs
}
function onQueued(e, files) {
console.log("Queued");
var html = '';
for (var i = 0; i < files.length; i++) {
html += '<li data-index="' + files[i].index + '"><span class="content"><span class="file">' + files[i].name + '</span><span class="cancel">Cancel</span><span class="progress">Queued</span></span><span class="bar"></span></li>';
}
$(this).parents("form").find(".filelist.queue")
.append(html);
}
function onStart(e, files) {
$(this).parents("form").find(".filelist.queue")
.find("li")
.find(".progress").text("Waiting");
}
function onComplete(e) {
console.log("Complete");
// All done!
}
function onFileStart(e, file) {
console.log("File Start");
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]")
.find(".progress").text("0%");
}
function onFileProgress(e, file, percent) {
console.log("File Progress");
var $file = $(this).parents("form").find(".filelist.queue").find("li[data-index=" + file.index + "]");
$file.find(".progress").text(percent + "%")
$file.find(".bar").css("width", percent + "%");
}
function onFileComplete(e, file, response) {
console.log("File Complete");
if (response.trim() === "" || response.toLowerCase().indexOf("error") > -1) {
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]").addClass("error")
.find(".progress").text(response.trim());
} else {
var $target =
$(this).parents("form").find(".filelist.queue").find("li[data-index=" + file.index + "]");
$target.find(".file").text(file.name);
$target.find(".progress").remove();
$target.find(".cancel").remove();
$target.appendTo($(this).parents("form").find(".filelist.complete"));
}
}
function onFileError(e, file, error) {
console.log("File Error");
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]").addClass("error")
.find(".progress").text("Error: " + error);
}
HTML where i used formstone control
<div class="uploadImage" style="height:100px;border:1px dashed #000;" data-upload-options='{"action":"<?php echo base_url();?>innovation/uploadImage","chunked":true}'></div>
<div class="uploadDocs" style="height:100px;border:1px dashed #000;" data-upload-options='{"action":"<?php echo base_url();?>innovation/uploadDocs","chunked":true}'></div>
Try this...
.ajax({
type: 'POST',
url: base_url + 'innovation/addProcess',
dataType: "html",
data: $('#add_innovation').serialize(),
success: function(result) {
var res = result.split("#");
if (res[0] == 'success') {
$(".uploadImage").upload("defaults", {postData: {"ideaId":10}});
$(".uploadImage").upload("start");
$(".uploadDocs").upload("defaults", {postData: {"ideaId":10}});
$(".uploadDocs").upload("start");
} else {
showNotification('alert-danger', result);
}
},
error: function(error) {
console.log('error');
}
});
Before you call the method "start" you need to add the option "postData". As what I understand from the documentation the "start" method doesn't allow additional params.
CodyKL's solution works using the defaults method, or you can append extra params with the beforeSend callback:
// Var to store ID of inserted item
var resultId;
// Insertion AJAX
$.ajax({
...
success: function(result) {
// Get the id from the result
resultId = result;
// Start the upload
$(".uploadImage").upload("start");
},
...
});
// Initialize Upload
$(".uploadImage").upload({
...
beforeSend: onBeforeSend,
...
});
// Modify upload form data
function onBeforeSend(formData, file) {
formData.append('ideaId', resultId); // add resultID obtained in insertion AJAX above to form data
return formData; // Return modified formData
}
You should read up on how JS and the FormData API work: https://developer.mozilla.org/en-US/docs/Web/API/FormData.
I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I getting undefined value when I try to get the value of coupon from coupons table from my DB but when I get the value of percentage or price it comes correct the code is written in ajax as I am new to ajax help me solve this problem.
(function() {
var path = "{{ route('validate.coupon') }}";
$('.reserve-button').click(function() {
var coupon_number = $('.coupon-number').val();
var org_price = parseInt($('#amount').val());
//alert(coupon_number);
if (coupon_number == '') {
alert("Please Enter Coupon Number");
} else {
$.ajax({
url: path,
data: {
"coupon_number": coupon_number
},
type: 'get',
success: function(result) {
if (result.percentage == 0 && result.price == 0) {
alert('Sorry Coupon Not Exists');
} else {
$("input[name='coupon']").prop('disabled', true);
$("#btn-apply-now").remove()
var disc = org_price * (result.percentage / 100.0) + result.price;
var new_price = org_price - disc;
$('.price').html('$' + new_price);
// $('#amount').val(new_price);
$('#coupon-number').val(coupon_number);
alert('!!__ Congratulations you got ' + result.percentage + '% and ' + result.price + '$ discount __!!');
$('#price_detail').append('<li class="item clearfix"><div class="title">Discount</div><span>$' + disc + '</span></li>')
}
}
});
}
});
})();
Based on your description, you get the percentage, price from coupon code input and using ajax select the db.
What you need is return the json from sql response like this:
Press F12 -> Console log to check the result.
You can check in jsfiddle
var coupon = 'asd';
$.ajax({
url : "https://api.myjson.com/bins/95yl8",
type: "get",
dataType: 'json',
data: {coupon_code: coupon},
success: function(res)
{
console.log('all result', res);
console.log('percentage', res['data']['percentage']);
},
error:function(x,e) {
if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I was trying to implement the Google Drive API using PHP. Here is my goal,
Request a Google Drive folder id from the user
Once entered, authenticate the user and get the authorization code
Fetch and set the access token to get the file detail from the folder
Here the code sample,
PHP
public $google_client;
function __construct(){
$this->google_client = new Google_Client();
$this->google_client->setApplicationName(APPLICATION_NAME);
$this->google_client->setScopes(SCOPES);
$this->google_client->setAuthConfig(CLIENT_SECRET_PATH);
$this->google_client->setAccessType('offline');
}
function get_drive_auth_url(){
$folder_id = trim($_POST['folder_id']) || null;
$auth_code = trim($_POST['auth_code']) || null;
if(!$folder_id || !$auth_code){
$auth_url = $this->google_client->createAuthUrl();
$response = array('type' => true, 'message' => 'success', 'data' => $auth_url);
echo json_encode($response);
exit();
} else {
$access_token = $this->google_client->fetchAccessTokenWithAuthCode($auth_code);
print_r($access_token);
exit();
}
}
JS
var folder_id = jQuery(this).val() || '';
if(!folder_id){
alert('Please provide a valid folder id.');
return false;
}
// AJAX Request to fetch the auth url
jQuery.ajax({
url: woocommerce_params.ajax_url,
method: 'POST',
dataType: 'json',
data: {
action: 'get_drive_auth_url'
},
success:function(response) {
var url = response.data || '';
if(!url){
return false;
}
window.open(url, 'Google Drive Authorization', 'width=600,height=350', true);
var auth_code = prompt('Please provide the authorization code.');
if(auth_code){
//AJAX Request to pass the folder id and auth code
jQuery.ajax({
url: woocommerce_params.ajax_url,
method: 'POST',
dataType: 'json',
data: {
action: 'get_drive_auth_url',
auth_code: auth_code,
folder_id: folder_id
},
success:function(res) {
console.log(res);
},
error: function(errorThrown){ console.log(errorThrown);
alert('Error: ' + errorThrown.status + ' ' + errorThrown.statusText);
}
});
}
},
error: function(errorThrown){
alert('Error: ' + errorThrown.status + ' ' + errorThrown.statusText);
}
});
Error
Array( [error] => invalid_grant [error_description] => Bad Request)
Appreciate your help!
It was my mistake,
Replace below code,
$folder_id = trim($_POST['folder_id']) || null;
$auth_code = trim($_POST['auth_code']) || null; // This returns 1
to
$folder_id = trim($_POST['folder_id']);
$auth_code = trim($_POST['auth_code']); // This return the actual auth code
I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});