views:

1195

answers:

3

Hi Guys,

I'm new to Jquery. I have a project that has checkboxes and if their status change, then I update some sql table.

But i decided to start with the simple things first to learn how this works...

So, I want to pass to a Jquery function, a php variable if a checkbox status changes.

I have this code:

<?php ?>

<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script type="text/javascript">
      function my_function(var mensagem_id)
        {
            alert("Sucesso, Mensagem nº: " + mensagem_id);
        }
    </script>
 </HEAD>

 <BODY>
 <?php 
    $mensagem_id = "3";
    echo $mensagem_id; 
 ?>
  <input type='checkbox' name='lida' value='mensagem_id' onchange='my_function($mensagem_id)'/>
 </BODY>
</HTML>

But in firebug I keep getting the message (function my_function() not defined)...

Can anyone help me?

A: 

jQuery runs on the client, whereas PHP runs on the server. So, there is no way to pass a PHP variable to a jQuery function. You could write directly to the onchange callback:

<input type='checkbox' name='lida' value='mensagem_id' onchange='my_function( <?php 
    $mensagem_id = "3";
    echo $mensagem_id; 
 ?>
)'/>

Also note that in jQuery you should avoid setting events this way and use jQuery events instead:

$('#myinputid').change(function() {
});

Another way will be to set a hidden field with the PHP variable and use javascript/jQuery code to read it on client side.

kgiannakakis
and can I pass variable values to that jquery event?
Metraton
Yes, by using the same techniques
kgiannakakis
A: 

i think you don't have to use that var in your function parameter...

j.
Very true. Parameters are not the places to declare variables. It should just be (mensagem_id). Or, better, (mId) or something short--you don't need to declare it, just pass it when you call the function.
D_N
I tried that but still get the my_function() not defined, message :(
Metraton
A: 

Take "var" away from the function definition, and use <?php echo and ?> around $mensagem_id in the onchange call.

But you're not using jQuery at all, just simple Javascript.

kemp
I know, it's only javascript for now, but later i want to add some jquery stuff but i need to start from here :)I updated the code with your suggestion:<?php ?><HTML> <HEAD> <script type="text/javascript" src="jquery-1.4.2.js"></script> <script type="text/javascript"> function my_function(mensagem_id) { alert("Sucesso, Mensagem nº: " + mensagem_id); } </script> </HEAD> <BODY> <?php $mensagem_id = "3"; echo $mensagem_id; ?> <input type='checkbox' name='lida' value='mensagem_id' onchange='my_function(<?php echo $mensagem_id; ?>)'/> </BODY></HTML>Still the same error
Metraton
That code works fine for me
kemp