jquery.post doesn't create a session - php

I hava a strange problem. I'm using jquery $.post() to send/recieve vars from a PHP script.
JavaScript:
$("#r_submit").click(function()
{
$.post("http://" + server + "/msws/",
{
action: "register",
sub_action: "register_validate"
},
function(json)
{
json = $.parseJSON(json);
alert(json.cell_is_good);
});
});
PHP:
http://textuploader.com/?p=6&id=S7zDD
Problem:
If I run the code on my pc (WAMP) it works fine,
but if I upload it to my server (justhost) then it dosn't keep the session
if I alert the session when I create it, it is there, but when I try to get the session
later, it's gone,
I think it has to do with the fact that the server thinks that the browser was closed, so it destroys the session?
Thank you :)

You are starting your session without a session id. For this to work your PHP has to be configured to use transparent session id, which is deactivated by default. So you will have to start the session in the script that has the AJAX-call, and submit the session_id() in the POST request, and start the session in your PHP something like this:
if (!isset($_POST['SID'])) {
die('{}');
}
session_start($_POST['SID']);
Also I would leave out the host-part of the url you are calling in your $.post to avoid cross-domain ajax call problems (also this most likely will not fix your problem). It will work only on the same server, so you can write the ajax call like this:
$.post("/msws/", //...

check if you have multiple session cookies.
i've the same situation with codeigniter and i found that every new page creates its own session

Related

Jquery ajax set some session variables then trigger click

I have a page that has tabs on it. each of the tabs have a few forms on it. On the form, a user can set a filter. for example "Show me (10,25,100) result"
The when user enters a value, i fire off an ajax call to a php script that sets session variables
$_SESSION['filter'] = $_POST['filter'];
The success of the ajax call triggers the tab click to get to the form the user is on:
$.ajax({
type:"POST",
data:"filter="+filter,
url:"actions/Tickets/filters.php",
success:function(result){
$('#someTab').trigger('click');
}
});
The problem I am running into is if I
print_r($_SESSION);
on the page that the form is on, i do not see any changes to the $_SESSION['filter'] value.
What i think is happening is the ajax isnt waiting for the script to finish, so the SESSION var never gets set. asynch isnt an option. how can i acheive this?
How can i use an ajax script to call a php file to set SESSION variables then trigger a click event on nav tabs.
As you have stated in the comment that you set the session using:
$_SESSION['filter'] = $_POST['filter'];
Than, I think the issue is, when you set the session in php uisng an ajax call, than you can only get the updated session by using an another ajax call or after page refresh. So make an another ajax call and see what happens.
You cann't assign session in javascript because javascript occurs on client side and session stored at server side.
So , It's not possible you can use php variables in js like.
<?php
$_SESSION['filter'] = "foo";
?>
Then you can use this session variable in js. But you can't do vice versa. You can't assign session from js to php.
You can set value from js to html using jquery but this scenario isn't possible.
Edit :-
So, set session variable in filter.php.
$_SESSION['filter'] = "foo";
After then when result is retured reload the page. Because Page must be reload for session set. I'm not sure for it but may be it works.
$.ajax({
type:"POST",
data:"filter="+filter,
url:"actions/Tickets/filters.php",
success:function(result){
$('#someTab').trigger('click');
location.reload(); // reload the page
}
});
Ofcourse you cant assign like that because js is client side script & php is server side, you can assign php variable to js variable but not vice versa
You need to use this:
$_SESSION['filter'] = $_POST["filter"];
This post may help you:
Set php session via ajax

Getting difficulty to write php code in jquery

My code,
Using below code ineed to store catlog_id in a session but it is not working
$(document).ready(function() {
$("#catlog").click(function(event) {
var catlog ="<?php $this->session->set_userdata('catlog_id',"+$('.catlog_id').val()+")?>";
});
});
Your JavaScript is executed on the client machine and there is no PHP interpreter there. Any code that you create on the fly through JS must be HTML, CSS, JS. Setting cookies can be done through JS, look for a cookie plugins for jQuery.
A good way to access client data is to use cookies.
You can store with javascript/jquery data in a cookie and then you can it later access with php $_COOKIE
You can use the firefox plugin firebug to track the cookie changes.

PHP sessions and AJAX request (from injected JS code)

I think I forgetting something in my code but can't find what.
On my server I have simple logging.php file.
If I pass user/password parameters then a new session is created.
If I pass loggout the session is destroyed.
If I pass report the list of current session variables are reported on screen.
If I test the code writing urls in my browser all works fine. First invoke .../logging.php?user=xxx&password=xxx. The session is started and the session variables are reported to me. And finally I destroy the session passing the logout parameter.
If user request a report or a logout and no session exists a HTTP-401 error code is returned to client.
On the other hand I have a piece of JavaScript code that I can inject on web page using a bookmarklet. Once code is injected I show a toolbar where user can write user/password and send to server.
The logging actions seems to works fine, and server returns me a 200 status code, but later if I make a request to logout the server returns me a 401 error, which mean no session exists.
I was using chrome and looking at HTTP request and responses can see that when I logging the server returns in the response different values for PHPSESSIONID.
That means two different AJAX request are considered different sessions. The server seems to not recognize the second request from AJAX as if it was started by the same client.
Repeat, the PHP code works fine if I execute using browser directly but not with AJAX request, so I think I forgetting something in AJAX.
Any ideas?
Thanks in advance.
Update
To be more concise, my problem is calling php from JavaScript. It seems there are no sessions started.
Imagine a very simple PHP code:
logging.php: given a user/password starts a new session and also stores 'user' names as a session variable.
request.php: which returns the user name stored as session variable.
logout.php: which destroys the session.
My first AJAX request start a PHP session. That seems fine because a PHPSESSIONID cookie is returned from server. Also I store the user name as session variable.
The second AJAX request tries to get the user name (stored in the session) but it gets nothing and in addition a new PHPSESSIONID cookie is returned from server.
I know it seems impossible and more when I'm testing using browser url request and works fine, but it's the truth.
I'm forgetting something on AJAX, expiration times or something similar?
Update again
I made some tests and I found the problem but not the solution.
My JS code is injected through a bookmarklet.
When I inject the code in a HTML page from my server, the AJAX requests works fine. The first (logging) request gets a PHPSESSID which is passed in subsequent request to the server.
On the other hand If I load google.com and inject the code, the first (logging) request gets the PHPSESSID too but later it is not sent with next requests.
Anyone has experienced the same issue? which is the problem?
Thanks in advance.
Update again, again
Ok finally I found my problem. Because my JS is injected from a different domain (current page is from domainA and my JS code comes from domainB) cookies are not cross domain, so PHPSESSID can be shared.
A possible soulution is when I logging I will return the PHP session ID in pice of JSON data and use it for subsequent calls.
If I'm correct, you're trying to log in a user by making an AJAX request to a URL, with the username and password provided in the URL? That's not really a safe construction, the password is very vulnerable this way?!
I would advice you to implement jQuery, and transer the login details using the $.POST command:
http://api.jquery.com/jQuery.post/
Make sure all your files (also those requested by AJAX) contain session_start(); on top of the file.
When every file contains session_start(); and you're using the same $_SESSION variables to check if a user is loggedin, it should work!
Are both of your AJAX requests coming from the same page? The requests are Asynchronous, so it may be that the "logged in?" request is returning its result before the "log in" request goes through.
From what you have asked, I hope your code is (at its beginning more or less) something like:
A file logging.php like this:
<?php # file : loggging.php
if(!ini_set('session.auto_start'))
// more stuff
if(!empty($_REQUEST['user']) && !empty($_REQUEST['passwd'])) {
session_regenerate_sid(); // This is important (1)
$_SESSION['user'] = $_REQUEST['user'];
// Whatever
}
A file request.php like this..
<?php # file : request.php
if(!ini_set('session.auto_start'))
// Whatever stuff to process data
var_dump($_SESSION);
// Or a nice foreach($v as $i => $x) {
// echo("[$i] => $x\n<br />");
// } instead :)
And your logout.php should read something like..
<?php # file : logout.php
if(!ini_set('session.auto_start')) session_start();
session_destroy();
You are probably not calling either session_start() or you are calling it twice.
To check this out try this: change all your session_start() lines for:
session_name('MYCoolNewName');
session_start();
Now your session should not read PHPSESSID, instead it should be MYCoolNewName.
If it is not, then your problem is the aforementioned.
(1) I put as important session_regenerate_sid() because opened authenticated sessions are a threat out there. I'll demonstrate it with an example.
Alice visits coolwebsite.com/login.php, which gives her a SID which I'll call AliceSID.
Alice tells Bob to visit coolwebsite.com/login.php?PHPSESSID=AliceSID, and when Bob does Alice could log in his account unless Bob's session was regenerated.

Setcookie won't work?

I set the cookies regularly in a callback page in my Twitter application. Everything works fine.
Now, using jQuery, I submit a form, and the callback function activates a PHP script. That script only needs to set one cookie to the serialized values of $_POST; and the values run fine (both serialized and normal, I echoed them out to debug). The expiration time is set to 1 year ahead. But for some reason, the cookie just won't appear anywhere. Here's the code:
// js/main.js
$('#settings-form').live('submit', function() {
$.post('controllers/settings.php', $(this).serialize(), function(data) { // Everything here works.
if (data == 'OK') // no errors spits out "OK". this works
changeView({'msg': 'Your settings were saved successfully.'}); // This just resets the view and adds a message div at the top. This works
else
changeView({'msg': data}); // This echoes the error if any exists. Doesn't happen, no errors arise
});
return false; // Cancels redirecting after submitting form
});
// controllers/settings.php
setcookie('user_settings', serialize($_POST), strtotime('+1 year'));
I checked all the variables and I even tried setting dummy ones for test (like "boo" instead of serialize($_POST). for some reason that doesn't work.
Any ideas why this is happening? I tried doing a chdir('..'); to make the cookie dir go to the right place, but that doesn't seem to be the problem, checking the cookies inside my browser doesn't seem to work at all, for any path. It just doesn't work at all. I also just tried manually changing the domain and path, but those don't work either.
Firstly, the chdir() thing is a red-herring -- Cookies are domain-specific; the directory path doesn't have any bearing on them.
Cookies can work a bit strangely when you're making ajax type calls, and I think this is what you're seeing -- The server is probably setting the cookie, but the browser may not be setting it in the cookies data it as it's not a page load.
I would suggest you'd be better off using PHP's session handling rather than cookies; it's better for security, less bandwidth (because the whole of the cookie data is transmitted in both directions with every http single request), and more likely to work.
If you really want to use cookies, it may work better if you use Javascript to do it. You can set cookies in your javascript code by accessing document.cookie. (you need to get the syntax right for the cookie string, but JQuery probably has its own functions that makes them easier to work with)

access post vars JS or PHP?

I am using jquery to post vars to a php script.
Is it possible to access these vars once the script has posted? If I post the data to the php script, is the only way to access it in the html/js that i posted it from, to send it back from the php script as json?
I cant seem to do it in JS, but even php will not work?, Sorry correction i can access the post vars in the php page, but not in the html/js page i posted from
Any ideas how to access posted vars from the page thats doing the posting?
update: yep to be a bit clearer, i am using a html page with javascript to post to a php page, i would like to access the posted vars in the html javascript page. I tried outputting $.post and $.ajax and these just show a long function.
Cheers
Ke
How are you submitting your elements to php page? If you are doing everything fine and using ajax (see jquery post method) for example, you can access the php variables normally with $_POST['var_name'].
Make sure that:
Your form method type is set to POST
Your ajax request goes successful
You have specified the correct path to your server side script
In PHP, the data should be accessible through the $_POST array, just like if you posted to the script using a form (whether you make an AJAX request or a normal request through your browser, the server behaves the same). If they're not there, perhaps you actually sent your data by GET instead (you could check $_REQUEST, but it's better, and more secure, to know what method your data will be coming in), or else your AJAX request failed.
I don't recommend using $_REQUEST to post something back to your site. If someone changes their $_REQUEST vars on you, then you have an opening for cross site scripting.
Push all your vars to $_SESSION and post them as you see fit but only after they have been purified. That way even if you make some modifications to them after the fact you can rely on the source, which is in the $_SESSION. However if you are trying to perform actions after a page has executed you are straying outside the boundaries of PHP's limitations. People do it all the time with things like Jquery but it doesn't make it right.
Warning: if you allow accessing and process of vars after PHP has finished printing the page, then you run the risk of enabling attacks on your code.
I assume that you are using $.ajax or $.post to do this.
Just keep your data in local variables. There i sno reason why you should lose the posted data, or your php not being able to access it.
If you post code, maybe someone can help better.
In your php function, you can use this:
function foo() {
//do something
echo json_encode($var);
}
I use .ajax, use dataType: "json". The success attribute would be:
$.ajax(
{
url: 'ajaxfile.php',
type: "POST",
data: ($("#myForm").serialize()),
dataType: "json",
success: function(data)
{
//Insert your logic to handle the vars from php
}
});

Categories