Mobile browsers doesn't support session variables? - php

I have a browser version of my web app and I have some values stored in cookies. Now I am making a mobile version and it seems that my cookies are not working.
Is it possible to use cookies on mobile devices?
I am trying to perform this code and my php is giving me an empty value:
$(document).ready(function() {
var session_lang= '<?php if(isset($_SESSION['SESS_LANGUAGE']))
echo $_SESSION['SESS_LANGUAGE'];?>';
if (session_lang!='')
{
check_and_change(session_lang);
}
});
Is there any other way to store data in internal memory so it can work as cookie?
Does mobile devices support session variables? I am looking on the firebug and I can see that I can create session variable but when I want to read it it is null.
What could be a problem and how to solve this?
EDIT:
I will put you almost entire code so you can see what am I doing...btw. this code is working normally on PC browser.
Javascript file:
$(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) {
check_and_change(response.message);
}
});
return false;
});
} );
function check_and_change(lang)
{
switch (lang)
{ //do something
}
}
Then this first part that I have put above is on the actual php site that I am looking and which is opening:
And the last thing is pass_value.php:
<?php
session_start();
$_SESSION['SESS_LANGUAGE'] = $_POST['lang'];
print json_encode(array('message' => $_SESSION['SESS_LANGUAGE']));
die();
?>
I really don't know why this code doesn't work on the mobile phones.

Cookies definitely work on mobile browsers. You say "I am looking on the firebug" which makes me think you aren't really looking at it on a phone.
Have you started the session, and turned on error reporting?

I had a similar situation and discovered that, before my tablet called the script I specified in the URL parameter of the .ajax( ) call, it was actually calling the index.php script again.
Same with my phone. Since I had initialized my session variables in index.php, they kept getting re-set to their initial values (making it look like they were not being correctly stored between pages).
I never figured out why index.php was getting re-called, but I added if !isset( ) checks around the initialization statements and that cleared it up.

On Android, turning on "Data Saver" effectively destroyed my session. I have a login script which will redirect to the previous page when login succeeds. Worked until I turned on Data Saver. Turning it off made it work again. Google does state that Data Saver may affect secure pages which I guess includes my script, which is not on a HTTPS website.

Related

Why my AJAX function blocks the header of PHP that I have on my page?

