Search code examples
phpjqueryajaxsymfony-1.4

symfony 1.4 and jquery. How to pass variable to jquery function?


I have the template indexSuccess.php with an AJAX function:

<script type="text/javascript">

    jQuery(document).ready(function(){


 jQuery('#test<?php $mensajes->getIdmensajes() ?>').click(function(){

            jQuery('#contenido<?php $mensajes->getIdmensajes() ?>').load(this.href); 
            return false;

        });

    });

</script>


<h2>Listado de mensajes emitidos</h2>
<h3>En orden cronológico inverso (más nuevo primero)</h3>

<table id="enviados" width="60%" border="1" cellpadding="8">
  <thead>
    <tr>

      <th>Fecha Creación</th>
      <th>Contenido del mensaje</th>
      <th>Destinatarios</th>
    </tr>
  </thead>
  <tbody>
   <?php foreach ($mensajess as $mensajes): ?>

    <tr>

      <td width="10%" align="center"> <?php echo date('d/m/Y', strtotime($mensajes->getFechaalta())) ?></td>
      <td bgcolor="<?php echo $mensajes->getColores()->getCodigo() ?>"><?php echo $mensajes->getCuerpo() ?></td>
        <td  width="20%" id="contenido<?php echo $mensajes->getIdmensajes() ?>">   


       <a  id="test<?php echo $mensajes->getIdmensajes() ?>" href="<?php echo url_for('mensajes/receptores?idmensajes='.$mensajes->getIdmensajes()) ?>">Ver receptores</a>

        </td>

    </tr>

    <?php endforeach; ?>

  </tbody>
</table>

I want to pass the value $ message-> getIdmensajes () to the AJAX function. I will have a different ID for each row, but this does not work. But the function works well when I set the value. For example: jQuery ('# test24') and jQuery ('# contenido24') works well for the value Idmensajes=24 . How do I pass the value $ message-> getIdmensajes () to AJAX function?


Solution

  • Your question is not so clear but you wrote

     jQuery ('#contenido24') works well for the value Idmensajes=24
    

    Also, you have this

    jQuery('#test<?php $mensajes->getIdmensajes() ?>').click(function(){
        jQuery('#contenido<?php $mensajes->getIdmensajes() ?>').load(this.href); 
        return false;
    });
    

    So, I think you have elements with similar ids, such as contenido24, contenido25 and so on as data container and links with ids like #test24, #test25 an so. If this is the case then you can simply use

    jQuery(document).ready(function(){
        // Register click handler for all a tags whose id begins with 'test'
        jQuery("a[id^='test']").click(function(e){
            e.preventDefault(); // instead of return false
            jQuery('#contenido'+this.id.match(/\d+/)[0]).load(this.href);
        });
    });
    

    jQuery('contenido'+this.id.match(/\d+/)[0]) will select elements with id like #contenido24, contenido25 depending on the ID of a, if an a tag has id='test20' then it'll select #contenido20 and load content from ajax call into this element.