How to insert javascript value into the php session variable - php

I want to insert javascript value into the php session variable but inside the javascript function.
Here is what I have tried and it is not working:
function languageChange()
{
var lang = $('#websites1 option:selected').val();
<?php $_SESSION['SESS_LANGUAGE']?> = lang;
alert(<?php echo $_SESSION['SESS_LANGUAGE']?>);
}

You cannot access it directly (the way you are doing). However, it can be done using AJAX.
Here is the perfectly working solution.
Here is the HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label for="websites1">Websites</label>
<select name="websites1" id="websites1">
<option value="Design">Design</option>
<option value="Dev">Dev</option>
<option value="Ecom">Ecom</option>
</select>
</form>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function languageChange()
{
var lang = $('#websites1 option:selected').val();
return lang;
}
$('#websites1').change(function(e) {
var lang = languageChange();
var dataString = 'lang=' + lang;
$.ajax({
type: "POST",
url: "pass_value.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(response) {
alert(response.message);
}
});
return false;
});
});
</script>
</body>
</html>
Here is the AJAX part:
//pass_value.php
<?php session_start();
$_SESSION['SESS_LANGUAGE'] = $_POST['lang'];
$_SESSION['SESS_LANGUAGE'] = 'This is my PHP session var --->'.$_SESSION['SESS_LANGUAGE'];
print json_encode(array('message' => $_SESSION['SESS_LANGUAGE']));
die();
?>
EDIT 1:
Once you run the code, simply select any of the other options from the dropdown menu and you will receive an alert that gives you the value of the php session variable along with the custom text that I added to it.
EDIT 2:
If you want to run my solution on your end, make sure you point to core jQuery js file correctly. My jquery code points to src="js/jquery_1.7.1_min.js". Make sure you update this.

Javascript does not have access to PHP-variables. The client (web browser/javascript) only has access to the Cookie or Cookieless ID (Querystring) associated with the session.
Sessions are used this way for the purpose of not letting the client modify settings associated with the session without going through the server. The less "secure" way is to use cookies for all settings. Something like language-setting might be a good idea to store in a cookie rather than the session.
In order to solve this, you could make a page which takes a session property name (like your "SESS_LANGUAGE") and a value which puts it in the session using php. I strongly advise against this because any user could then set any session variable.
The best way I can imagine is that you send an AJAX-call to a page saying that you want to change the language.
The called URL would be something like this:
changelanguage.php?lang=en_US
And the php-code for changelaguange.php:
$_SESSION['SESS_LANGUAGE'] = $_GET['lang'];

Related

Resetting a PHP $_SESSION array with jquery function

I am trying to reset a session array in php with a function in jquery using a button. I would use a submit but I don't want the page to refresh. I tried to send a $.post request leaving the variables and return blank, and then sending a variable so I could use $_session[''] = array() but none of it worked. I have searched and can't find much about it just a lot on sending strings.
OK this is very simple to stop the page from refreshing you need to tell js to disable the default event i use jquery for this here is my code
Html & js
<html>
<head>
<title>Reseting a PHP $_SESSIO array with jquery function</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function sessRest(){
$.post("rest.php", {x: "9845621"}).done(function(data){
alert("States: " + data);
});
}
$(document).ready(function(){
$("#target").click(function(event){
event.preventDefault();
sessRest();
});
});
</script>
</head>
<body>
<div id="main">
Click to rest me
</div>
</body>
</html>
php code rest.php
<?php
session_start();
(string)$data = $_POST['x'];
if($data == "9845621"){
$_SESSION['gx'] = array();
return $_SESSION['gx']; //return the empty array to js
}else(
return "error";
)
?>
I hope this helps .
User below jquery to submit to php code
var requestData = { param: "value"};
$.ajax({
url: your_url/session_change.php,
type: "post",
dataType: "json" or what ever,
data: your_data,
success: function (data) {
}
});
You can end the session successfully on server side with an ajax call, but apart from reloading the page, you're not going to clear what information was loaded already on client side. The session information wont be there once you do reload, but there is no way around that.
You can, however, emulate what you want to do with javascript.
When you load your session information, echo it to the page as javascript variables, then you have full control on client side. Just beware of echoing sensitive information like passwords, obviously.
try this:
your html file should contain this jQuery file:
$('#button').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'http://yourwebsite.com/session.php'
}).done(function(data){
if(data=='reseted'){
//do anything...
}
else {
//do anything...
}
})
});
and in your session.php file:
<?php
session_start();
session_unset();
if($_SESSION == FALSE){
echo 'reseted';
}
else echo 'no';
?>
the answer was
jquery $.post('reset.php');
in reset.php
$_SESSION['products'] = array();
?>
this reset my session array when the reset button was clicked with no page refresh...
I had done this originally and forgot to include my core.php in the reset.php which contained my start session()..
Thank you all for the help though.... great suggestions

pass query string variables without refresh page

My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.

Ajax call to a PHP page always returns nothing even though the PHP page echoes something

