Passing Session variables to javascript [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
In an ExpressionEngine template, I'm setting a PHP session variable in a javascript file like this: (Yes, EE will parse the PHP and add plug the values to the javascript)
<?php session_start(); ?>
function check_someone_else_result(data) {
waiting_list_flag = false;
<?php $_SESSION['waiting_list_flag'] = false; ?>
if(data.CanBuy=='YES'){
show_for_someone_else();
} else {
waiting_list_flag = true;
<?php $_SESSION['waiting_list_flag'] = true; ?>
$('#sm_content .oblcontent').html($('#waiting_list').html());
$('#sm_content a.closebtn').click(function(){location.reload(true);});
$('#sm_content a.yeswaitbtn').click(function(){show_for_someone_else();});
} // if(data.CanBuy=='YES')
} // function check_someone_else_result
Now, in the show_for_someone_else() function, I'm redirecting to another page that loads another javascript file and I'm trying to set a javascript variable to the same value that I set the session variable to above.
<?php session_start(); ?>
var CART_URL = '{site_url}store/checkout/cart/';
$(document).ready(function(){
// attach the validationEngine to the form
$("#voucher_form").validationEngine('attach', {
scroll: false
}); // $("#voucher_form").validationEngine
// handles the NExt button click
$('#checkout-step-billing a').click(function(){
$('#checkout-step-billing .voucher_form').submit();
}); // $('#checkout-step-billing a').click
// handles keypresses in all the fields in the form to submit the
// form when the press enter
$("#checkout-step-billing .voucher_form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#checkout-step-billing .voucher_form').submit();
return false;
} else {
return true;
}
}); // $("#checkout-step-billing .voucher_form input").keypress
// set the wait_list_flag from the session variable
var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>
}); // $(document).ready
But I am not getting anything at all.
How do I need to do this?

var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>
should be
var wait_list_flag = <?php echo $_SESSION['waiting_list_flag']; ?>;
^^^^ ^
Without the echo, the PHP block doesn't output anything, so nothing gets inserted into the Javascript block. You're also missing the trailing semicolon in the javascript, which may also cause a fatal parse error.

To set the value, you will need to echo / print the $_SESSION['waiting_list_flag']; in the second snippet.
Keep in mind, in the first snippet, PHP will be run first (it's not run with the JavaScript), so the session var will always be true. (Unless that is what you meant wrt EE)

Related

Jquery Login Control in Php

I have a problem with jQuery. I'm checking the password and username with the code above.
It's working but the issue here is how can I send the data from this HTML form to my PHP file, or how can I start a session here and transfer it to PHP?
$("#girisButon").click(function (giris) {
if ($("#kadi").val() == "" || $("#sifre").val() == "")
alert('Username or Password is empty');
else
$.post($("#login").attr("action"),
$("#login :input").serializeArray(),
function (data) {
if (data == "1") {
$("#mesaj").removeClass("mesaj").addClass("basarili").text("OK").fadeIn(300);
// window.location.replace("index.php");
} else {
$("#mesaj").removeClass("basarili").addClass("mesaj").text("WRONG").fadeIn(300);
$("#giris").effect("shake", {
times: 2
}, 300);
}
});
$("#login").submit(function () {
return false;
});
});
$("#login").submit(function () {
window.location = 'phpprocessingpage.php';
});
Then, in phpprocessingpage.php, use POST variables to access any <input> elements that were part of the #login form:
$_POST['input1']
I like to save POST variables to my own local variables in this manner:
$input1 = (isset($_POST['$input1'])) ? $_POST['$input1'] : '';
You can't start a session on javascript and transfer it to PHP. You need to call PHP file on background with necessary parameters and start the session.
According to your script, you are currently making a request to your PHP file using $.post method, which takes URL from #login's action attribute.
Simply edit the PHP file and create sessions. After that, echo 1 to browser so javascript can understand your response.
Finally, this is the block that runs if server returns 1
if (data == "1") { }
Do whatever you want here. Sessions should be created.

Starting a PHP session on a jQuery function event

I've got a simple jQuery function and at a certain point (let's say on a button click) I'd like to start a PHP session.
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//here I'd need a way to trigger the session.
});
});
I would assume starting a session from PHP can be done as easily as changing a PHP variable. For example - the PHP can be something like:
<?php
$testVar = null;
if(isset($testVar)){
session_start()
$_SESSION['sessionStarted'] = $testVar;
}
?>
Is there a way for such as session to be started?
<?php
session_start();
if(isset($_GET['login'])) {
if(isset($_SESSION['sessionStarted'])) {
echo 'session is already set';
} else {
$_SESSION['sessionStarted'] = $testVar;
}
}
?>
and client-side:
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//code to redirect to index.php?login=true or make some ajax GET call, doesnt matter
});
});
then you can add like php checks, if session exists, do not echo loginPopupButton and so on :)

