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
Related
controller
).controller('LoginController',
[
'$scope',
'dataService',
'$location',
'$window',
function ($scope, dataService, $location,$window){
$scope.check_login=function($event,userID,passwd)
{
dataService.login(userID,passwd).then
(
function (response){
$scope.loginCount = response.rowCount + 'account Record';
$scope.loginConfirm = response.data;
console.log(response.data);
},
function (err) {
$scope.status = 'unable to connect to data' + err;
});
// $scope.reloadRoute = function () {
// $location.path('/#');
// $window.location.reload()
// }//end of reload route fnction
}//end of function check_login
}
]
Services.js
this.login = function (userID, passwd) {
var defer = $q.defer(),
data = {
username: userID,
password: passwd
};
$http.post(urlBase, {
params: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
cache: true
})
. // notice the dot to start the chain to success()
success(function (response) {
defer.resolve({
data: response.login.Result, // create data property with value from response
rowCount: response.login.RowCount // create rowCount property with value from response
});
})
. // another dot to chain to error()
error(function (err) {
defer.reject(err);
});
// the call to getCourses returns this promise which is fulfilled
// by the .get method .success or .failure
return defer.promise;
};
index.php
if (isset($_POST['username']) && isset($_POST['password'])) {
$useremail = $_POST['username'];
$password = $_POST['password'];
$service = new FilmsService();
$result = $service->login($useremail, $password);
echo $result;
} else {
echo "Cant Find The Data";
}
Currently i got 3 file name controller,service.js and index.php , service.js is u to pass the data to the php side, but when i try to get the username and password in the php side, it will be error.Cant get the username and password.
How to solve it? is it my code error?
Try this in place of your $http.post:
$http({
method: 'POST',
url: urlBase,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
});
Im working on a mobile application, trying to send data from the app to an API though jQuery Ajax. It keeps giving me a callback error even though i defined my callback.
Code below is the jQuery Ajax connecting to the API
function isDashboard(){
var task = 'balance';
var json = { // Create object
"task" : task,
"merchant" : getSession('x_u'),
"token" : getSession('x_token')
};
var jsonfull = []; // Push to jsonfull.
jsonfull.push(json);
var url = JSON.stringify(json);
var crypt = CryptoJS.SHA512(getSession('x_token')+task+getSession('x_email')+url).toString(CryptoJS.enc.Hex);
$.ajax({
url: "http://samplesite.com/?p=app&'",
crossDomain: true,
data: {
json : url,
hash :crypt
},
dataType: "jsonp"
})
.done(function (json){
$('#welcome').prepend(json.response);
alert(json.response);
})
.fail(function (jqxhr, textStatus, error){
var err = textStatus + ", " + error;
$('#welcome').prepend(err);
});
}
On my receiving file in php, i have
$rest = $_GET['json'];
$api = json_decode($rest,true);
$type = "json";
// did some processing with $api
//returning response to the app
$out = [];
$out['response'] = 'X006';
$out['description'] = 'Invalid hash';
$out['values'] = '';
$out['salt'] = $salt;
$out['hash'] = '';
if($type == 'json'){
header('Content-Type: text/json');
$out = $_GET['callback'].'('.json_encode($out).')';
}
echo $out;
die();
i keep getting the error parsererror, Error: jQuery1111036580699938349426_1446328908674 was not called
ill appreciate any help i can get. Regards
I am working with Laravel 4 and I want to perform validation with Ajax. I have 2 main problems:
1. The URL at Ajax is static, which means that if I have my app online I should put the URL for online and locally doesn't works
2. my route is insur_docs/{id} how should be URL for this?
jQuery('form#insur_docs_update').submit(function()
{
jQuery.ajax({
url: "http://localhost:8080/insur_docs/{id}", //my url I don't know how to put it
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
})
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
jQuery.each(arr, function(index, value)
{
if (value.length !== 0)
{
$("#validation-div").addClass('alert alert-danger');
document.getElementById("validation-div").innerHTML += '<span class="glyphicon glyphicon-warning-sign"></span>' + value + '<br/>';
}
});
jQuery('#ajax-loading').hide();
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
routes.php
Route::get('insur_docs/{id}', 'Insur_DocController#edit');
controller
public function update($id) {
Input::flash();
$data = [
"errors" => null
];
$rules = array(
"ownership_cert" => "required",
"authoriz" => "required",
"drive_permis" => "required",
"sgs" => "required",
"tpl" => "required",
"kasko" => "required",
"inter_permis" => "required",
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->passes()) {
$car_id = DB::select('select car_id from insur_docs where id = ?', array($id));
$data = InsurDoc::find($id);
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->save();
return Redirect::to('car/' . $car_id[0]->car_id);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => $validation->errors()->toArray()
);
return Response::json($response_values);
}
}
}
Use laravel's url generator helper to create your form's action:
<form action="{{ URL::action('Insur_DocController#edit', $id) }}" method="post">
You can access it in your javascript:
jQuery('form#insur_docs_update').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
});
}
EDIT
You're second problem is that you're redirecting in response to the ajax call, and that does not redirect the page. You'll need to return the url and do the redirect in javascript like this.
Controller:
return Response::json(["redirect_to" => 'car/' . $car_id[0]->car_id]);
JS (just the relevant part):
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
// your code
} else {
window.location = data.redirect_to;
}
})
var myUrlExtension = "whatever.php"
and inside the ajax
url: "http://localhost:8080/insur_docs/" + myUrlExtension
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.
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;
});