Ajax with Yii 2?

I need to load a page dynamically via something like Ajax. How does Yii 2 handle this? Basically I just want to click a button and have the contents of another URL appear in a div on the same page. Very basic stuff, but I’m wondering if Yii has this built in somehow.

I’m trying this code below





 <p><a id="ajax" class="btn btn-lg btn-success" href="<?php echo"$url"; ?>">Choose Winner</a></p>




<div id="winner"></div>


<script type="text/javascript">

$(document).ready(function(){

  $('#ajax').click(function(){

    $('#winner').load($(this).attr('href'));

    return false;

  });

});

</script>




And it’s not working. $url is the url of the page I want to load.

Can anyone help?

May be Pjax will be good for you? Pjax is a jQuery plugin that uses ajax and pushState

Look at examples http://ksetrin.com/example/pjax/index (examples of code and implementations)

Hmm I can’t really read that site. Why would pjax be a better solution? is my implementation far off?

ok, try https://translate.google.com/translate?hl=en&sl=auto&tl=en&u=http%3A%2F%2Fksetrin.com%2Fexample%2Fpjax%2Findex&sandbox=1

You want "Basically I just want to click a button and have the contents of another URL appear in a div on the same page"

Just look example http://ksetrin.com/example/pjax/pjax-example-3 (it’s original link, because google try translate the code). You may click buttons and you see how change content in example block.

Why better?

  1. Pjax is already implemented in yii2

  2. Less code more results

  3. Do what you basically want