generale2222
generale2222

Reputation: 33

PHP JavaScript passing variable

I have a simple problem here that I don't understand and can't fix it.

The code gets data from MySQL database and display it in html box as a link which direct to Google (just for test), then added some code to display the content in the same page without refresh, so added the JavaScript code which direct to the link that I want.

(info.php?session=9&course=matlab) 

but in this link I want to get the (9) and the (matlab) as variables from he PHP code.

Note: currently when I press the link info.php opens, not Google. When I change the link is the JS to take variable.

(info.php?session='<?php echo($number);?>'&course=matlab)

It doesn't work and when I click the link, Google opens.

<?php
$mem_query = mysql_query("SELECT number FROM courses WHERE `course` = 'matlab'");

while($run_mem = mysql_fetch_array($mem_query)) {
    $number = $run_mem['number'];
    $course = 'matlab';
    ?>
    <div class="m_box">
        <?php 
        //echo '<a href="',$user_n,'"><img src="t_images/', $user_i, '"></img></a><br>'; 
        ?>
        <div class="box_link">
            <?php
            echo "<br><a href=www.google.com>$number</a><br>";
            ?>
        </div>
        <div class="clear">
        </div>
    </div>
    <?php
}
?>

<div id="content">hiiiiii</div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function() {
    //$('#content').load('content/index.php');
    $('div a').click(function() {
        //var page = $(this).attr('href');
        $('#content').load('info.php?session=<?php echo($number); ?>&course=matlab');
        return false;
    });
});
</script>

Upvotes: 2

Views: 95

Answers (2)

Fr4ncx
Fr4ncx

Reputation: 356

Use AJAX to get the data you need from the server,because your server side and client side scripts are completely separate. How ever you can insert an input hidden like this :

<input type="hidden" name="date" id="hiddenField" value="<?php echo $number ?>" />

Then with JQuery you can take this value

$(document).ready(function() {        
    $('div a').click(function() {
        var number = $('#hiddenField').val();
        $('#content').load('info.php?session='+number+'&course=matlab');
        return false;
   });
});

Upvotes: 1

Radek Pech
Radek Pech

Reputation: 3098

Try to manually cancel the event:

$('div a').click(function(e) {
    (!e || e.preventDefault());
    $('#content').load('info.php?session=<?php echo($number); ?>&course=matlab');
    return false;    
});

Sometimes jQuery does not correctly react when you just return false from the handler. Especially when it throws an exception and the function does not reach its end.

Upvotes: 0

Related Questions