Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Javascript variable to PHP via ajax

I am trying to pass a variable from my javascript code over to the server side PHP code. I know this must be done via an ajax call which i believe i have done correctly, however accessing the variable i pass from my ajax into my php is when i run into trouble as i am new to php. Here is my code i have thus far:

$(document).ready(function() {

            $(".clickable").click(function() {
                var userID = $(this).attr('id');
                //alert($(this).attr('id'));
                $.ajax({
                    type: "POST",
                    url: 'logtime.php',
                    data: "userID=" + userID,
                    success: function(data)
                    {
                        alert("success!");
                    }
                });
            });
        });

<?php //logtime.php
$uid = isset($_POST['userID']);
//rest of code that uses $uid
?>

I'm trying to pass my javascript variable "userID" to php ($userID), however i've gone wrong somewhere along the road. Thanks for the help!

like image 711
Staleyr Avatar asked Mar 17 '13 14:03

Staleyr


People also ask

How pass data from JavaScript to PHP using AJAX?

click(function() { var userID = $(this). attr('id'); //alert($(this). attr('id')); $. ajax({ type: "POST", url: 'logtime.

Can I pass JavaScript variable to PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result.

How use JavaScript variable on same page in PHP?

You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.

Can I use JavaScript in AJAX?

AJAX is not a programming language. AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)


1 Answers

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):

data: { userID : userID }

And in your PHP do this:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value.

like image 132
mirrormx Avatar answered Sep 20 '22 15:09

mirrormx