Call Javascript function from within PHP block [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to call a JavaScript function from PHP?
I'm working on a project for school, and I'm struggling with the login page. In my PHP code, if the user enters an incorrect username or password, I want to call a Javascript function that displays a message and briefly changes the background colour where the message is shown. Here are my JS and PHP code blocks:
<script>
var flashContent = function () {
document.getElementById("outputlogin").style.backgroundColor = "#ffff00";
document.getElementById("outputlogin").innerHTML = "Incorrect login.";
function proxy() {
updateColor(0);
}
setTimeout(proxy, 50);
}
var updateColor = function (newColor) {
var hexColor = newColor.toString(16);
if (hexColor.length < 2)
hexColor = "0" + hexColor;
var colorString = "#ffff" + hexColor;
document.getElementById("outputlogin").style.backgroundColor = colorString;
function proxy() {
updateColor(newColor);
}
if (newColor < 255) {
newColor = newColor + 5;
setTimeout(proxy, 50);
}
}
</script>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if(($username == "Ben") && ($password == "thepassword")){
//echo "SUCCESS";
session_start();
$_SESSION['bensedmgallerysesh'] = session_id();
header("Location:../index.php");
}else{
if($username != "" && $password != ""){
javascript:flashContent();
}
}
?>
Right now, after hitting the login button, I get the error message:
Fatal error: Call to undefined function flashContent()
How do I fix this?
You're trying to call a client side function in a server side script. You COULD do this:
if($username != "" && $password != ""){
?>
<script type="text/javascript">
flashContent();
</script>
<?php
}
But it might be smarter to actually separate the logic in a way that prevents you from trying to write server side processing like this. Organizational skills go a long way in this business.
Have you tried doing this:
echo '<script type="text/javascript"> flashContent(); </script>';
Instead of:
javascript:flashContent();
I dont think there is such thing like javascript: functionName()..
Javascript runs in user space, interpreted by the browser.
PHP runs in server space, and is processed by a preprocessor.
What you should do there is test the username and password in PHP, and if they are wrong send back a JSON reply to the client. In the client, parse the JSON data and show the corresponding message. You may want to do this with AJAX.
Hope that works
You cannot call a Javascript function like that with php, you would need to echo out the script calling the function in javascript. Something like this might work:
<?php
echo '<script> window.onload = function(){ flashContent(); } </script>';
?>
But that might not be a great way to do it. Php runs on the server before javascript runs on the browser. One better way to have the two languages communicate is to send AJAX calls to the php script.
EDIT
To clarify: You can echo out a call to a Javascript function in the script, and it will be run where you echoed it. But here, php will still just treat Javascript as a string to be printed on the document.

Getting through the DOM from the file to which I did a post request through ajax

I used this simplify examples to explain better the question.
given the following post request under ajax:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$code = $("#code");
$.post("ajax.php", {option : $var, code: $code}, function()
{
//Getting through the DOM could be useful if you want to analyse the answer coming from the ajax.php file
var $DOMresponse = getElementByTagName("div")[0].firstChild.data; // I would want the correct code here because this is incorrect... this is ti give you an idea
if($DOMresponse == "your code is correct")
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
elseif($DOMresponse == "your code is incorrect. Go again trough the procedure")
{
$("#container2").fadeOut(400, function(){ $("#container2").html(result); });
$("#container2").fadeIn();
}
// In this second case I could fill the second container id="container2"
});
});
});
ajax.php example:
<?php
if($_POST['request']==1)
{
if($_POST['code']==$user['code'])
{
?><img src="...">
<div>tomatoes</div>
<div>potatoes</div>
<div id="answer">your code is correct</div> <?php
}
else
{
?><img src="...">
<div>apples</div>
<div>oranges</div>
<div>your code is incorrect. Go again trough the procedure</div> <?php
}
}
I would like to know how to get through the DOM of the ajax.php file.
how do I do this? Thanks
Do you need to do this before inserting the result to the page? If so create new element and insert the result to it. For example
var div = document.createElement('div');
var obj = $(div).html(response);
Now you have a standard jQuery object with the dom element.
Responding to the comment:
I am confused. Do you want to validate the code in php or js? It looks like your checking if what is send through post is the same as defined in $user variable. So validating the code is done in php. In that case wouldn't be simpler to use json as a response. In php script create result array with key status set to 1 or 0. In post resposne you can check response.status == 0.
Other wise it look just strange that you make the validation once in php and the twice in js after response. Besides if you set your response to be standard text then you have to create dom element and place the reponse inside to be able to search through it.
I think what you're asking is how do you get the value of $('#code') in the ajax.php file.
Here's what you're doing:
var $code = $('#code'); // jQuery object
$.post('ajax.php', { code: $code });
The problem with this is that you're passing the entire jQuery object to ajax.php. What you probably want to do is pass the value or html of the $('#code') object, like so:
var code = $('#code').html(); // if it's a non-input element
var code = $('#code').val(); // if it's an input
$.post('ajax.php', { code: code });
Then in the ajax.php file, your $_POST['code'] will equal the value of code (e.g. "ABC123"), which you can then use to compare with $user['code'] or whatever you want.
I hope I understand the problem correctly. Good luck.
EDIT: I think I understand what you're getting at now. What you want to do is this:
HTML:
Javascript:
var $option = 'request';
var $code = $('#code').val();
$.post('ajax.php', { option: $option, code: $code }, function(data) {
if (data == 'valid') {
// show valid code result here
} else {
// show invalid code result here
}
});
and ajax.php
<? if ($_POST['option'] == 'request') {
if ($_POST['code'] == '123ABC') {
echo 'valid';
} else {
echo 'invalid';
}
}
?>
Notice that the variable data comes from the function(data) part in the $.post parameter. That data variable contains the response from ajax.php (in my example, it would be 'valid'.)

How can we call Php functions based on the Java script If-else condition?

How can we call Php functions with in the JavaScript If-else condition.
For Example,
if (top == self) {
// not in any kind of frame
} else {
// in a frame
// calling php function
}
</script>
Here, PHP exit() function calling for both if and else conditions. I need to call that function for only in else part.
Please advise me.
Thanks.
Prabhu
Technically not possible. However you can make an AJAX call to a PHP page and get the values returned by it.
PHP (test.php):
<?php
$x = 10;
$y = 20;
$val = $y / $x;
echo $val;
?>
Javascript (jQuery):
$(document).ready(function() {
$.ajax({url: 'test.php',
type: 'POST',
success: function(data){
//takes the value returned by test.php and
//puts it directly into the element with
//id = someElement
$('#someElement').html(data);
}
});
As far as calling exit(); and making the page that holds the JavaScript stop processing, you just can't unless you control the logic on that same page in PHP and call exit(); from there.
Do not try to mix javascript with php.
If you want to stop the page from loading you could also redirect the page to an other (php) page where you simply put exit();
If this javascript is in a function just use : return; or return false;

Categories