Getting PHP variables via Javascript without reloading page

Asked

Viewed 660 times

-1

I’m trying to pass on the results of foreach for <span id="mostra_ref"> mouse click, but this way is passing only the last value of the function explode, even the script being inside the foreach. I need to show each clicked reference.

<div class="entry-summary">
    <span id="mostra_ref"><?php echo @$referencia_1  ?></span>
    //primeiro mostra um valor do banco de dados
    //ao clicar em qualquer referência na classe sku imprime apenas F015 
</div>
<div class="product-variations">
    <ul class="variations list-unstyled">
        <?php
        $aux = explode(",", $referencia);  
        foreach($aux as $outras_refs) : ?>
        <li>
            <div class="thumbnails">
                <a class="zoom">

                    <script type="text/javascript">

                        $('a').on('click',function(){

                        $('#mostra_ref').html('<?php echo $outras_refs; ?>');

                        });
                    </script>


                    <div class="sku"><?php echo$outras_refs; ?></div>
                    //IMPRIME F014,F013,F015   

                </a>
           </div>
        </li>
        <?php
            endforeach;
        ?>
    </ul>
</div>
  • 2

    The problem is this: PHP is building the whole page. After PHP does its job, the page is sent to the browser. By then, everything that was PHP has already been replaced by the values you programmed. Look at the source code by the browser, it will be easier for you to understand what is being sent. You are sending 3 times the JS, each with a value, so what will be worth is the last. A solution would be you to put a different ID on each "a", and use $(<?php echo $id; ?>) on each one of them.

  • I was looking at it now, each value is right when I inspect each element. I’ll see how I can solve.

  • You could, for example, use one function only, and mount a JS variable in each one. Or even use a property data-ref="<?php echo $ref; ?>" at each anchor, and pick up the value at the onclick.

  • When you say creating an id for each "a" is creating an increment type <a id="<? php echo $id++ ? >" and calling in Js $('<? php echo $id++ >'). on('click',Function(){ ..... ? did not work out. I took the script from foreach but still keeps getting the last result. I will try to approach with $("a"). attr(ː date-reference');

  • 1

    No need to complicate, just use $outras_refs itself to create the ID. And the script is out of the foreach, just once. Within Function is that you will get the correct ID and use in echo. But in JS this end part, not in PHP.

  • I did not succeed ! You can please illustrate just how to set the id in Javascript?

  • Just looking at your code, I realize you’re doing it wrong. There are better ways to do this, I don’t mean to judge, but this code needs to be improved and much, just seeing you put a Javascript function inside the loop is no longer a good thing to see. Also, putting the @ to disguise the mistake... well, I would do it all differently... so I won’t even bother to answer your question.

  • If you’re not going to answer, you don’t need to comment. Everything you said about mistakes I know, but it’s not the problem at hand. This is a Q&A site, not a analytics site. @Ivanferrer

  • My comments are guidelines for your growth as a professional, you should learn from your mistakes, since you already recognize them, you should try to avoid them, and not "cover the sun with the sieve". Your question and your code need to be improved, so an answer here would not solve the question as a whole, as it would contribute to the extent of your problem. The site also has a comment area, and anyone working in the IT area is an analyst, so it makes no sense to post.

  • Unfortunately the policy of handling errors of the company is @, for not using framework, and having more "time", my codes I handle. That’s all right, I understand what you’re saying, I appreciate the guidelines. @Ivan Ferrer

Show 5 more comments

4 answers

1

I decided to create a id for each "a" with the variable itself $others_refs as proposed in the comment. Further I would like to another answer that does not apply the script tag inside the loop, which is a bad practice.

<div class="entry-summary">
    <span id="mostra_ref"><?php echo @$referencia_1  ?></span>
    //primeiro mostra um valor do banco de dados
    //ao clicar em qualquer referência na classe sku imprime a referência correspondente 
</div>
<div class="product-variations">
    <ul class="variations list-unstyled">
        <?php
        $aux = explode(",", $referencia);  
        foreach($aux as $outras_refs) : ?>
        <li>
            <div class="thumbnails">
                <a class="zoom" id="<?php echo$outras_refs; ?>">

                    <script type="text/javascript">

                        $('a').on('click',function(){


                        $( "#<?php echo$outras_refs; ?>" ).click(function() {
                            $( "#mostra_ref" ).html('<?php echo$outras_refs; ?>');
                        });
                    </script>


                    <div class="sku"><?php echo$outras_refs; ?></div>
                    //IMPRIME F014,F013,F015   

                </a>
           </div>
        </li>
        <?php
            endforeach;
        ?>
    </ul>
</div>
  • Look at my answer, I think that’s what you’re looking for and still remove unnecessary script repetition.

1

Well, there is a solution, perhaps it can be considered "gambiarrenta", but that will solve, without using any id and without change in PHP! But better than that I will say "how did I detect" such a solution.

Note this excerpt:

                <script type="text/javascript">

                    $('a').on('click',function(){

                    $('#mostra_ref').html('<?php echo $outras_refs; ?>');

                    });
                </script>


                <div class="sku"><?php echo$outras_refs; ?></div>

Note that the contents of .html() the same that exists within the div class="sku", which is even within itself a that is clicked, perfect!

So do the following:

Define the .on('click' for:

  $('a').on('click',function(){
  var html = $(this).find('.sku').html();

  $('#mostra_ref').html(html);
  });

That will, exactly:

Ao clicar no `a`.
Seta o `html` para encontrar o item de classe `sku` e pegar seu html.
Injeta o HTML do html no item de id `mostra_ref`.

The complete code:

<div class="entry-summary">
    <span id="mostra_ref"><?php echo @$referencia_1  ?></span>
    //primeiro mostra um valor do banco de dados
    //ao clicar em qualquer referência na classe sku imprime apenas F015 
</div>
<div class="product-variations">
    <ul class="variations list-unstyled">
        <?php
        $aux = explode(",", $referencia);  
        foreach($aux as $outras_refs) : ?>
        <li>
            <div class="thumbnails">
                <a class="zoom">
                    <div class="sku"><?php echo$outras_refs; ?></div>
                    //IMPRIME F014,F013,F015   
                </a>
           </div>
        </li>
        <?php
            endforeach;
        ?>
    </ul>
</div>

<script type="text/javascript">
  $('a').on('click',function(){
  var html = $(this).find('.sku').html();

  $('#mostra_ref').html(html);
  });
</script>

This solution is lighter, will save bandwidth and load faster. = ) Remember, if you’re declaring two things equal, it’s because something’s wrong.

Test this:

REMEMBER THIS DOES NOT REPRESENT YOUR CODE INTREGRALMENTE. THE Stackoverflow does not process PHP, so this is just one demonstration with SAME JAVASCRIPT, with sample data!

  $('a').on('click',function(){
  var html = $(this).find('.sku').html();

  $('#mostra_ref').html(html);
  });
#mostra_ref {
  background-color:#FFFF00;
  }

p {
  
  font-size:10px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Seus links:</p>
<a class="zoom">
  <div class="sku">F013</div>
</a>
<a class="zoom">
  <div class="sku">F014</div>
</a>
<a class="zoom">
  <div class="sku">F015</div>
</a>
<br>
<p>Seu mostra_ref:</p>
<span id="mostra_ref"></span>

  • Thank you @Inkeliz, your solution also works but I will score Jhonnyjks for having fewer points, besides having deleted a line of code.

1


Assuming that the variable PHP $reference = "F014,F013,F015", this must be the code you are looking for (it is not possible to run here, because it has PHP...):

    $('a').on('click',function(){

        $('#mostra_ref').html($(this).find('.sku').html());

    });
<div class="entry-summary">
    <span id="mostra_ref">F15</span>
</div>
<div class="product-variations">
    <ul class="variations list-unstyled">
        <?php
        $aux = explode(",", $referencia);  
        foreach($aux as $outras_refs) : ?>
        <li>
            <div class="thumbnails">
                <a class="zoom">
                    <div class="sku"><?php echo $outras_refs; ?></div>
                </a>
            </div>
        </li>
        <?php
        endforeach;
        ?>
    </ul>
</div>

0

Dude, it’s easy. I understood you want to use the data in both php and javascript.

First avoid this loop in the tag script. This is not cool. then you do a foreach to generate a json. depending on the amount of data you do this on the same html page, within a div with display:None. Then you can use this json data in php and after it is printed in the html page you can use it in javascript. if the amount of data is too large make a json file even.

I hope you helped him.

  • I’m new to JS so I don’t understand well, although well explained. My code worked more I’m aware of the bad practice of tag script in the loop. I took it that I had accepted my answer. If you want to exemplify with the code, maybe I can give the 50 points for you but I’m not sure if it will work @Thiago Lima, I believe so because the button is active.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.