i am trying to use gigya auth properties to login users on my website. They have a function that needs to be called after i authenticate the credentials as seen in this illustration
I have a form and when i submit the form i send it to login.php where i authenticate my users. My question is how do i call socialize.notifyLogin?.
this is the javascript:
<script type="text/javascript"> var conf = { APIKey:'2_9E9r_ojXEqzZJqKk7mRqvs81LtiSvUmBcm' }; </script>
<script type="text/javascript">
var secret = 'eIqtclW2CxC6qvmT55MvOxZ5Rm7V5JhBV/gioJLKIxM=';
var yourSiteUid= '<?php echo $talentnum;?>'; // siteUID should be retrieved from your user management system
function your_b64_hmac_sha1(secret, datePlusSite) {
var b64Sig = ''; // Place your implementation here ...
return b64Sig;
}
function printResponse(response) {
if ( response.errorCode == 0 ) {
alert('After notifyLogin');
}
}
var dateStr = getCurrentTime();
var datePlusSite = dateStr + "_" + yourSiteUid;
var yourSig = your_b64_hmac_sha1(secret, datePlusSite);
var params={
siteUID:yourSiteUid,
timestamp:dateStr,
signature:yourSig,
callback:printResponse
};
gigya.services.socialize.notifyLogin(conf,params);
</script>
to be more clear i set the $talentnum; inside my login.php. so i have the form i send it ti the login.php and a redirect page... Where the call to socialize.notifyLogin will be?
thanks,
any idea helps
You have two options:
If you call login.php as the target of an HTML form, you should redirect the user to a new HTML page upon successful login. This new HTML page should contain the socialize.notifyLogin call.
If you call login.php via an AJAX request, you should call socialize.notifyLogin in the "success" callback of the AJAX request.
In no case, however, will you be able to execute the Javascript function directly from your PHP script. PHP executes on the server before the Javascript is sent to the user as output with your HTML document, and therefore cannot execute Javascript functions directly.
PHP is executed before the page loads, therefore you cannot call a JavaScript function from PHP.
Related
Just want to ask if is it possible to clear a PHP session using a jquery or javascript process? Because what I want to do is to clear the PHP session using a dialog box. If the user click the 'OK' button it will process the unset function. In my page there's a checkout process and after the user click the button 'OK' it will prompt a dialog box and if the user click the 'OK' button it will unset the PHP session and it will be redirected to another page.
Here's my simple code:
<i class="fa fa-check"></i> <span id="save_registry" class="cursor: pointer">OK</span>
<div id="save_alert" style="display: none">
<?php unset($this->session->data['cart']);
</div>
....
$('#save_registry').click(function(){
$('#save_alert').dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
location = 'index.php?route=common/home';
}
}
});
});
Simply put: You can't, directly.
PHP is a server-side language while javascript is a client-side one, which means that there's no other connection between them other than the document you receive and interacts with you. The sessions are stored and managed by the server.
You can, however, as War10ck suggests, call to a server-side script that clears the session. Something like this:
PHP:
<?php
/*
* session_start();
* Starting a new session before clearing it
* assures you all $_SESSION vars are cleared
* correctly, but it's not strictly necessary.
*/
session_destroy();
session_unset();
header('Location: continue.php');
/* Or whatever document you want to show afterwards */
?>
HTML/javascript:
<script type="text/javascript">
function logout() {
document.location = 'logout.php';
}
LogoutButton.addEventListener('click', logout, false);
</script>
<button id="LogoutButton">Log out</button>
Or even performing an asynchronous call:
function logout() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
document.location = 'continue.php';
}
xhr.open('GET', 'logout.php', true);
xhr.send();
}
There is a way you can do it directly from javascript... first you have to declare a function that clears a cookie by its key
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=/";
}
Now all you have to do is to remove a cookie with the key "PHPSESSID" like this
removeCookie("PHPSESSID");
Now when you var_dump($_SESSION) you find it empty array
You can't clear a php session using Javascript directly.
PHP is a server-side language, whereas Javascript is client-side..
However, you can throw an ajax request to the specified page that handles the destruction.
Like this:
// Client-side
$.post("logout.php", {"can_logout" : true}, function(data){
if(data.can_logout)
// redirect the user somewhere
}, "json");
<?php
// Server-side
$can_logout = $_POST["can_logout"];
if($can_logout)
session_destroy();
echo json_encode(array("can_logout" => true));
?>
Or just point the user to some page that handles the session destruction; i.e. logout.php
On my homepage I'm using the maximage fullscreen image plugin. When someone clicks on a
specific link (product page), I must find out what the current image in the slideshow is
and set it as the background-image in the product index page.
I'm making an ajax call the moment someone clicks the '/producten' link on the homepage and store it as a session variable.
The problem is, it's not making an ajax call, I can't see the POST request in my apache logfile, only the GET request for the '/producten' page. Is it going to fast? Can't I do a POST request just before I make the GET request? I can't pinpoint it. Here's my code:
homepage index:
jQuery(document).ready(function($)
{
$("a[href='/producten']").click(function() {
var best;
var maxz;
$('.mc-image').each(function() {
var z = parseInt($(this).css('z-index'), 10);
if (!best || maxz<z) {
best = this;
maxz = z;
}
});
var bg_image = $(best).css('background-image');
bg_image = bg_image.replace('url(','').replace(')','');
$.post('/producten', {bg_image:bg_image});
});
});
bg_image is set correctly, I tested it with a console.log(), and I get output.
/producten index:
<?php
session_start();
$_SESSION['bg_image'] = $_POST['bg_image'];
?>
In javascript:
/* $.post('/producten', {bg_image:bg_image}); */
this.href = this.href + '?bg_image=' + escape(bg_image)
In php:
if(isset($_GET['bg_image'])) {
$_SESSION['bg_image'] = $_GET['bg_image'];
header('Location: /producten');
exit;
}
Pages loaded via AJAX methods. index.php is the base page, profile.php is the page loaded
jQuery: ("post" nothing to do with HTML request)
$('<a/>', {href: '?userID='+post['userID']+'#profile'}).text(post['firstName']+' '+post['lastName'])
HTML:
Firstname Lastname
Raw URL (after click)
http://########/#####/index.php?userID=1#home
$_GET print_r on profile.php:
Array ()
By request; the ajax load javascript (index.php):
//AJAX page loading
$(document).ready(function(){
//Default page
if(!window.location.hash)
window.location.hash = '#home';
//Check page reference
checkURL();
//Update nav
$('#main-nav li').on("click", function (){
$('#main-nav li').removeClass('active');
$(this).addClass('active');
//Assign each link a new onclick event, using their own hash as a parameter
checkURL(this.hash);
});
//check for a change in the URL every 250 ms to detect if the history buttons have been used
setInterval("checkURL()",250);
});
//Store the current URL hash
var lasturl="";
function checkURL(hash){
if(!hash)
//if no parameter is provided, use the hash value from the current address
hash=window.location.hash;
if(hash != lasturl) {
//If hash changed, update current hash and load new one
lasturl=hash;
loadPage(hash);
}
}
function loadPage(url) {
//Adjust page name
url=url.replace('#','');
url=url+'.php';
//AJAX load page contents in to main content div
$('#content').load(url);
}
Solution:
Create global storage on root page (index.php).
Set vars in storage instead of using $_GET.
Access vars from child pages.
Example:
index.php (Javascript)
if (typeof(window.storage) === 'undefined') {
window.storagePV = {};
}
$('#nav-profile').click(function() {
window.storage.userID = <?php echo "$_SESSION[userID]"; ?>;
});
accessing userID to view the user's profile page
var userID = window.storage.userID
How can I add redirect URL link to JS function (example form action to : session.php) in below code.
I've tried with another way code, but it still can't function.
$(document).ready(function() {
$("#submit_butt").click(function() {
var conf = {
frequency: 5000,
spread: 5,
duration: 600
};
/* do your AJAX call and processing here...
....
....
*/
// this is the call we make when the AJAX callback function indicates a login failure
$("#login").vibrate(conf);
// let's also display a notification
if($("#errormsg").text() == "")
$("#loginform").append('<p id="errormsg">Invalid username or password!</p>');
// clear the fields to discourage brute forcing :)
$("#password").val("");
document.forms['login_form'].elements['username'].focus();
});
});
You can try this
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
https://developer.mozilla.org/en-US/docs/DOM/window.location
Ref: How to redirect to another webpage in JavaScript/jQuery?
you can use this..
window.location.href = "http://www.google.com";
you can try
<script>
function name(){
window.location ='abc.php';
}
</script>
you can by breaking into php code inside your javascript
$(document).ready(function()
{
<?php
someFunction();
?>
});
but only if your javascript is in a php file so it can be processed by php. So if your linking to a .js file that needs to be changed to .php
I'm trying to run a quick php script when users leave my website, and also pass a variable from my javascript to php but i'm not quite sure how to include the php file and pass it a var. But it's not actually running the php script. any ideas?
(the javascript gets the username from an external activity function, and i know that works i tested the var on an alert and its there.)
My JavaScript:
<script language="javascript" type="text/javascript">
var username = null;
function GetUsername(usernameff)
{
username = usernameff;
}
window.onbeforeunload = function ()
{
if (username != null)
{
<?php include("scripts/RemoveUserOnDisconnect.php?username=username");?>
}
}
</script>
My RemoveUserOnDisconnect.php File:
<?php
mysql_connect("mysql.mysql.com", "username", "password");
mysql_select_db("my_db");
mysql_query("DELETE FROM my_table WHERE username = '$username'");
?>
Try an ajax request. Depending on your php script you will need $.post or $.get
jQuery:
<script language="javascript" type="text/javascript">
var username = null;
function GetUsername(usernameff){
username = usernameff;
}
window.onbeforeunload = function(){
if (username != null){
$.post('scripts/RemoveUserOnDisconnect.php', {username: username}, function(){
//successful ajax request
}).error(function(){
alert('error... ohh no!');
});
}
}
</script>
EDIT:
Your php script should reference the $_POST array if you use my code above.
<?php
$username = $_POST['username'];
mysql_connect("mysql.mysql.com", "username", "password");
mysql_select_db("my_db");
mysql_query("DELETE FROM my_table WHERE username = '$username'");
?>
Make an ajax call to scripts/RemoveUserOnDisconnect.php?username=username. You cannot include PHP with Javascript, Javascript executes on the browser, PHP executes on the server..
You need to make an AJAX call to the PHP script. Your javascript code will just make a background request to the php script which will execute those MySQL statements. Google up AJAX. Recommended: Learn jQuery and use ajax using $.get() or $.post()