Accessing php session while using Angular Routing - php

I am using Angular routing and want to access a php session variable in the view.
<?php
session_start();
//print_r($_SESSION['query']); the variable is available and will print here
?>
<script>
var x = <?$_SESSION['query']?>
console.log("x: " , x) //this returns undefined
</script>
I'm trying to pass the session variable as a parameter in
function, but it is not available here either.
ng-init="mc.makeQuery(<?($_SESSION['query'])?>)"

You can start session on your page like and create hidden field for session like this
<input type="hidden" name="mysession" id="mysession">
and write javascript function some thing like this
function Result(){
var marks = 55;
document.getElementById("mysession").innerHTML= <?php echo session_id();?>;
document.getElementById("hdnmarks").innerHTML= marks;
document.getElementById('Form').submit();
}
change the Form name with your form name.

Related

How to reach php $_SESSION array in javascript?

I am trying to build some javascript function and I need to check if the users are logged in or not. When a user log in to my site I set a variable in session array named is_logged. I want to reach that variable in javascript is it possible???
I tried some ways but did not work like following:
var session = "<?php print_r $_SESSION['is_logged']; ?>";
alert(session);
and:
var session = '<?php echo json_encode($_SESSION['is_logged']) ?>';
alert(session);
It is either show a text or never alert at all
Just echo it:
var session = <?php echo $_SESSION['is_logged']?'true':'false'; ?>;
alert(session);
You need tertiary operator, as false is echoed as empty string so it would lead to var session = ; which is a JS syntax error.
If you want to reach all elements of $_SESSION in JavaScript you may use json_encode,
<?php
session_start();
$_SESSION["x"]="y";
?>
<script>
var session = eval('(<?php echo json_encode($_SESSION)?>)');
console.log(session);
//you may access session variable "x" as follows
alert(session.x);
</script>
But note that, exporting all $_SESSION variable to client is not safe at all.
Try the following code:
var session = "<?php echo $_SESSION['is_logged'] ?>";
In a js file you cant get the value of a php variable or php code doesnt works on a js file because php code will works in a .php extension file.
So one method is to set the session value as a hidden element value and in your js file get the value of the hidden element.
In the html:
<input type="hidden" id="sess_var" value="<?php echo $_SESSION['is_logged']; ?>"/>
In your js:
var session = document.getElementById('sess_var').value;
alert(session);
You can do things like this
Just insert the $_SESSION['is_logged'] in a hidden field like
<input type = "hidden" value = "<?php echo $_SESSION['is_logged']; ?>" id = "is_logged" />
Then you can access that in your jquery like this
var is_logged = jQuery.trim($('#is_logged').val());
//then do validation here
var get_session=<?php echo $_SESSION['is_login']
alert(get_session);
?>
## *Just try this * ##

my "post" form doesn't post

I have a a problem when trying to send data from one page to another via using SESSION.
In page 1 I have a form like:
<form id="myForm" name="myForm" action="" method="post">
<input name="item_1">......</input> // an input for a number
<input name="comment1">......</input> // an input for text
</form>
to avoid refreshing, I use
function submitOnclick()
{
$.post("thisPage.php", $("#myForm").serialize());
redirectToAnotherPage();
}
then I tried to store data via using SESSION
function redirectToAnotherPage(){
<?php $_SESSION['item_1']=$_POST['item_1'] ?>;
<?php $_SESSION['comment1']=$_POST['comment1'] ?>;
location.href='anotherPage.php';
}
but the $POST result is empty, I tried to replace $_POST['item_1'] with a number 1 and it did store the number to item_1, so I assume it is because $_POST['item_1'] has some problems, I don't know why I can't get the form data in one page without submitting / refreshing,
Any help will be appreciated, thanks!
I don't think you can set a PHP session variable like that inside your javascript function. PHP is separate to javascript since PHP is serverside, those values will be read and assigned when the page first pre-processes.
There will be no change, whether the javascript function gets called or not.
Even without AJAX< just a simple PHP form will do. Please see below:
<form id="myForm" name="myForm" action="anotherPage.php" method="post">
<input name="item1">......</input>
<input name="comment1">......</input>
</form>
To submit using javascript, just use something like this on your function:
function submitForm() {
document.myform.submit();
}
the problem is name of your input is not same with your $_POST index
your input: <input name="item1">
your post index: $_POST['item_1']
and also its not right way to use PHP function inside Js, this:
function redirectToAnotherPage(){
<?php $_SESSION['item_1']=$_POST['item_1'] ?>;
<?php $_SESSION['comment1']=$_POST['comment1'] ?>;
location.href='anotherPage.php';
}
you need to set $_SESSION directly in thisPage.php(ajax post url)
EDIT :
dont use serialize(), this way instead:
function submitOnclick()
{
$.post(
"thisPage.php",
{item_1 : $('input[name="item_1"]').val(),
comment1 : $('input[name="comment1"]').val()
}
);
redirectToAnotherPage();
}
good Luck !!!