I am calling a very simple PHP page with some equally simple AJAX, but the call always returns nothing, even though the PHP is fine. That is, you can go to the URL of the PHP page and see that it echoes "Hello World" but when it is called with JS, it returns nothing.
Below is the HTML Page with the Javascript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......<br />
Enter your email: <input id="email" type="text" />
<input type="button" onclick="setXMLHttpRequest()" value="Go!" />
<script type='text/javascript'/>
var http;
function setXMLHttpRequest()
{
if(window.XMLHttpRequest)
http = new XMLHttpRequest();
else if(window.ActiveXObject)
http = new ActiveXObject("Microsoft.XMLHTTP");
url = "http://www.convolutedconstruct.com /Ajax/checkemail.php?email=" +
document.getElementById('email').value;
http.onreadystatechange = display;
http.open("GET", url, true);
http.send(null);
}
function display()
{
if (http.readyState == 4)
{
infostr = http.responseText;
alert("From the PHP: " + infostr);
}
}
</script></body></html>
Here is the content of the PHP page
Click here for the live PHP page
<?php
$email = $_GET['email'];
echo "Hello World!";
?>
Why does this return nothing to the JS, even though the PHP page echoes the text correctly?
As has been suggested above, AJAX request will only work usually when both the caller and called are on same domain, You have to ensure that your html code, which contains the javascript, resides on same domain http://www.convolutedconstruct.com.
If that is not the case you can use CORS to allow your ajax to receive input from your php page by sending this header in your php output
<?php
header("Access-Control-Allow-Origin: *");
//rest of your code
?>
See: http://enable-cors.org/
i dont like using the XMLHTTP request. instead i use jQuery's method $.ajax({}); method. it always works for me!
$.ajax({
type: "POST", // or 'GET'
url: "your-url.php", // url that you are passing the data to
data: {
dataName: 'data to pass' // string, variable, object, array, etc
},
success: function(output) { // output is what the url is 'echoing' back to the jQuery
// do something when the ajax method is complete.
}
});
dont forget to import the jQuery source code - http://code.jquery.com/jquery-1.7.2.min.js
these are the most common of the components that are used in ajax.
I'll be glad to help you out some more if you would like it.
If you want to know more just check the documentation on it: http://api.jquery.com/jQuery.ajax/

Passing js variable into php string

I need a little bit of help im trying to page a js variable into a url thats being parsed in php using file_get_contents. Im not sure where to start to do that.
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
</script>
<?php
$ticker = js_varable_here;
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re');
?>
any advice is appreciated, like i said im in the dark on this one.
Here's an example using jquery.
Javascript:
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
$.post("/somephp.php", {ticker: js_variable}, function(data) {
// returned from php
});
</script>
PHP:
<?php
$ticker = $_POST['ticker'];
$file = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re");
?>
Expanding on what Jashwant says...
PHP is a server-sided language, which does work behind the scenes. Javascript is client-side, which runs and executes code on the local client's machine (ie through the browser).
You can however use AJAX (Asynchronous JavaScript and XML) so the local client sends HTTP requests to the server without reloading the current page. For instance, you can use AJAX to send the contents of the variable to the server.
For easier usage, you should check out jQuery's methods regarding ajax calls. See: http://api.jquery.com/jQuery.ajax/
Hope it works well.
Heres how you can do it with jquerys post() and then return json, you could build the result as you expect to output within the php part or you could use jquery to loop with each() through the result.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'
&& isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
if(!empty($_POST['s'])){
$ticker = $_POST['s'];
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s='.$ticker.'&f=soac1p2ghjkj1re');
header('Content-Type: application/json');
echo json_encode(array('result'=>$file));
}else{
echo 'Request not allowed!';
}
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
<script>
var js_variable = "appl+goog+fb+mfst+nflx";
$.post('this_script.php',{s: js_variable}, function(data) {
$('#divResult').replaceWith('<div id="divResult">'+ data.result +'<div>');
});
</script>
</head>
<body>
<div id="divResult"><div>
</body>
</html>

Basic ajax logic

Upon suggestion of using Ajax for an html page, I decided to attempt to learn how it works. In my example, I'm just trying to get the response from a php file (which just echoes a simple string as a test) but it doesn't work, in that nothing actually happens.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> Incident Center </title>
<!--<link rel="stylesheet" href="http://web.njit.edu/~swp5/assignment/style/style.css">-->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function onsubmit()
{
var sender;
if (window.XMLHttpRequest)
{
sender=new XMLHttpRequest();
}
else
{
sender=new ActiveXObject("Microsoft.XMLHTTP");
}
sender.onreadystatechange=function()
{
if (sender.readyState==4 && sender.status==200)
{
document.getElementById("myDiv").innerHTML=sender.responseText;
}
}
sender.open("GET","proz.php",true);
sender.send();
}
</script>
</head>
<body>
<div class="header">
Incident Center
</div>
<p>
<button onclick="onsubmit()">Test</button>
</p>
<div id="myDiv"></div>
</body>
</html>
As I already mentioned in my comment, you should check the response code of your request to see if something went wrong. Add the following line to the start of your onreadystatechanged function:
alert(sender.readyState + ', ' + sender.status + ', ' + sender.responseText);
Based on this output you can probably determine your error.
Using Opera 11.51 here, it doesn't actually like the fact that you use onsubmit() as a function name. Presumably because onsubmit() is actually already an eventhandler hook of a <button> element itself. I presume other browsers won't like this function name either.
So, first off, rename the function. Let's assume dosubmit() here.
Furthermore, you should wrap a button in a <form> element. And because a default button, acts as a submit button, the form is being submitted, causing the page to reload.
To prevent this, you should let the function return false; and call the function like so onclick="return dosubmit()", if you are going to call it inline like this, or make the button a button of type button, like so: <button type="button" onclick="dosubmit()">
Why don't you use jQuery ? http://www.jquery.com/
Send doesn't actually display anything. Send calls the page and populates two different variables. What send does is populates the "responseXML" and "responseText" properties of the sender. Try after your send:
alert(sender.responseText);
See http://en.wikipedia.org/wiki/XMLHttpRequest
It's much easier to use jQuery to do this as it has a built in AJAX function. Your code would look like this:
jQuery.ajax({
type: 'get',
url: 'proz.php',
error: function(r) {
alert("Something went wrong - "+r);
}
success: function(response) {
alert(response);
}
});
Hope that helps

Categories