Rectangle 27 0

You would have to make an AJAX call from JavaScript to a PHP script. That PHP script would save the screen resolution in the current session (you'll need to use sessions for this). A PHP script requested at a later point could then access the screen resolution as passed by the JavaScript snippet.

I'm so bad in AJAX. It could be done just with javascript and php. When they are on the same page.

@Trava no, it can't be done without Ajax, sorry. Javascript runs after PHP has generated the page, and has no chance of passing anything back to PHP. This is why Ajax exists.

@Trava check out jQuery's Ajax examples: api.jquery.com/jQuery.ajax it's easy to get into, just a few lines of code.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Data transfer from JavaScript to PHP - Stack Overflow

php javascript html
Rectangle 27 0

PHP variables are set at run time. You can't do it directly within the javascript. Off the top of my head the best way I can think of to do it would be to set the php variables as session variables. Then use your javascript to call a php file via ajax/jquery that can update the session variables.

if nothing else comes up, i will try doing that.. unfortunately there is a lot of complications (for me) behind that.. :(

Change php variable based on javascript value - Stack Overflow

php javascript onchange
Rectangle 27 0

Q2&Q3 ) I think you're making it too complex for yourself. Best way to achive what you want with restrictions that you have is to combine the power of cookie and session, you'll have a faster and neater code. So what you can do is check if the session layoutType is set, if not, inject a javascript code that'll get the layoutType for you and puts it in a cookie, and next time you include viewport.php in a a page, it'll check to see if the cookie is set and will transfer it to session for future use, so you can change viewport.php to this :

<?php
  if(isset($_SESSION['layoutType'])){
    //write the code for when session is set here
  }elseif(isset($_COOKIE["layoutType "])){
    $_SESSION['layoutType']=$_COOKIE["layoutType "];
  }else{
      $script = "<script language='javascript'>function SetCookie(cookieName,cookieValue) { var today = new Date(), expire = new Date(), nDays=1;expire.setTime(today.getTime() + 3600000*24*nDays);document.cookie = cookieName+'='+escape(cookieValue)+ ';expires='+expire.toGMTString();SetCookie('layoutType',document.documentElement.clientWidth}";
      echo $script;
  }
?>

Javascript Variable to PHP Session Variable and then call it via Ajax ...

php javascript ajax session-variables viewport
Rectangle 27 0

As a previous comment mentioned, to "dynamically" update a session variable you'd have to use javascript (jQuery is a good library to use). If you add a event handlers to the dropdown box: onChange='updateVar();' and then create a javascript function to update the value of the variable. One way this function could work is to use ajax to call a php page which updates the session variable.

$("select[name='dropdownBox']").change(function() { //event handler
        newvalue = $(this).val(); //get selected value
        $.ajax({
                    type : 'GET',
                    url : 'ajax.php',
                    dataType : 'json',
                    data : {
                        p : 'updateVar',
                        v : newvalue
                    },
                    success : function(data) {
                       //on success code
                    },
                    error : function(XMLHttpRequest, textStatus, errorThrown) {
                       //on error code
                    }
                });
 } );

Then you just need a simple php script that grabs the $_GET variables and updates the $_SESSION variables required.

php - setting session variables into drop down menu selected item - St...

php mysql drop-down-menu session-variables
Rectangle 27 0

'onclick' will not fire php code. It will trigger javascript though. You can use javascript to make AJAX calls to a php page that'd in turn be able to set your session values (and ajax would help you do so without a page refresh on the button click.

#('.btn-auth btn-facebook large').click(function(){
// fire off the request to /redirect.php
request = $.ajax({
    url: "/redirect.php",
    type: "post",
    data: 'facebook'
});

// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
    // log a message to the console
    console.log("Hooray, it worked!");
});

// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
    // log the error to the console
    console.error(
        "The following error occured: "+
        textStatus, errorThrown
    );
    });
});
<?php

$_SESSION['role'] = $_POST['data'];

?>

change php session value by click - Stack Overflow

php session redirect session-variables
Rectangle 27 0

The unset is correct, but PHP is executed on the servers side. So because this is a client action, you'll need to use JavaScript to pick up the action. (you could also use an old fasion form as well). I prefer to use jQuery since it allready has the built in ajax support and makes it easy. Basically, just call a function from the onClick that passes the "ID" of the element you want to delete. Then that function will make an AJAX call to another script that will take that ID and remove the element. When that script returns a success, have JavaScript delete (or hide) the element. This way the user never leaves or refreshes the page, and the script can do some extra cleanup (like database updates, session updates, validate request, etc.)