Separate Javascript file from View

I am using Codeigniter and want to separate the JavaScript from the view files, but many of the JavaScript functions need data from controller (it depended on values from controllers)
ex:
controller :
function show_post() {
$data['data'] = $this -> get_data(); //some data
$data['random_key'] = $this -> generate_random(); //returns a random value
$this -> load -> view('posts', $data);
}
and in view I have a js function:
<script>
function get_random() {
return "<?= $random_key; ?>";
}
</script>
How can I save this javascript snippets to some other file say posts.js? If I did something like this then I cannot use php variables inside the script.
What is the best way to achieve this in terms of Performance and Maintenance?
Some other ways I do not want to follow :
Save the JS file as a PHP file and then pass the values to that file
Declare all those variable in the view file globally
you could pass the value as parameter to your js function, like
post.js
function get_random( param ) {
//use param here
}
//OR
function get_random( ) {
//get arguments like
var firstArg = arguments[0];
}
view.php
//include post.js file
//call the js function passing php variable as parameter, like
get_random("<?php echo $random_key; ?>");
did you mean something like this
One way to do it by using hidden fields, in your case store them in hidden field like:
<input type="hidden" value="<?php echo $random_key;?>" id="randomkey">
and access them in js by using ID like:
$("#randomkey").val();
In this way you can use controller paramter in your js.
Help it will help you!
the simplest method is that , define php variables as js variable in your view file
<script type="text/javascript">
var random_key = <?= $random_key; ?>;
</script>
then you can use that variable in your example.js file

how to set the php variable with javascript value and use that php variable in external php file

design.php file:
<script>
$(".colr_sldr li img").click(function(){
var src = $(this).attr('src');
var value=src.substring(src.lastIndexOf('/')+1);
<?php $var = "<script>document.write('" + value + "')</script>";?>
});
</script>
and use this variable in index.php file:
<?php
include('design.php');
echo $var;
?>
here while i am printing this variable it is getting zero can any one help
you can't take var like this in php..
$var = "<script>document.write('" + value + "')</script>";?>
because php is server side language ..
and javascript is client side.
For this you have to use ajax ,get and post methods
the only solution I may know is using jquery on client side an sending your variable via ajax :
script.js
$('document).ready(function(){
var myVar="Hello";
$.post('design.php',myVar);
});
and in design.php you have acces to your variable with $_POST
design.php
<?php
$myVar = $_POST['myVar'];
echo $myVar;?>
please check http://api.jquery.com/jQuery.ajax/ for more details
or http://api.jquery.com/jQuery.post/

How to pass data from input form to js on another page

