user3745888
user3745888

Reputation: 6253

How can I share javascript var with php?

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!!

Upvotes: 0

Views: 71

Answers (4)

Jhonny Pinheiro
Jhonny Pinheiro

Reputation: 328

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.

Upvotes: 0

Fanis Hatzidakis
Fanis Hatzidakis

Reputation: 5340

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.

Upvotes: 0

Marcovecchio
Marcovecchio

Reputation: 1332

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.

Upvotes: 1

Aleksandr Sasha
Aleksandr Sasha

Reputation: 168

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.

Upvotes: 0

Related Questions