i = 0;
 foreach($_SESSION['cart'] as $item)
{
    //Populate items in a table  ?>
<tr>
<td><center><?php echo $i; ?></center></td>
<td><center><?php echo $item['item'];?></center></td>
<td><center><?php echo ''. $item['unitprice'];?></center></td>
<td><center><?php echo $item['quantity'];?></center></td>
    <td><center><?php echo ''.($item['unitprice'] * $item['quantity']) ?></center></td>
<td><input type="submit" value="Remove" onClick="RemoveItem(<?= $i ?>)" ></td>
</tr>
<?php
 $total += ($item['unitprice'] * $item['quantity']);
$i++;
}

Here I've changed the onClick section to use a javascript call instead. You'll notice I used the <?= tag instead of a full <?php echo. This is because as of php5 you can use the shorthand <?= to echo an expression.

In your script section you can do something like this. I use POST since it's more secure.

function RemoveItem(id) {
   $.post('script-to-remove.php',
      { ItemID: id },
      function(data) {
         if(data==='success') {
            //Remove item from DOM
         } else alert("There was an error!"); //If you want error handling
      }
   );
}

For removing items from the dom, its a bit trickier with tables since none of the cool effects will really work, such as fadeOut, slideUp, animate, etc. I would look into reformatting it with divs.

As for the php script it calls, its as simple as calling the unset. You can develop it more, so as to possibly check the validity of the request, but for now, I'm just going to do the unset.

<?php 
$ItemID = isset($_POST['ItemID'])?intval($_POST['ItemID']):-1;
if($ItemID<0) die("Invalid ID"); //Change this if you want
if(isset($_SESSION['cart'][$ItemID])) unset($_SESSION['cart'][$ItemID]);
echo 'success';
?>

Basically in this, I first check that the right parameter came in, make sure it's an integer and save it, otherwise I default it to -1. Then if the Item ID is under 0 (so definatly wrong) I tell the script to output the message and quit. Finally I check that there is a value for that ID or index as it really is, and unset it. If it makes it to the end, output the success.

Hey! Thanks for a quick reply..., but to be honest I've never tried AJAX or jQuery so I don't think I got the idea... Sorry, I'm not very skilled, I'm a noob )))

I updated it a bit to help you, some additional reading can be done using google. If you really don't want to dive into AJAX (but you should) you can use a form as well that goes to the unset script. But you'll need to pass along the ID properly. Otherwise, here's some reading. phpcodeforbeginner.blogspot.com/2013/01/ net.tutsplus.com/articles/web-roundups/

That's great, thanks a lot !That function RemoveItem .. is it php function?

No, its a javascript function. So stick it in a <script></script> right above your </body> tag. If you don't know Javascript or jQuery then you should really read about it. codeproject.com/Articles/246701/JQuery-for-Beginners

php - Remove array of items from session shopping cart - Stack Overflo...

php session-variables shopping-cart
Rectangle 27 0

I have recently implemented this sort of setup: what I did to get around the problem is put the session setting code into the AJAX script and then, in the main/calling script, use that data to generate the content appropriately whenever you navigate back to that page. If you need to do it in a JavaScript script, make this a PHP script and change the content-type to text/javascript (or whatever the MIME type is supposed to be) and then you can set up the JavaScript source dynamically with PHP, just as you would with HTML... While this approach worked just fine, ultimately I went for a purely dynamic JS solution - without session variables - because my setup never required you navigating away from the same page.

php - Applying session to this piece of code - Stack Overflow

php ajax session
Rectangle 27 0

First of all I'm going to write my question in brief. I wanted to catch a event and wanted to use the event to store some value in my session to recognize that event in rest of my site unless the session is destroyed by somehow. Al the variables used in .php file stores value in them and execute all operations when they are on the server. Browser displays the result. How can we expect while a user do something [in my case clicked] and it simply store a value in a php variable while there are no php variables inside the browser. So what can we do is simply store the result in a javascript variable or go back to server and set the value to the variable. To call the server using ajax is a method of experts and honestly speaking I don't know much of it. So I needed to look for something what i already know. Of course based on php. Finally I got the COOKIE. To catch the event its obvious to use javascript. I used a event listener using jQuery and inside it I store a value in my browser's cookie. and then used both javascript and php to check the cookie in my website. This has a fallback. If user disables the cookie then you won't have the option to use it.

javascript - why i can't unset session in php? - Stack Overflow

php javascript session
Rectangle 27 0

The only way I can think of setting the $_SESSION variable of time left, would be to use an ajax call inside your javascript every second or so, that calls a php script with a get variable in the filepath. This php script would set a session variable, and your timer page would check if something like $_SESSION['timeLeft'] was set, and echo out a js variable for timeleft, if not set echo out 0.

