Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need a hand with the below script, i am new at JSON and need to store some data to MYSQL database.
How can i do this? Or if you can assist with the script and a detailed explanation on how to store the user login with Facebook Javascript SDK to MYSQL database. To store they Name and ID
<?php
$sApplicationId = 'YOUR_APPLICATION_ID';
$sApplicationSecret = 'YOUR_APPLICATION_SECRET';
$iLimit = 99;
?>
<!DOCTYPE html>
<html lang="en" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta charset="utf-8" />
<title>Facebook API - Get friends list</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<img src="facebook.png" class="facebook" alt="facebook" />
<center>
<h1>Authorization step:</h1>
<div id="user-info"></div>
<button id="fb-auth">Please login here</button>
</center>
<div id="result_friends"></div>
<div id="fb-root"></div>
<script>
function sortMethod(a, b) {
var x = a.name.toLowerCase();
var y = b.name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
window.fbAsyncInit = function() {
FB.init({ appId: '<?= $sApplicationId ?>',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) { // in case if we are logged in
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
button.innerHTML = 'Logout';
});
// get friends
FB.api('/me/friends?limit=<?= $iLimit ?>', function(response) {
var result_holder = document.getElementById('result_friends');
var friend_data = response.data.sort(sortMethod);
var results = '';
for (var i = 0; i < friend_data.length; i++) {
results += '<div><img src="https://graph.facebook.com/' + friend_data[i].id + '/picture">' + friend_data[i].name + '</div>';
}
// and display them at our holder element
result_holder.innerHTML = '<h2>Result list of your friends:</h2>' + results;
});
button.onclick = function() {
FB.logout(function(response) {
window.location.reload();
});
};
} else { // otherwise - dispay login button
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
window.location.reload();
}
}, {scope:'email'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
Store your data in an array then use json_encode().
Have a look here.
In your for loop :
for (var i = 0; i < friend_data.length; i++) {
results += '<div><img src="https://graph.facebook.com/' + friend_data[i].id + '/picture">' + friend_data[i].name + '</div>';
$.ajax({
type: "POST",
url: "some.php",
data: { id : friend_data[i].id, name: friend_data[i].name }
});
}
in some.php :
$tmpArray = array('id' => $_POST['id'], 'name' => $_POST['name']);
$output = json_encode($tmpArray); // <-- save this in your db, if you want to store a JSON string, but it doesn't seem to be optimized. You'd better to save ID and name.
Related
I'm a newbie in API requests and javascript...
I try to use an API based on the OAuth2.0 protocole (Autorisation Code Grant).
I don't understand how i can pass the first step :
why my request don't generate the redirection to the redirect_uri ?
after, how to catch the url params contain in this redirection url ?
Here, my actual code :
const link = 'https://gw.hml.api.fr/group/espace-particuliers/consentement/oauth2/authorize?client_id=MY_API_CLIENT_ID&state=fz80ac780&duration=P6M&response_type=code&redirect_uri=https://gw.hml.api.fr/redirect';
const connect = document.getElementById('connect-btn')
if (connect) {
connect.addEventListener('click', function(event) {
event.preventDefault();
fetch(link)
.then(response => response.text())
console.log(response);
// HOW TO CATCH THE REDIRECTION_URI PARAMS ?
});
};
Exemple of response :
<html lang="fr">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>Veuillez patienter...</p>
<script type="text/javascript">
/**
* Delete cookies (iPlanetDirectoryPro, amlbcookie)
*/
function removeCookie(cookieName) {
cookieValue = "";
cookieLifetime = -1;
var date = new Date();
date.setTime(date.getTime() + (cookieLifetime*24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = cookieName+"=" + JSON.stringify(cookieValue) + expires+"; path=/; domain=.ene.fr";
}
removeCookie("iPlanetDirectoryPro");
removeCookie("amlbcookie");
/**
* Parse url query
*/
var parseQueryString = function( queryString ) {
var params = {}, queries, temp, i, l;
// Split into key/value pairs
queries = queryString.split("&");
// Convert the array of strings into an object
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
};
var url = "https://gw.hml.api.fr/redirect?code=sD4F5RT3qPPJ15qFhrGu32YiumzN5D&state=fz80ac780&usage_point_id=225158214714453";
// Get redirect_uri params
var queryString = url.substring( url.indexOf('?') + 1 );
var params = parseQueryString(queryString);
var forceNonAutomaticClose = params.close !== undefined && params.close == 'false';
// Avoid closing popup
if (forceNonAutomaticClose || !this.window.opener || this.window.opener.closed) {
this.window.location.href = url;
} else if (this.window.opener && !this.window.opener.closed) {
// Close popup
this.window.opener.location.href = url;
this.window.close();
}
</script>
</body>
</html>
How I can complete my code ?
Thanks !
I'm opening a new window to display a report using javascript and jquery in an MVC 4 application. The code is as follows.
window.open method:
$(document).ready(function () {
// validation stuff
submitHandler: function (form) {
var brewery = document.getElementById('BrewerySelect').value;
var line = document.getElementById('LineSelect').value;
var day = document.getElementById('datepicker').value;
var width = window.innerWidth * 0.66;
var height = width * window.innerHeight / window.innerWidth;
var urlStr = '/DashboardReport/Report?brewery=' + brewery + '&line=' + line.trim() + '&day=' + day;
alert(urlStr);
window.open(urlStr, 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
});
});
The controller does nothing, which I have tried as both PartialViewResult and ActionResult, the rest of the methods in the controller work fine for the ajax calls. The report works in a modal.:
public ActionResult Report()
{
return View();
}
The page that is opened:
#{
Layout = null;
}
<html>
<head>
<title>Report</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="reportBody" style="height: 100%;">
</div>
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/scripts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var brewery = GetURLParameter('brewery');
var line = GetURLParameter('line');
var day = GetURLParameter('day');
alert('document hit');
SetReport(brewery, line, day);
});
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
function SetReport(brewery, line, day) {
var url = '#Url.Action("GetUrl")';
alert('SetReport Hit ( action url = ' + url + ')');
$.ajax({
url: url,
data: { breweryCode: brewery, packageLine: line, date: day },
dataType: 'json',
cache: false,
type: "POST",
success: function (data) {
alert('SetReport success. data = ' + data);
var url = '<iframe src="' + data + '" height="100%" width="100%" scrolling="auto"></iframe>';
$('#reportBody').html(url).show();
},
error: function (response) {
alert('document.ready() dashboardReportForm SetForm() method failed');
}
});
}
</script>
</body>
</html>
I've set alerts throughout the javascript to let me know what is getting hit, but none of the alerts are firing. The document.ready function is not being hit.
There's a U+200b character after the ending bracket of GetURLParameter function, which causes syntax error. Remove it and it should work.
See No visible cause for "Unexpected token ILLEGAL"
This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 6 years ago.
I'm trying to execute a callback after multiple jQuery Ajax have completed.
In my code both Ajax requests call another function and when I try to use these functions I get undefined.
I think the problem has to do with using deferred/promise, but I don't know how to use them.
Here is my code:
<link rel="stylesheet" type="text/css" href="https://tag/sites/ocean1/maker/captions/shared%20documents/Web_ComplianceCSS.txt">
<div id = "cabbage" style="font-size:10px">
<p>Web Compliance Stats</p>
</div>
<script type = "text/javascript">
var WebComplianceReportApp = {} || WebComplianceReportApp;
WebComplianceReportApp.GetStatuses = (function() {
var pub = {},
_userId,
_ultimateObjectHolderArr = [],
_items = [],
_options = {
listName: "M_Web_Compliance",
container: "#cabbage",
};
pub.init = function() {
var clientContext = new SP.ClientContext.get_current();
_userId = clientContext.get_web().get_currentUser();
clientContext.load(_userId);
clientContext.executeQueryAsync(getUserInfo, _onQueryFailed);
};
function getUserInfo() {
_userId = _userId.get_id();
getSpecifiedList(_options.listName, _userId);
}
function buildObject(results, listName) {
_items = results.d.results;
$.each(_items, function(index, item) {
_ultimateObjectHolderArr.push({
"Division": item.ParentOrg,
"ORG": item.ORG,
"URL": item.URL,
"Status": item.Site_Status
});
});
//createStatusView2(_ultimateObjectHolderArr);
}
function getSpecifiedList(listName, userId) {
var counter = 0;
var baseUrl = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url1 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages";
var call1 = $.ajax({
url: url1,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
var url2 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages&$skiptoken=1000";
var call2 = $.ajax({
url: url2,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
}
function createStatusView2(Arr) {
var divisionArr = [];
var oRGArr = [];
var divisionCount = 0;
var oRGCount = 0;
for (var i = 0; i < Arr.length; i++) {
if ($.inArray(Arr[i].Division, divisionArr) === -1) {
divisionArr.push(Arr[i].Division);
var divisionHolderElement = $("<div id='p_" + Arr[i].Division + "' class='division_row_holder'></div>");
var divisionElement = $("<div id='" + Arr[i].Division + "' class='division_div ORG'></div>").text(Arr[i].Division);
$("#cabbage").append(divisionHolderElement);
$(divisionHolderElement).append(divisionElement);
}
if ($.inArray(Arr[i].ORG, oRGArr) === -1) {
oRGArr.push(Arr[i].ORG);
var orgElement = $("<div class='org_div ORG' id='" + Arr[i].ORG + "' style='font-size:10px;'></div>").text(Arr[i].ORG);
$("#p_" + Arr[i].Division).append(orgElement);
}
}
}
//automatically fired by init
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return pub
}());
$(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
//After the SP scripts are run, we access the WebComplianceReportApp.GetStatuses
WebComplianceReportApp.GetStatuses.init();
});
});
</script>
I dont know if this will make your code dirty, but I would use a flag in this case
ex:
var ajaxCalls = 0;
function checkAjaxCalls()
{
if (ajaxCalls == 2)
{
//do your thing...
//and maybe you want to reset ajaxCalls value to zero if needed...
}
}
And from each Ajax response completes, increment ajaxCalls variable by one, and call the checkAjaxCalls function from both your Ajax responses.
Method One:
This time we'll have waited for the request to complete instead of waiting for the request to succeed
$(".ajax-form-button-thingy").on("click", function() {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
error: function() {
throw new Error("Oh no, something went wrong :(");
},
complete: function(response) {
$(".ajax-form-response-place").html(response);
}
});
});
Method Two:
If you want to wait for ALL Ajax requests to complete without changing the async option to false then you might be looking for jQuery.ajaxComplete();
In jQuery every time an Ajax request completes the jQuery.ajaxComplete(); event is triggered.
Here is a simple example but there is more info on jQuery.ajaxComplete(); over here.
$(document).ajaxComplete(function(event, request, settings) {
$(".message").html("<div class='alert alert-info'>Request Complete.</div>");
});
Also you can take a look at the Ajax response by using request.responseText this might be useful in case you want to double check the response.
For more information about jQuery.ajax you can read the docs here
You could call createStatusView(); and then call createStatusView2(); after all of your Ajax requests are done
$(document).ready(function(){
createStatusView();
$(this).ajaxStop(function() {
// NOTE: I did not see you use createStatusView(); in your code
createStatusView2();
});
});
I'm working on an rss feed displayer for a webpage. I cant use PHP or Google API's.
But can use Javascript, HTML and such.
I created some code before but that used Google API's. I can't find a way how to use the code without Google API's.
Here is the code that i used before:
<script type="text/javascript">
$(function(){
var feedUrl = 'www.feed.com' + 'feed'; //Example
var postsToShow = 3;
$.ajax({
type: 'GET',
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=' + postsToShow + '&callback=?&q=' + encodeURIComponent(feedUrl),
dataType: 'json',
success: function(xml){
if(xml.responseData == null){
alert('Unable to load feed, Incorrect path or invalid feed');
}
else
{
values = xml.responseData.feed.entries;
console.log(values);
for(var i = 0; i < postsToShow; i++){
if(i >= values.length){
break;
}
var title = values[i].title;
var content = values[i].contentSnippet;
var link = values[i].link;
if(title != null && content != null && link != null){
$('<a>',{
id: 'wpPostTitle' + i,
class: 'wpPostTitle',
title: title,
href: link,
text: title
}).appendTo('#wpFeed');
$('<p>',{
id: 'wpPostContent' + i,
class: 'wpPostContent',
title: title,
html: ''+ content + ''
}).appendTo('#wpFeed');
}
}
}
},
});
});
</script>
I have implemented google plus login in my website using javascript:
<div id="googlenew">
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
function logout()
{
alert("in logout");
gapi.auth.signOut();
location.reload();
}
function login()
{
alert("in login");
var myParams = {
'clientid': '11818350844-r7c61fc96gjtor64oa75ccaun1k52gni.apps.googleusercontent.com',
'cookiepolicy': 'single_host_origin',
'callback': 'loginCallback',
'approvalprompt': 'force',
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
};
gapi.auth.signIn(myParams);
}
function loginCallback(result)
{
alert("in login call back");
if (result['status']['signed_in'])
{
alert("Is signed in:"+result['status']['signed_in']);
var request = gapi.client.plus.people.get(
{
'userId': 'me'
});
request.execute(function(resp)
{
var email = '';
if (resp['emails'])
{
for (i = 0; i < resp['emails'].length; i++)
{
if (resp['emails'][i]['type'] == 'account')
{
email = resp['emails'][i]['value'];
}
}
}
var str = "Name:" + resp['displayName'] + "<br>";
str += "Image:" + resp['image']['url'] + "<br>";
str += "<img src='" + resp['image']['url'] + "' /><br>";
str += "URL:" + resp['url'] + "<br>";
str += "Email:" + email + "<br>";
document.getElementById("profile").innerHTML = str;
});
}
}
function onLoadCallback()
{
alert("in onLoadCallback");
gapi.client.setApiKey('11818350844-r7c61fc96gjtor64oa75ccaun1k52gni.apps.googleusercontent.com');
gapi.client.load('plus', 'v1', function() {
});
}
</script>
</div>
<input type="button" value="Login" onclick="login()" />
<input type="button" value="Logout" onclick="logout()" />
<div id="profile">User Information</div>
The login works fine.
function onLoadCallBack() works fine.
function login() works fine.
But in loginCallBack(result) funciton,
alert("Is signed in :"+result['status']['signed']);
gives me alert with:
Is signed in true
after logging in. And what happens after that i dont know, nothing is happening.
gapi.client.plus.get({'userid':'me'})
doesnot respond with anything.. can any one helpp me asap?
Thank you
I am etting this error in my browser console:
XMLHttpRequest cannot load https://gateway.zscaler.net/auD?origurl=https%3A%2F%2Fcontent%2egoogleapis%…dr7c61fc96gjtor64oa75ccaun1k52gni%2eapps%2egoogleusercontent%2ecom&wexps=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://content.googleapis.com' is therefore not allowed access.