0

I have a php file. I click on and with onclick I call a javascript function with a parameter passed. This parameter is received on javascript function like a var, but into this function I want add this to $_SESSION php var.

 script language="javascript">
 <?php
 session_start();
 ?>
function recargar(myVar){   
   var variable_post="Mi texto recargado";
   <?php
      $_SESSION['b'] = variable_post;  //Here I want add myVar
   ?>
   });          
 }
  </script>

 </head>
 <body>
 <div id="recargado">My text</div>
 <p align="center">
     <a href="miscript.php" onclick="javascript:recargar(myVar);">recargar</a>

 </p>    
 </body>
 </html>

I know that this could be a wrong way, how can I do this possible or in a similar way?

Thanks!!

2
  • $_SESSION is server side, submit your variable to the file through ajax to update your session. Commented Aug 25, 2015 at 19:54
  • How can call this with ajax? I'm begginning with this. Can you teach me some tutorial? Thanks!! Commented Aug 25, 2015 at 22:17

4 Answers 4

1

You can only manipulate $_SESSION on the server, but JS code runs only on the client. The easiest way to do that would be with an ajax call, which will look like this, assuming you're using jQuery:

function recargar(myVar){   
   var variable_post="Mi texto recargado";
   $.get("setsession.php?var="+variable_post);
   });          
 }

This will run the setsession.php script on the server, without reloading the page. The setsession.php script will look like this:

<?php

  $_SESSION['b'] = $_GET['var'];

?>

Of course, this code needs more work on error handling, but this is the general idea.

Sign up to request clarification or add additional context in comments.

Comments

0

You won't be able to set php session through js but you can use cookies with javascript like this :

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}

Just call setCookie to set cookie, getCookie to get it and checkCookie to check it.

Comments

0

Javascript, loaded on the client-side like this, cannot write into a PHP variable directly, because PHP resides in the server-side.

To do what you want you will need to pass your Javascript variable to PHP in the server-side, via an HTTP request. It can be, for example:

  • clicking on a link like <a href="myscript.php?myVar=something">Click</a>, which will reload the page (and there you will be able to do $_SESSION['b'] = $_GET['myVar'] ),
  • having a <form> submit, just like the link above,
  • or without re-loading the page by using AJAX, meaning "background" calls from Javascript to other pages without leaving your page. You can do AJAX calls in many ways, some of the other answers mention jQuery, a Javascript library that makes it easy to do such things. This post seems to explain it well.

Comments

0

use ajax, passing the variable to a php file.

Just below created a index.php file name in the header receives a script with an ajax, you will see that it is sending the variable you created to another file name file.php that receive so that you can process and return to the index.php file so you may make an append to your html.

I will put an example that the script's been a for variable returned can be treated the way you want.

If you do not know a lot of ajax follows the link via ajax jquery documentation. http://api.jquery.com/jquery.ajax/

//---------------------------------------------------------------------------

index.php
<!DOCTYPE html>
    <html>
        <head>
            <script type="text/javascript" src="js/jquery.js"></script>
            <script type="text/javascript">
                $(document).ready(
                    function(){
                        var variable_post="Mi texto recargado";
                        $.ajax({
                            url:'file.php',
                            type:'post',
                            data:{variable_post:variable_post},
                            success:function(data){
                                $('h1').html(data);
                            }
                        });
                    }               
                );
            </script>
        </head>

        <body>
            <h1>Text Here</h1>
        </body>
    </html>

//---------------------------------------------------------------------------

file.php

<?php
    $_SESSION['b'] = $_POST['variable_post'];

    echo $_SESSION['b'];
?>

//---------------------------------------------------------------------------

Remembering that using the browser features, for example in Chrome Inspect Element -> NetWork, you can check out everything that is sent back to the ajax a php page.

If you have any questions let me know.

4 Comments

Is it valid to do in the same php? When I load the php file get undefined var variable_post
@user3745888 Sorry, i don't understand your question. What is it valid to do in the same php? The AJax?
I mean if $.ajax({... is into function recargar(){ I am trying this, but not load the value of var into data:{variable_post:variable_post}, to read this in the next page. I hope I've explained myself well. Thanks!!
@user3745888 Take a look and see if you understand. If you do not understand, let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.