ptamzz
ptamzz

Reputation: 9375

How to assign the value of a javascript variable to a php variable

I've a form.

<form action="inc/genxml.php" method="post">
      <input id="nameTxt" name="name" type="text" value="test"/>
      <button id="nameSave" class="left">Save</button>
</form>

And a div element #name

When I click the save button, I want to pass the position of the div #name to the form action file. To get the position, I'm using jQuery .position().

Something like below. (which just prints out the coordinates)

$('#nameSave').click(
    function() {
        var pos = $('#name').position();
        alert("left: " + pos.left + ", top: " + pos.top );
    }
);

I want to pass the coordinate values (pos.left & post.top) to the form action file (in this case to the file genxml.php).

How should I do that?

Upvotes: 0

Views: 1051

Answers (3)

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

Try this:

var pos = $('#name').position();
$("form").append('<input type="hidden" name="name_position" value="' + pos.left + ',' + pos.top + '" />');

Then read name_position value from the POST data in the server side code.

Upvotes: 1

polarblau
polarblau

Reputation: 17744

The easiest way would be to use a hidden input field and use jQuery to set the value for this input field or these input fields in your case.

HTML:

<form action="inc/genxml.php" method="post">
    <input id="nameTxt" name="name" type="text" value="test"/>
    <input id="posLeft" name="posLeft" type="hidden" />
    <input id="posRight" name="posRight" type="hidden" />
    <button id="nameSave" class="left">Save</button>
</form>

JS:

$('#nameSave').click(
    function() {
        var pos = $('#name').position();
        $('#posLeft').val(pos.left);
        $('#posRight').val(pos.right);
    }
);

Upvotes: 7

kaklon
kaklon

Reputation: 2432

add two hidden input to your form and use jQuery to change their value

Upvotes: 2

Related Questions