I am doing a program in PHP (MVC) in which I need to delete a row from the database when I click on a link on the View side. So, when I click on the link, the following ajax function it is called.
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
}
});
}
but I do not want to send any data so it is the reason why I put it as above.
Then, in the Controller side I have the following method:
public function deleteCar($id)
{
//Here I call the function to delete the Car that I send by id. It works fine.
header('Location: http://localhost/project/car');
}
If I call directly the method deleteCar on the link without Ajax the header works properly but in the same moment I use Ajax to call it, I have to refresh the page to see the content that I have modified, I mean, that the Car have been deleted.
The code works fine, just I do not want to refresh the page after AJAX function had finished.
Thanks in advance!
I am guessing the use case is to allow the app to work when the user does not have JS enabled - so they just click the links and get a non-AJAX experience. In this case you probably want to redirect ONLY if the page was requested via GET, not POST. something like
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
header('Location: http://localhost/project/car');
}
is likely what you are looking for.
You will then have to actually remove the element representing the car from the DOM in your success handler, with something like:
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
$('#car-row-' + id).remove();
}
});
}
(that won't be it exactly, it depends how the HTML of your page is setup how exactly you will do this).
I believe the key thing to understand here is - when your PHP function has completed it has removed the car from the database, but the browser still has the same HTML it got from the page originally. Just sending an AJAX request won't change that. If you want the HTML in the browser to change to reflect the new state of the database, you will NEED to do one of two things:
Refresh the page, so the entire thing is rebuilt by PHP based on the current database state
Use javascript to change the HTML in the browser, to reflect the changes you have made to the database state.
It is wrong on so many levels but it's difficult to put in words. It's subtle.
Long story short - think about jquery.ajax as of another virtual tab of you browser.
When you make ajax-request to the server - you create new virtual tab.
You php header could affect this virtual tab and redirect it where that header defined.
But it will redirect that virtual tab, not your current tab - if that makes sense.
What are your options? On success - make redirect with pure javascript.
success: function(response){
location.href = "http://localhost/project/car";
}
This would be the basic way to solve your problem.

PHP not redirecting when working with Jquery post [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to manage a redirect request after a jQuery Ajax call
I have a form that is validated client-side with Jquery. Jquery then passes this data to a php script for server-side validation. At the end of the php script, I try to redirect upon success, but no re-direction happens.
Is Jquery interfering with the redirection? How can I get the php script to redirect. Don't want to redirect with jquery, bc I am going to use sessions and want to keep the session data at redirection.
Here is the code:
JQUERY:
$.ajax({
//this is the php file that processes the data and send mail
url: "includes/process/processAdminLogin.php",
//POST method is used
type: "POST",
//pass the data
data: dataString,
//indicate result is text
dataType: "text",
//Do not cache the page
cache: false,
//success
success: function (data) {
$('input').removeAttr('disabled'); //enable input fields again.
if(data == "fail"){
$("#statusMessage").html("");
$("#statusMessage").html("<p class='statusBoxWarning'>Username and password do not match!</p>");
$('button').removeAttr('disabled');
document.forms[0].reset();
}
}
});
PHP
if($correctPass == 1){
ob_start();
session_start();
$_SESSION['usernameIdentity'] = $userName;
unset($userName, $userPass);
header("Location: ../../adminDashboard.html");
exit;
}else{
echo "fail";
}
The php script gets to the redirection part and just hangs up. I would really want to keep jquery functionality, along with php redirection. Is there a better method?
Thanks!
FINAL WORKING SOLUTION:
Ok, after the input from this post and other similar posts, this is what I have as the working solution. It may not be the most efficient or prettiest solution, but it works, and will have to do for now.
JQUERY
$.ajax({
//this is the php file that processes the data and send mail
url: "includes/process/processAdminLogin.php",
//GET method is used
type: "POST",
//pass the data
data: dataString,
//indicate result is text
dataType: "text",
//Do not cache the page
cache: false,
//success
success: function (data) {
$('input').removeAttr('disabled'); //enable input fields again.
if(data == "success"){
$('#statusMessage').html('<form action="http://www.example.com/test/userRegistration/adminDashboard.html" name="userSubscription" method="post" style="display:none;"><input type="text" name="username" value="' + reg_contact_username + '" /><input type="text" name="password" value="' + reg_contact_password + '" /></form>');
document.forms['userSubscription'].submit();
}else{alert("couldn t redirect");}
}
});
PHP
if($correctPass == 1){
echo "success";
}else{
echo "fail";
}
The receiving redirection page will have to verify username and password being given again, so validation will be done 2x...which is really inefficient. If anybody can provide me with a better solution - please! A sample write out would also help out.
Thanks!
Since AJAX happens "behind the scenes" (so to speak) your redirect will just interrupt the response to your javascript handler.
You'll need to return the URL and have your callback kick the browser to a new location.
Update:
On this note, since you have to return data to the front end, you'll want to add a status or similar variable so that you can switch your front end behavior based on whether the call "failed" or not.
Update 2:
In response to your solution, I strongly recommend against your form submission technique. As you say, it's not efficient, it's not pretty, and it requires twice the work (validating the user 2 times).
Why don't you use PHP's built in session handling to set a session if the user logs in successfully, and then simply check the session after a simple javascript browser redirect?
A javascript redirect is as simple as window.href = "http://mylocation" and if you don't know much about PHP's sessions, you could use this class I've built up (please disregard that it's also managing cookies, that's a silly oversight).
Where are you flushing your output buffer? Try to add ob_end_flush(); after the header() redirection and see if that works.
EDIT:
Maybe turning your relative URI to an absolute URI will fix your issue. This is a general example directly pulled from php.net. It creates an absolute URI based on a relative one - you could always hard-code the absolute URI instead of doing it this way.
<?php
/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>
Try using the full url in the AJAX call.
Instead of:
url: "includes/process/processAdminLogin.php",
Try:
url: "http://www.mysite.com/includes/process/processAdminLogin.php",

jquery $.ajax request remains pending

I have made a simple chat application which uses long-polling approach using jquery,
function sendchat(){
// this code sends the message
$.ajax({
url: "send.php",
async: true,
data: { /* send inputbox1.value */ },
success: function(data) { }
});
}
function listen_for_message(){
// this code listens for message
$.ajax({
url: "listen.php",
async: true,
timeout:5000,
success: function(data) { // the message recievend so display that message and make new request for listening new messages
$('#display').html(data);
listen_for_message();
}
});
}
THIS SHOULD HAPPEN : after page loaded the infinite request for listen.php occurs and when user sends message, the code sends message to database via send.php.
PROBLEM is, using firebug i've found that send.php request which is performed after listen.php request, is remains pending. means the request for send message is remains pending.
The issue was because of session locking;
both send.php and listen.php files use session variables,
so session is locked in listen.php file and the other file (here send.php file) can't be served after the session frees from serving another file ( here listen.php).
How do I implement basic "Long Polling"?
the link above is a similar question that may help you.
it does not have to be on a database, it can be saved on a tmp file, but your problem is that you are choking the browser by performing too many requests, any one browser handles two requests at a time, which means you should really allow the browser to finish the first requests first then do the second one... and so on...
you do not need to do send.php and listen.php, because you can do it simply on one page both of them.
function check(){
$.ajax({
url : 'process.php',
data : {msg:'blabla'/* add data here to post e.g inputbox1.value or serialised data */}
type : 'post',
success: function (r){
if(r.message){
$('#result').append(r.message);
check();//can use a setTimeout here if you wish
}
}
});
}
process.php
<?php
$msg = $_POST['msg'];//is blabla in this case.
$arg['message'] = $msg;//or grab from db or file
//obviously you will have to put it on a database or on a file ... your choice
//so you can differentiate who sent what to whom.
echo json_encode($arg);
?>
obviously this are only guide lines, but you will exhaust your bandwidth with this method, however it will be alot better because you have only one small file that returns either 0 to 1 byte of information, or more if there is a message posted.
I have not tested this so don't rely on it to work straight away you need a bit of changes to make it work but just helps you understand how you should do it.
however if you are looking for long pulling ajax there are loads of scripts out there already made and fine tuned and have been test, bug fixed and many minds help built it, my advice is don't re-invent the wheel

jQuery/Ajax call - It Doesn't work on IE7

i make a Jquery function that (for the moment) call a function dinamically and print it with an alert. with firefox, chrome : it works! when i try on IE7 (the first time), it fails. If i reload the page (F5) and retry , it works! o_O
I FINALLY understand why that's happen. In my old website i used the jquery-1.3.2.min.js library. On this i use the jquery-1.4.2.js and in fact it doesnt work. So what's up? A bug in this new version?
cheers
EDIT
actual functions (with Bryan Waters suggestions):
// html page
prova
// javascript page
function pmNew(mexid) {
var time = new Date;
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php' + '?dummy=' + time.getTime(),
data: 'mexid='+escape(mexid)+'&id=pmnew',
success: function(msg) {
alert(msg);
}
});
return false;
}
// ajax.php
if($_POST['id']=="pmnew") {
echo "please, i will just print this";
}
Fiddler result : if i use http://localhost/website fiddler doesnt capture the stream. if i use http://ipv4.fiddler/website it capture the stream, but at the ajax request doesnt appair. if i refresh the page, yes it works. mah...i really don't know how resolve this problem...
Best way to debug is to download Fiddler and see what the HTML traffic is going on and if the browser is even making the ajax request and what the result is 200 or 404 or whatever.
I've had problems with IE cacheing even on posts. And not even sending out the requests. I usually create a date object in javascript and add a dummy timestamp just to make the url unique so it won't be cached.
ok, I'm not exactly sure what the issue is here but I think you could probably fix this by simply letting jquery handle the click instead of the inline attribute on the tag.
first change your link like this to get rid of the inline event
<a class="lblueb" href="./asynch/asynchf.php?mexid=<?$value?>"><?=value?></a>
then in your javascript in the head of your page add a document.ready event function like this if you don't already have one:
$(function(){
});
then bind a click event to your link inside the ready function using the class and have it pull the mexid from the href attribute, then call your pmNew function like so:
$(".lblueb").click(function(e){
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
Your final code should look like this:
<script type="text/javascript">
function pmNew(mexid) {
$.ajax({
type: "POST",
url: "./asynch/asynchf.php",
data: "mexid="+mexid+"&id=pmnew",
success: function(msg){
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
//document.ready function
$(function(){
$(".lblueb").click(function(e){
//prefent the default action from occuring
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
});
</script>
I believe you have an error in your SQL code. Is userd supposed to be userid?
Gaby is absolutely right that your SQL code is wide open for injection. Please consider learning PDO, which will reduce the likelihood of SQL injection significantly, particularly when using placeholders. This way you will have query($sql) and execute($sql), rather than the code going directly into your DB.
As a matter of habit you should deal with your request variables early in your script, and sanitize them to death -- then assign the cleaned results to new variables and be strict in only using them throughout the rest of the script. As such you should have alarm bells ringing whenever you have a request variable in or near an sql query.
For example at the very least you should be stripping any html tags out of anything that will get printed back to the page.
That is in addition to escaping the quotes as part of the sql string when inserting into the database.
I'm all for coding things up quickly -- sure, neaten up your code later... but get security of request vars right before doing anything. You can't tack on security later.
Anyway sorry for harping on.... as for your actual problem, have you tried what Gaby suggested: change your html to:
<a class="lblueb" href="#" onclick="return pmNew('<?php echo $value; ?>')"><?php echo $value; ?></a>
And then update your JS function to:
function pmNew(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php',
data: 'mexid=' + escape(mexid) + '&id=pmnew',
success: function(msg) {
$('#pmuser').html('<a class="bmenu" href="./index.php?status=usermain">PANEL (' + msg + ')</a>');
}
});
return false;
}
Also, with IE -- check the obvious. Clear the browser cache/history
I didn't understood the "fail", but here's another example..
function pmNew(mexid) {
$.post("./asynch/asynchf.php", {mexid: mexid, id: "pmnew"},
function(msg) {
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
It appears that this issue is faced by several people.
One of them had luck with clean installation of browser:
http://www.geekstogo.com/forum/topic/22695-errorpermission-denied-code0/
Check to make sure the content returned to the DOM is valid for the DOCTYPE specified.
I've had a similiar problem with Chrome, FF and Safari all working just fine, but finding the ajax result broken in IE. Check to make sure you don't have any extra divs or spans in the ajax result breaking your markup.

AJAX Post Not Sending Data?

I can't for the life of me figure out why this is happening.
This is kind of a repost, so forgive me, but I have new data.
I am running a javascript log out function called logOut() that has make a jQuery ajax call to a php script...
function logOut(){
var data = new Object;
data.log_out = true;
$.ajax({
type: 'POST',
url: 'http://www.mydomain.com/functions.php',
data: data,
success: function() {
alert('done');
}
});
}
the php function it calls is here:
if(isset($_POST['log_out'])){
$query = "INSERT INTO `token_manager` (`ip_address`) VALUES('logOutSuccess')";
$connection->runQuery($query); // <-- my own database class...
// omitted code that clears session etc...
die();
}
Now, 18 hours out of the day this works, but for some reason, every once in a while, the POST data will not trigger my query. (this will last about an hour or so).
I figured out the post data is not being set by adding this at the end of my script...
$query = "INSERT INTO `token_manager` (`ip_address`) VALUES('POST FAIL')";
$connection->runQuery($query);
So, now I know for certain my log out function is being skipped because in my database is the following data:
alt text http://img535.imageshack.us/img535/2025/screenshot20100519at125h.png
if it were NOT being skipped, my data would show up like this:
alt text http://img25.imageshack.us/img25/8104/screenshot20100519at125.png
I know it is being skipped for two reasons, one the die() at the end of my first function, and two, if it were a success a "logOutSuccess" would be registered in the table.
Any thoughts? One friend says it's a janky hosting company (hostgator.com). I personally like them because they are cheap and I'm a fan of cpanel. But, if that's the case???
Thanks in advance.
-J
Ok, for those interested.
I removed the full URL http://www.mydomain.com/functions.php
and replaced it with the local path functions.php and that did the trick.
Apparently AJAX has issues with cross domain ajax calls and I'm not on a dedicated server, so I imagine what's happening is every couple hours (or minutes) I am somehow hitting my script from a different location causing AJAX to dismiss the POST data.
-J
Try enabling error reporting on the jquery $.ajax function, your code would look something like
function logOut(){
var data = new Object;
data.log_out = true;
$.ajax({
type: 'POST',
url: 'http://www.mydomain.com/functions.php',
data: data,
success: function() {
alert('done');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus+" - "+errorThrown);
}
});
}
See if that sheds light on your situation.
I have a strong feeling that it's more of a server side issue rather than the client's.
The odd thing is that you see the problem for a period of time. If the client works at all, then at the minimum refreshing the page or restarting the browser should fix it.
The die() at the end of the function is suspicious, but I am not quite sure how it will affect it.
Btw you can see http headers in FireBug's Net tab, to know whether those parameters has been sent properly.

Categories