PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 18, 2022

[FIXED] how to pass value inside loop in template to jquery

 October 18, 2022     jquery, symfony, twig     No comments   

Issue

I want to pass a value inside a loop into a query. I made a list of rings and displayed those using a loop in a twig. and I wanted to edit one of them when I clicked the Anker.

This is my twig,

        {% set ring_id = ''%}
        {% for ring in rings%}
        <tr>
            <td><p>{{ ring.id }}</p></td>
            <td><p>{{ ring.ring_name }}</p></td>
            <td><p>{{ ring.ring_type }}</p></td>
            <td><p>{{ ring.ring_shape }}</p></td>
            <td><p>{{ ring.size }}</p></td>
            <td><p>{{ ring.price }}</p></td>
            {%set ring_id = ring.id %}
            
            <td><a href="#" id='ring_delete' >Delete</a></td>
            
        </tr>
        {% endfor %}

This is my query,

  <script>

$(function() {
    var ring_id = "{{ring_id}}";
    $('#ring_delete').on('click', function(e) {
     $.ajax({
            url: "{{ url('admin_product_custom_delete_ring') }}",
            type: "POST",
            dataType: 'json',
            data: { 
            },
            async: false
        }).done(function(data){
            alert('check' + data);
        }).fail(function(){
            alert("no");
        })

    });
 </script>

So I want to delete the ring that I chose by passing ring_id to the url. However, it says ring_id does not exist, even though I added {%set ring_id %}. How can I pass a value inside a loop using a twig into a jquery?


Solution

Try using data attributes.

<a href="#" class="ring_delete" data-id="{{ ring.id }}">Delete</a>
$('.ring_delete').on('click', function(e) {
  var ring_id = $(this).data('id');

Also notice I changed ring_delete from an id to a class. This is because ids need to be unique and there can only be one with that name. Since it's inside a loop and will be several, we should use classes instead to reference.



Answered By - Torsetha
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing