user2918003
user2918003

Reputation: 3

Passing javascript variable to php without refreshing the page

I have a 5x5 grid of div boxes (25 of them) and I am using jQuery UI to register when I drop a item in it. It will receive the title of the box it was dropped in and the name of the item, that part works.

I want to pass the title and name to PHP without refreshing the page (because then the items will reset). I get a "success!" but it seems like it doesn't pass the data.

index.php

<script>
    $(function() {
        $( "li img" ).draggable({ 
            snap: ".grid", 
            start: function (event, ui ) {
                item = $(this).attr('title');
            }
        });
        $( "li .grid" ).droppable({
            drop: function( event, ui ) {
                box = $(this).attr('title');
                $.ajax({
                    type: "POST",
                    url: 'index.php',
                    data: { box : 'box' },
                    success: function(data){
                        alert("success!");
                    }
                });

            }
        });
    });        
</script>

sessions.php

<?php
   session_start();
if(isset($_POST['box']))
{
   // store session data
   $_SESSION['box'] = $_POST['box'];
}
   //retrieve session data
   echo $_SESSION[box];
?>

How do I pass the title and name to PHP without refreshing the page?

Upvotes: 0

Views: 5620

Answers (2)

Felix
Felix

Reputation: 38102

Try to change the url and your data from this:

url: 'index.php',
data: { box : 'box' }

to this:

url: 'sessions.php',
data: { box : box }

Upvotes: 1

user229044
user229044

Reputation: 239250

Given that you're doing this...

box = $(this).attr('title');

I assume you want to pass that variable to the server. However, you're just passing the literal string "box", not the variable box.

In your code, you've written this...

data: { box : 'box' },

which needs to be this, to pass the value in box:

data: { box : box },

As an aside, you've created a global variable box. Instead of box = $(this).attr('title');, you should use var box = $(this).attr('title'); to create a variable local to the function.

Upvotes: 0

Related Questions