Home Ask Login Register

Developers Planet

Your answer is one click away!

Kopse February 2016

How can i call a javascript function from a php file?

In my PHP-Code i have got a variable $password, which i want to edit in a javascript function which is located in a .js File. That means passing $password as a parameter to the function and saving the return value into the variable.

How can I do this?


Gabriel Mendez February 2016

I know you can try to add this to your PHP code:

echo '<script type="text/javascript"> drawChart(); </script>';

and it will access your script, however you should really try to do it with AJAX.

Hope it works for you

Gwendal February 2016

Here is how to do it with jQuery and Ajax :



$_SESSION['password'] = "whatever";

header("Content-Type: application/json");
echo json_encode(array("password" => $_SESSION['password']));

Javascript part, don't forget to include jQuery

    // Let's get the password !
    $.ajax({url: "http://yoursite/getPassword.php", dataType: "JSON"}).done(function(response) {
        // Stocking the password here
        var password = response.password;

        // Do whatever you wan't with the password
        password = processPassword(password);

        // Post the password to php
        $.post("http://yoursite/setPassword.php", {password: password});

And finally, setPassword.php



if (!empty($_POST['password'])) {
    // Retrieving the password sent by ajax in session
    $_SESSION['password'] = $_POST['password'];

Post Status

Asked in February 2016
Viewed 3,706 times
Voted 9
Answered 2 times


Leave an answer

Quote of the day: live life