I have a page where a user enters an address and clicks search. The user should be taken to the next page which should contain a google map with the address the user specified. How should I pass the address from the form on page 1, to js on page 2 where I can manipulate it with the google maps api? I'm using codeigniter btw.
EDIT:
My ideal solution would be to use flash data or pass the address in the url the codeigniter way. My problem is i'm not sure how I would retrieve the data if I used either of these methods.
In the CodeIgniter view for page 1:
<form method="POST" action="getMap">
<input type="text" name="address" value="" />
<input type="submit" value="Map It!" />
</form>
In the CodeIgniter view loaded by getMap() method of the controller (in other words, in page 2):
<script>
address = "<?php echo htmlspecialchars($this->input->post['address']); ?>";
// create the map with the address here
</script>
You'll want to take care to do some validation on the user input.
Use url variables to accomplish this. An example might look like this:
http://www.testurl.com/mappage.html?address=someaddress&city=somecity&state=ca&zip=12345
You can pick up the values of these url variables in javascript and pass it to the google map.
Do you want the user to be able to save the url?
If you don't, just use POST in the input field and retrieve the data in the second page this way (inside the javascript):
var address = '<?=$this->input->post('address')?>'
Otherwise:
In javascript, in the first page, prevent the default action on form submit and instead redirect the user to [url of the second page]/[stuff written in the form] (I can give you a jquery example if you want);
In the second page controller (let's pretend the function is called get_map and it is in the maps controller you get the data in this way
function get_map($address = null)
Now you have the input address. Pass it to the view that should contain the map.
Why don't you simply print the POSTed information via PHP on the destination page using Javascript literals syntax?
As an example, if your form POSTs the following (both GET or POST query):
firstname=aaron&lastname=pink
you can print in a destination PHP page:
<html>
<head>
<script type="text/javascript">
var fname = "<?php echo addslashes($_POST['firstname']); ?>";
var lname = "<?php echo addslashes($_POST['lastname']); ?>";
</script>
</head>
<body>
...
<button onclick="alert(fname);">Say First Name!</button>
</body>
</html>
Then, you can simply use fname and lname Javascript vars as you wish, just as my sample button does on click!
I hope it was helpful, even if very simple :)
If you are using jquery, you can use the $.cookie plugin to transfer informations between PHP and Javascript.
or 2. Send data from 1. page per $_GET or $_POST and catch the data in 2. page
<script>
var myData = '<?php=htmlspecialchars($_POST['data_from_page1']);?>';
</script>
#Catfish you're getting all confused. The objective of making your urls "pretty" and having them resemble paths / files rather than query strings is for SEO & user friendliness. You shouldn't really be including any form input in as a "pretty" url. Either send your address data via the $_POSTS global or send it as a query string. CI uses the [QSA] flag in its mod_rewrite definitions in the htaccess file so you're totally fine to stick on a (IMO) semantically correct query string on the end.
Anyway, to the code.
On form.php:
<form action="map.php" method="get">
<input type="text" name="addr" />
</form>
On map.php:
<?php
$addr = $this->input->get('addr');
// or $addr = $_GET['addr'];
echo $addr;
?>
You can use sessionStorage on modern browsers to stock your datas between pages inside the same browsing session.
For older browser you can use an hacky solution that allow you to stock datas inside the window.name
if( typeof sessionStorage !== 'undefined' ){
myStorage = sessionStorage;
}else{
myStorage = {
setItem:function(key,val){
this.removeItem(key);
window.top.name+=(window.top.name.length?'&':'')+escape(key)+'='+escape(val);
}
,getItem:function(key){
var r = window.top.name.match(new RegExp('(^|&)'+escape(key)+'=([^&=]*)($|&)'));
return r?unescape(r[2]):null;
}
,removeItem:function(key){
window.top.name = window.top.name.replace(new RegExp('(^|&)'+escape(key)+'=([^=&]*)(?=$|&)'),'');
}
};
}
Now you can use myStorage.setItem('key',value) with each of the form fields you want to keep and retrieve them on the next page with myStorage.getItem('key')
It's not more complicated than using cookies, and have the benefits to not transfer the cookie datas in each request header.
Hope this help..
Why not do it entirely in JavaScript, using the Google Maps API ?
Let's say that your Map is initialized with the variable var Map and the Geocoder in the var Geocoder and that you have an <form id="searchForm">Address:<input /> <br /> <input type="submit" /></form>.
I'm also assuming you have jQuery loaded, so:
<script type="text/javascript">
$('#searchForm').submit( function(e) {
e.preventDefault();
var searchString = $(this).find('input:first').val(); // get the address
Geocoder.geocode( { 'address': searchString}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Map.setCenter(results[0].geometry.location);
} else {
alert("Geocode error: " + status + "\n" + "Try another address");
}
});
});
</script>
Demo here: http://jsfiddle.net/toxik/Xjy3S/embedded/result/
Codeigniter sessions would be the easiest to work with.
Once you get the address submitted, set some userdata like so.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mycontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//do something from post
$this->session->set_userdata('street', $this->input->post('street'));
$this->session->set_userdata('city', $this->input->post('city'));
$this->session->set_userdata('state', $this->input->post('state'));
$this->session->set_userdata('zip', $this->input->post('zip'));
//then redirect to the next page
redirect('mycontroller/map');
}
else
{
//load the form
$this->load->view('address_form');
}
}
function map()
{
$data = array(
"street" => $this->session->userdata('street'),
"city" => $this->session->userdata('city'),
"state" => $this->session->userdata('state'),
"zip" => $this->session->userdata('zip')
);
$this->load->view('map' $data);
}
}
Set the values in a hidden input. Just have javascript grab the value of that inputs ID...
check this
// JavaScript function function abc(pram1, pram2) { alert(pram1 + pram2); } // end of JS function
now call this function on your search form. pass all parameters you want to move other page
like
<a name="search" href="javascript:void(0)" onclick="abc('param1','param2')> search </a>

Categories