-4

hi i want to pass a javascript variable to php function in the same page.In the head of my page i have this javascript code

<script type="text/javascript">
function getTableRow() {
    var userSelect;
    if (!document.getElementsByTagName || !document.createTextNode) return;
    var rows = document.getElementById('products_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
            userSelect = this.rowIndex;
        }
    }
}
</script>

and in the body i call a php function and i want to pass as argument the javascript variable userSelect.

<body>
 <p><?php table_from_xml(javascript variable); ?>
 </p>
</body>

Is impossible to do that without reload the page?

user3071235
  • 17
  • 1
  • 7

1 Answers1

-1

Here is a basic example of what you could do using ajax. It is pretty self explanatory.

<?php
if(isset($_POST["variable1"])){
    $javascriptVariable = $_POST["variable1"];
}
?>
<script type="text/javascript">
function getTableRow() {
    var userSelect;
    if (!document.getElementsByTagName || !document.createTextNode) return;
    var rows = document.getElementById('products_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
            userSelect = this.rowIndex;
        }
    }
}

$('#your-button').on("click", function(){
       var somevar1 = "your variable1";
    $.ajax({
        type:"POST",
        url: "ThisFile.php",
        data: "variable1=" + somevar1,
        success: function(){
        //do stuff after the AJAX calls successfully completes
    }

    });
});

</script>

<body>
 <p><?php table_from_xml($javascriptVariable); ?>
 </p>
</body>
Kevin Lynch
  • 24,427
  • 3
  • 36
  • 37
  • I don't know if i do something wrong but didn't work..In the $('#your-button') i must have a button to work?All idea is that i have an html table with products(All products have a link to another page.. same page).With javascript i take the row index of user selection.That row index i want to pass it to php function and do something before i redirect to new page.I don't know if you understand me but i am a little confused now..Thanks for your help. – user3071235 Dec 14 '13 at 20:13
  • That's no way near self-explanatory. – geotheory Dec 30 '14 at 15:53