jfaustino
jfaustino

Reputation: 67

Yii2 Ajax DropDownList change content of div

I'm developing a application with Yii2 and I don't have to much knowledge of ajax. So I tried to use an example of W3Schools (http://www.w3schools.com/php/php_ajax_database.asp)

I want to make sort of a filter and I want to change the content of a div using a value from a DropDownList, here is the code of the view:

...
<script>
function showUser(str) {
  if (str==="") {

document.getElementById("transactions").innerHTML="";
return;
} 
  if (window.XMLHttpRequest) {

// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
 xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {

  document.getElementById("transactions").innerHTML=xmlhttp.responseText;
  }
 };    
    xmlhttp.open("GET",document.location.href="filter?by="+str,true);
    xmlhttp.send();
}
</script>
<?php $this->head() ?>
</head>

Now the DropDownList:

<?=Html::dropDownList(
    'test', //name
    'b', //select
    ['' => 'Select Filter...', '1' => 'Exchanging Now', '2' => 'Last Exchanged', '3' => 'Last Offered', '4' => 'Last Discounted', '5' => 'Last Recieved', '6' => 'View All'],
    ['onchange'=> 'showUser(this.value)'])
   ?>

Well, the content of the div "transactions" it changes but, the it redirects to localhost/.../filter?by=x

How can I stop this redirect? In my controller I'm returning a string. Is that a problem?

--- EDIT ---

After some research I read about Pjax, I tried some tests and with a simple link and with works but can't do with the dropdownlist. Here is the changes on my code. View:

<div id="categories">
<?=Html::a('TEST LINK', Url::to(['filter', 'by' => 1]), ['data-pjax' => 'transactions'])
?>
    <?= Html::dropDownList(
            'test', //name
            'b', //select
            ['' => 'Select Filter...', '1' => 'Exchanging Now', '2' => 'Last Exchanged', '3' => 'Last Offered', '4' => 'Last Discounted', '5' => 'Last Recieved', '6' => 'View All'], //items
            ['onchange' => 'this.form.submit()'], ['data-pjax' => 'transactions']
    )
    ?>

PjaxCode StackOverflow dont let me put the code of Pjax, so I uploaded an image through a link

Controller - Just to show an example of what i'm returning:

public function actionFilter() {
$by= $_POST['test'];
$string = "";
if ($by == 1) {
return $string = self::searchPendingEvent();  
}}

public function searchPendingEvent() {
    $query = Event::findBySql("Select * from dot_events where (dot_event_to_user =" . Yii::$app->user->id . " "
                    . "and dot_event_type = 1 and dot_event_completed = 0) or ("
                    . "dot_event_type = 4 and dot_event_to_user =" . Yii::$app->user->id . " and dot_event_completed = 0)"
                    . " order by dot_datecreate DESC")->asArray()->all();


    $string = "";
    if ($query == null) {
        $string .="Nothing to show :(";
    } else {

        for ($i = 0; $i < sizeof($query); $i++) {

            $string.= self::formatEvent($query[$i]['dot_event_id']);
        }
    }

    return $string;
}

public function formatEvent($id) {

if ($model['dot_event_type'] == 1 && $model['dot_event_to_user'] == Yii::$app->user->id) {
        $string .= "<p class='text-primary text-right p1'>" . Functions::xTimeAgo($model['dot_datecreate'], date("c", time())) . "</p>";
        $string .="<div class='well'>";
        $string .="<p class='lead text-left text-primary'>";
        $string .= "<img class='img-circle' height='50' width='50' src='" . Yii::$app->request->baseUrl . "/img/user/" . $model['dot_event_to_user'] . ".png' alt='Image Missing'>";
        $string .=Html::a("You", ['user/profile']);
        $string .="</p>";
        $string .="<p class='text-left'>requested " . Html::a($profile[0]['full_name']);
        $string .="to trade " . Html::a($tradeE['dot_cr_dots'] . " pts", ['dashboard/index']) . " from company ";
        $string .=$company['dot_com_name'] . " for company" . $companyE['dot_com_name'];
        $string .="</p>";
        $string .="</div>";
    }

Upvotes: 2

Views: 9179

Answers (1)

Degger
Degger

Reputation: 4313

redirect starts at this line:

xmlhttp.open("GET",document.location.href="filter?by="+str,true);

after asignment

document.location.href="filter?by="+str

I thinks there is mistake or typo. Try this:

xmlhttp.open("GET",document.location.href+"/filter?by="+str,true);

Or with jQuery ( http://api.jquery.com/load/ ):

function showUser(str) {
  $( "#transactions" ).load( "test.php", { "by": str } );
}

where test.php - url where from you get data for your #transactions block

UPD: remove your <script>...</script> in head

<?=Html::dropDownList(
    'test', //name
    'b', //select
    ['' => 'Select Filter...', '1' => 'Exchanging Now', '2' => 'Last Exchanged', '3' => 'Last Offered', '4' => 'Last Discounted', '5' => 'Last Recieved', '6' => 'View All'],
    ['onchange'=> 'showUser(this.value)'])
  ?>
  <?php
  use yii\web\View;
  $this->registerJs('
  function showUser(str) {
      $( "#transactions" ).load( "dashboard/filter", { "by": str } );
  }', View::POS_END);
  ?>

So now your js code positioned after connecting jQuery file.

Upvotes: 1

Related Questions