Login with Gmail on my site on the HTML page using javascript & PHP. The page will not be refreshed after login.
I am using this code.
<script>
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile www.googleapis.com/auth/userinfo.email';
var CLIENTID = '<Client ID>';
var REDIRECT = 'url/'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch (e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText) {
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
</script>
This code will redirect to anothe page but I want page will not be referesh. Only give the response in the form of (true, false) from server.
please give better solution for this.
Thanks in advance.
Related
Can anyone tell me why this error?
Server Log:
StandardWrapperValve[ws_site.ApplicationConfig]: Servlet.service() for servlet ws_site.ApplicationConfig threw exception
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
at com.google.gson.Gson.fromJson(Gson.java:791)
Javascript function, responsible for capturing the data of the filled form and sending to the server:
function save()
{
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name}';
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: obj
}).done(function (data)
{
alert(data);
});
}
Restful Java method:
#POST
#Path("data")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({MediaType.APPLICATION_JSON})
public String registerUser(Gson json)
{
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
u.setAddress(a);
userDAO.save(u);
return "Saved successfully!";
}
Save userDAO method:
public void save(User u) {
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (u.getId_User() == null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Using Gson to convert json into an object
You're not sending an object to the server, you're just sending a string:
var obj = '...';
Instead, send an object:
var objdata = {
"email_user": str_email,
"name_user": str_name
};
var objlocation = {
"country": str_country,
"state": str_state,
"city": str_city,
"neighborhood": str_neighborhood,
"street": str_street,
"number": str_number,
"zipcode": str_zipcode
};
var obj = {
"user": [objdata],
"endereco": [objlocation]
};
A string that looks like an object is still a string.
objdata was not populating correctly as valid json. Try with this:
function save() {
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name + '"}';
console.log(objdata);
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
console.log(objlocation);
var obj = '{"user":[' + objdata + '],"endereco":[' + objlocation + ']}';
console.log(obj);
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: JSON.parse(obj)
}).done(function (data) {
alert(data);
});
}
In your server side you are trying bind JSON data.
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
It mean user and endereco should be a JSON objects like below.
{
"user":{
"email_user":"str_mail","name_user":"nameeee"
},
"endereco":{
"country":"str_country","state":"str_state","city":"str_city","neighborhood":"str_neighborhood","street":"str_street","number":"str_number","zipcode":"str_zipcode"
}
}
But in your case user and endereco are actually a JSONArray's(See the square brackets.).
{
"user":[
{
"email_user":"str_mail",
"name_user":"nameeee"
}
],
"endereco":[
{
"country":"str_country",
"state":"str_state",
"city":"str_city",
"neighborhood":"str_neighborhood",
"street":"str_street",
"number":"str_number",
"zipcode":"str_zipcode"
}
]
}
So change below line
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
to
var obj = '{"user":'+objdata+',"endereco":'+objlocation+'}';
I am using Google Authentication in Web Application and while log in with Google..if user click on "Deny" option..It still redirect to "Authorized redirect URIs" which i mentioned in Console Developers of google.
<script type="text/javascript">
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = // My Client Id;
var REDIRECT = 'http://localhost:49234/Account/GoogleSign';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
$(document).ready(function () {
login();
});
function login() {
debugger;
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function () {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch (e) {
}
}, 5000);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function (responseText) {
//alert("Call")
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function (resp) {
user = resp;
// console.log(user);
IsAuthenicated(user.id, user);
$('#txtFirstName').val(user.name);
$('#txtEmail').val(user.email);
},
dataType: "jsonp"
});
}
function gup(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
function IsAuthenicated(GoogleId, user) { //This function call on text change.
$.ajax({
type: "POST",
url: "http://localhost:49233/AutoComplete.asmx/IsGoogleAuthenicated", // this for calling the web method function in cs code.
data: '{GoogleId: "' + GoogleId + '" }',// user name or email value
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
}
});
}
// function OnSuccess
function OnSuccess(response) {
//alert('s ' + response.d);
debugger;
var retval = response.d;
if (retval == '0') {
$('#txtFirstName').val(user.name);
$('#txtEmail').val(user.email);
$('#hdgmailId').val(user.id);
$('#hgverified').val(user.verified_email);
$('#hglocale').val(user.locale);
$('#hdgiven_name').val(user.given_name);
}
else {
window.open("http://localhost:49233/Dashboard.aspx?Id=1&number=" + response.d, "_self");
}
}
</script>
Can someone suggest better approach how to handle Deny option? And also if i have opened 2 gmail account in same browser then also it is not redirecting me to my application after click on "Allow" access.
I am working phonegap application. I want to send data image to server but i can not sent it.
function addSiteToServer() {
var cId = localStorage.getItem("cId");
var sname = $('#sitename').val();
var slat = $('#lat').val();
var slng = $('#lng').val();
var storedFieldId = JSON.parse(localStorage["field_id_arr"]);
var p = {};
for (var i = 0; i < storedFieldId.length; i++) {
var each_field = storedFieldId[i];
var val_each_field = $('#' + each_field).val();
p[each_field] = val_each_field;
console.log("p" + p);
}
var online = navigator.onLine;
if (online) {
var data = {
site: {
collection_id: cId,
name: sname,
lat: slat,
lng: slng,
properties: p
}
};
//function sending to server
$.ajax({
url: App.URL_SITE + cId + "/sites?auth_token=" + storeToken(),
type: "POST",
data: data,
enctype: 'multipart/form-data',
crossDomain: true,
datatype: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("data: " + data);
alert("successfully.");
},
}
Looks like you are using the normal method to send data/image to server which is not recommended by Phonegap/Cordova Framework.
I request you to replace your code with the following method which works as you expected,I also used local storage functionality to send values to server,
function sendDataToServer(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.some_text = localStorage.getItem("some_text");
params.some_id = localStorage.getItem("some_id");
params.someother_id = localStorage.getItem("someother_id");
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://example.co.uk/phonegap/receiveData.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode+"Response = " + r.response+"Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
function saveData(){
sendDataToServer(globalvariable.imageURI);
alert("Data Saved Successfully");
}
Hope this helps.
I have this code in a js file which I am including in Default page to Create cookies at the clients' browser and using it in the Thankyou page to invoke my web service to track payment transactions.
// Read a page's GET URL variables and return them as an associative array.
$(document).ready(function () {
$.extend({
getUrlVars: function () {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function (name) {
return $.getUrlVars()[name];
},
getCookie: function (name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return unescape(dc.substring(begin + prefix.length, end));
}
});
{
var cookieStart, cookieEnd, cookieValue, UserGuid, productId, AffiliationURL, PricePerUnit, commissionAmount;
// Get object of URL parameters
if ($.getUrlVars() != null) {
var allVars = $.getUrlVars();
}
// Getting URL var by its name
//Now check if the user is from Seek Site??
//If this is not null that means the user is Refered from Seek Site
if ($.getUrlVar('clientId') != null) {
UserGuid = $.getUrlVar('clientId');
if ($.getUrlVar('productId') != null) {
productId = $.getUrlVar('productId');
}
if ($.getUrlVar('AffiliationURL') != null) {
AffiliationURL = $.getUrlVar('AffiliationURL');
}
if ($.getUrlVar('PricePerUnit') != null) {
PricePerUnit = $.getUrlVar('PricePerUnit');
}
if ($.getUrlVar('commissionAmount') != null) {
commissionAmount = $.getUrlVar('commissionAmount');
}
//Now Create the cookie for the user
var myCookie = $.getCookie("ReferedCookie");
alert(myCookie);
if (myCookie != null) {
// cookie exists
cookieStart = myCookie.indexOf("clientId=");
//alert(cookieStart = cookieStart + "ReferedCookie=".length);
cookieEnd = myCookie.indexOf(";", cookieStart);
//if there is no occurence of the semicolon character
//cookieEnd takes the length of the document.cookie property
if (cookieEnd == -1) cookieEnd = myCookie.length;
cookieValue = myCookie.substring(cookieStart, cookieEnd);
// check the Product Id
if (cookieValue.indexOf(productId + "&", "productId=") != -1) {
// that means the User clicked on the same Product again and there is already a cookie Exists for that product
alert("User clicked on the same Product again");
}
else {
// The Product Id is different ,We are going to add that product value as string to the cookie
}
}
else {
// Create Cookie
var expiryDate = new Date();
expiryDate.setTime(expiryDate.setDate(expiryDate.getDate() + 365)); // 365 days
document.cookie = "ReferedCookie=" + "clientId=" + UserGuid + "&productId=" + productId + "&AffiliationURL=" + AffiliationURL + "&PricePerUnit=" + PricePerUnit + "&commissionAmount=" + commissionAmount + ";" + "expires=" + expiryDate.toGMTString() + ";";
}
}
}});
And Here the Code which I want to run at Thankyou page but it runs in IE9 (at time I dnt know why???)
{
var cookieStart, cookieEnd, cookieValue, UserGuid, productId, AffiliationURL, PricePerUnit, commissionAmount;
$(window).load(function (e) {
e.preventDefault();
$.extend({
readCookie: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
});
var x = new Array(3);
cookieValue = $.readCookie("ReferedCookie");
var s = 0;
var pos = cookieValue.indexOf("&");
while (pos > -1) {
x[s] = pos;
pos = cookieValue.indexOf("&", pos + 1);
// alert(x[s]);
s++;
}
var c1 = cookieValue.indexOf("clientId=");
alert(UserGuid = cookieValue.substring(c1 + 9, x[0]));
var p1 = cookieValue.indexOf("productId=");
alert(productId = cookieValue.substring(p1 + 10, x[1]));
var A1 = cookieValue.indexOf("AffiliationURL=");
alert(AffiliationURL = cookieValue.substring(A1 + 15, x[2]));
var pp1 = cookieValue.indexOf("PricePerUnit=");
alert(PricePerUnit = cookieValue.substring(pp1 + 13, x[3]));
var com1 = cookieValue.indexOf("commissionAmount=");
alert(commissionAmount = cookieValue.substring(com1 + 17));
var ServiceURL = 'http://localhost:12445/Service/TrackPayment.asmx/InsertCommissionRecord';
// var d = '{"ProductID": "' + productId + '" , "AffiliationURL": "' + AffiliationURL + '" , "Quantitiy": "' + 15 + '" , "PricePerUnit": "' + PricePerUnit + '" , "commissionAmount": "' + commissionAmount + '"}';
var d = '{"ProductID":"1","AffiliationURL":"1","Quantitiy":"1","PricePerUnit":"1","commissionAmount":"1"}';
alert(d);
$.ajax({
type: 'POST',
data: d,
url: ServiceURL,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
alert(data);
alert(textStatus);
alert(XMLHttpRequest);
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
});}
In firebug console it show data.d is null
Kindly help me out and please point out where I am going wrong.
Thanks
JS:
$.ajax({
type: 'POST',
data: {'d': d},
url: ServiceURL,
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
alert(data.ProductID); // returns '1'
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
test.php:
$data = json_decode($_POST['d']);
echo json_encode($data);
I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. I need to somehow define the query terms in my window.location.hash.replace so I am just left with the search type from the URL. How can I go about changing the QUERYGOESHERE in my example below to the query the user has made? I hope people can understand my question.
My jQuery Script is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
if (window.location.hash != "") {
url = window.location.hash.replace('#', '').replace('/QUERYGOESHERE/', '');
$('#type_' + url).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
This should do it.
var full = window.location.hash.replace('#', '')
var queryType = full.substring(0,full.indexOf("/"))
var query = full.replace(queryType, '');
EDIT: Updated code
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0,full.indexOf("/"));
console.log('#type_' + queryType);
$('#type_' + queryType).click();
}