<?php
  if(isset($_GET['timeLeft'])){
    $_SESSION['timeLeft'] = $_GET['timeLeft'];
  }
?>
$.ajax({url: "somePath/updateTimeLeft.php?timeLeft=1234"});

and when you load the page, in your php

if(isset($_SESSION['timeLeft'])){
  echo 'var timeLeft = ' . $_SESSION['timeLeft'] . ';';
  $_SESSION['timeLeft'] = undefined;
}else{
  echo 'var timeLeft = 0;';
}

javascript - Set countdown/timer to continue after reset or do not res...

javascript php jquery timer
Rectangle 27 0

PHP code runs on the server (before your code is sent to the client browser), and JavaScript on the client (after the code is sent to the client browser). I'm not sure there is any other way to pass information to the server, other than sending a request to the server. so if you want to send something to your PHP application (server side) you'll have to send a request from your JavaScript code (client side). you may use AJAX techniques, but this causes another PHP process on the server to start. so you'll have to find a way to communication between the base PHP process (who created the JavaScript) and the new process (called by the JavaScript) to pass information. you may use server side data persistence like sessions or files or databases, or inter-process communication solutions like shared memory. but I guess this will get a little more complicated in implementation.

javascript variable into php - Stack Overflow

php javascript
Rectangle 27 0

Firstly, PHP happens server side, so once the page loads the only way to use PHP again (without loading a page) is to make an ajax call, presumably to another php page that performs a certain function and returns a value.

If you want to store a value as a session variable so that it can be used continuously, you can do the following:

  • when they first land on your site have php check for the existence of a session and if it does not exist, call a Javascript function to get the layoutWidth and make an ajax call to a php page that will store it as a session variable and then reload the page and include the correct layout file.

I would probably not use this method and actually look at ways to do this with JavaScript/JQuery instead. But this is how you have asked to do it.

For your example, I have not used JQuery at all, but I would as the include is only about 19kb or so and it makes life SO much easier.

<?php
   session_start();
?>
<!DOCTYPE html>
<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <?php 
         if (empty($_SESSION['layoutWidth'])) {
            echo '<script type="text/javascript"> var session=false; var layoutWidth;</script>';
         } else {
            echo '<script type="text/javascript"> var session=true; var layoutWidth=' . $_SESSION['layoutWidth'] . ';</script>';
         }
      ?>
      <script type="text/javascript" src="js/viewport.js"></script>
   </head>
   <body>
         <?php

            if (!empty($_SESSION['layoutWidth'])) {
               $layoutWidth = $_SESSION['layoutWidth'];
               if ( $layoutWidth >= 240 && $layoutWidth <= 900 ) {
                  include('layout1.php');
               } else if ($layoutWidth > 900 && $layoutWidth <= 1200 ) {
                  include('layout2.php');
               } else {
                  include('layout3.php');
               }
            }
         ?>
   </body>
</html>
// JavaScript Document

window.onload = function() {
    // if there is no session (session = false)
    if (!session) {
        // call function to get the screen size
        getScreenWidth();

        // make ajax call to php page to set the session variable
        setSession();
    }
}

function getScreenWidth() {
    layoutWidth = screen.width;
}

function setSession() {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        // Reload the page
        window.location.reload();
        }
      }
    xmlhttp.open("POST","set_session.php?layoutWidth=" + layoutWidth,true);
    xmlhttp.send();
}

your php file to set the session the parameter is passed from your ajax call:

<?php
    session_start();
    // you can check if it is already set if you like otherwise:
    $_SESSION['layoutWidth'] = $_REQUEST['layoutWidth'];
?>
<?php
  echo '<div>This is layout2.php</div>';
  echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>
<?php
   echo '<div>This is layout3.php</div>';
   echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>

This method means you dont have to pass parameters around in your URL. it will all be hidden.

echo '<script type="txt/javascript"> var session=true; var layoutType=' + $_SESSION['layoutType'] + ';</script/>';

Done Vikram, that example works you can see it on my test_site I created for you. You had quite a number of mistakes within your examples and were missing some integral parts. Good luck, please re-add my answer as the correct answer :)

Javascript Variable to PHP Session Variable and then call it via Ajax ...

php javascript ajax session-variables viewport
Rectangle 27 0

Using ONLY Javascript, you can't. Your PHP session can only be accessed through php. The only thing you can do is create a function in php that removes whatever you want from the session, and call it from javascript using ajax calls like @MouradK said

php - Symfony2 is it possible to remove session variable with Javascri...

javascript php symfony session