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()
Related
i have a page in php to execute query. when i need the parameter from another page with session using jquery. so, how to set session in php from session in jquery. please check my code and give me solution. thanks...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.ciphertrick.com/demo/jquerysession/js/jquerysession.js?d56ac9"></script>
<script>
$(document).ready(function(){
var sDecode = $.session.get("sesDecode");
alert(sDecode);
});
</script>
<?php
include('connection.php');
$content= ==> how to get " sDecode " ???
$upd = mysql_query("UPDATE t_modules set content='$content' where id_t_modules='3'") or die(mysql_error());
?>
You can use ajax to send parameter to a php file like this
$.ajax({
url: "connection.php",
data: "Session="+$.session.get("sesDecode"),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
Note that both solutions needs you to check the input since the user could potentially modify it.
Using Ajax
The best way to get sDecode is probably to send it via jQuery.post() (AJAX) to a PHP page that will register the session value (after doing the appropriate checks to it).
$.post('session.php', { d: sDecode }, function (response) {
alert(response);
});
and you get it in PHP via :
$sDecode = $_POST["d"]; // Please test the input here!
You might have to use .serialize() and then unserialize it in PHP depending on the content and how you treat it.
Using Redirection
You can simply redirect to a page and transmit it directly as a GET value:
window.location.href=”session.php?d="+sDecode;
Then on the session.php page you would read it using this code :
$sDecode = $_GET["d"]; // Please test the input here!
You can have PHP fill in the Javascript variable from the session variable.
<?php session_start(); ?>
<html>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sDecode = <?php echo json_encode($_SESSION['sDecode']); ?>;
alert(sDecode);
</script>
PHP execute before Jquery so use ajax after get the parameter from session to do your query
I have a php script, only for learning purposes. I would like to use on my web app ajax form. Never did it, this is testing php script. So I would like to send via ajax form name and password, in php script will be checked if its correct and it will return either success(when login and password correct) or error(when no match). My problem is how to send it and receive it correctly in js or jQuery. Anyone who could help me maybe with better idea and/or better secure function of doing this?
I found on stackoverflow and tryed this script:
//bind an event handler to the submit event for your login form
$('#login_form').live('submit', function (e) {
//cache the form element for use in this function
var $this = $(this);
//prevent the default submission of the form
e.preventDefault();
//run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request
$.post($this.attr('action'), $this.serialize(), function (responseData) {
//in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page
});
});
And I was wondering if in php script it could work like this?:
<?php
$username = $_GET["name"];
$password = $_GET["password"];
if($username="*****" && $password==********)
{
header('Location:http://*****************/jaz/imes/index.html?login="success"');
}else{
header('Location:http://*****************/jaz/imes/index.html?login="error"');
}
?>
And as I said this is just a test script just for learning more about it.
First of all, try to use on() method if you're using jQuery 1.8+
Another thing is that you should set the session for that user in the PHP script, then redirect the user using the js:
jQuery:
$('#login_form').on('submit', function(){
$.post($this.attr('action'), $this.serialize(), function (responseData) {
if(responseData == 'success'){
window.location = "userpanel.php"
}else{
alert('NO MATCHES');
}
});
});
PHP:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// VALIDATING HERE, in db maybe?
if($username == 'blah' && $password == 'blah'){
$_SESSION['username'] = $username;
echo "success";
}else{
echo "failed";
}
?>
And in your HTML form you need to have 2 inputs with IDs as "username" and "password" so the above code could work.
I have a php code that provides the database values. I need those values in the javascript variable.
Javascript Code
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text() {
var textVal=$("#busqueda_de_producto").val();
$.ajax(
{
type:"POST",
url:"index.php", //here goes your php script file where you want to pass value
data: textVal,
success:function(response)
{
// JAVSCRIPT VARIABLE = varable from PHP file.
}
});
return false;
}
</script>
PHP FILE CODE:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
?>
Your returning data is in the response parameter. You have to echo your data in PHP to get the results
Using JSON format is convenient
because of its key-value nature.
Use json_encode to convert PHP array to JSON.
echo the json_encoded variable
you will be able to receive that JSON response data through $.ajax
JavaScipt/HTML:
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text()
{
var textVal=$("#busqueda_de_producto").val();
$.post('index.php', { codigo:textVal }, function(response) {
$('#output').html(response.FIELDNAME);
}, 'json');
return false;
}
</script>
<span id="output"></span>
PHP:
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo='".mysql_escape_string($_POST['codigo'])."'";
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo json_encode($row11);
You aren't echoing anything in your PHP script.
Try altering your PHP to this:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo $row11; //This sends the array to the Ajax call. Make sure to only send what you want.
?>
Then in your Ajax call you can alert this by writing alert(response) in your success handler.
Tips
Send your data to the server as a URL serialised string : request=foo&bar=4. You can also try JSON if you fancy it.
Don't use mysql_* PHP functions as they are being deprecated. Try a search for PHP Data Objects (PDO).
i see lots of things that needs to be corrected
the data in your ajax do it this way data: {'codigo':textVal}, since you are using $_GET['codigo'], which leads to the second correction, you used type:"POST" so you must also access the $_POST variable and not the $_GET variable and lastly the target of your ajax does not display / return anything you either echo it or echo json_encode() it
The best solution is to use
echo json_encode("YOUR ARRAY/VALUE TO BE USED");
and then parse JSON in the javascript code as
obj = JSON.parse(response);
I'd like to know how can I use a jquery variable in a sql query?
Here is my jquery that is in my php file:
?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(function(){
jQuery('#event_form_field-<?php echo $event_id; ?>').click(function() {
var bradio = jQuery("input[type=radio]:checked").val();
alert(bradio);
}) });</script> <?php
I want to use the bradio variable in a sql query (on the Having clause, for example Having answer='$bradio'.
But i don't know how to passe the jquery variable in php.
Can you please explain me how can I do this?
Thanks.
You can use AJAX to pass the variable to a PHP script. That PHP script can also return data to the JavaScript AJAX call, for instance you can output error or success in your PHP file so the JavaScript code can alert the user as to what happened (in my example this response is saved in the serverResponse variable):
jQuery(function ($) {
$('#event_form_field-<?php echo $event_id; ?>').click(function() {
$.get('path/to/server-side.php', { 'bradio' : $("input[type=radio]:checked").val()}, function (serverResponse) {
//the server request has been made and has come back successfully
});
});
});
Some documentation:
$.get(): http://api.jquery.com/jquery.get
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.