Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
systems:yii2:using_ajax [2018/05/22 11:29]
smayr [Using JQuery $.get()]
systems:yii2:using_ajax [2018/05/31 11:16] (current)
smayr [Using JQuery $.get() or $.post()]
Line 136: Line 136:
  
 == Using JQuery $.get() or $.post() == == Using JQuery $.get() or $.post() ==
-You can also get data without using AJAX by simply using this JQuery ''$.get()'' method attached to an event (such as ''OnChange'' event):+You can also get data using a simplified AJAX call using JQuery ''$.get()'' or ''$.post()'' method attached to an event (such as ''OnChange'' event)
 + 
 +Using GET method:
 <code php> <code php>
-<?= $form->field($model, 'product_name')->dropDownList(ArrayHelper::map(Products::find()->all(), 'id', 'name'),  +<?= $form->field($model, 'product_name')->dropDownList(ArrayHelper::map(Products::find()->all(), 'id', 'name'), [ 
-    ['prompt'=>'-Choose a Product-', +    'prompt' => '-Choose a Product-', 
-         'onchange'=>' +    'onchange' => ' 
-         $.get( "index.php?r=suborders/listprice&id="+$(this).val(), function( data ) {+         //var aUrl = "index.php?r=suborders/listprice&id="+$(this).val();           // with enablePrettyUrl disabled (default) 
 +         var aUrl = "'.Yii::$app->homeUrl.'suborders/listprice/id/"+$(this).val();   // with enablePrettyUrl enabled 
 +         $.get( aUrl, function( data ) {
             $( "#suborders-product_price" ).val( data );             $( "#suborders-product_price" ).val( data );
          });          });
-    '])+    '
-?>+]) ?>
 </code> </code>
 +
 +Using POST method:
 +<code php>
 +<?= $form->field($model, 'product_name')->dropDownList(ArrayHelper::map(Products::find()->all(), 'id', 'name'), [    
 +     'prompt' => '-Choose a Product-',
 +     'onchange' => '
 +         var anId = $(this).val();  // or $("#my_element_id").val()
 +         var aUrl = "'.Yii::$app->homeUrl.'suborders/listprice"; // with enablePrettyUrl enabled
 +         $.post({
 +            url: aUrl, 
 +            data: {id: anId},
 +            success: function( data ) {
 +                $( "#suborders-product_price" ).val( data );
 +            },
 +            error: function (xhr, status, errorThrown) {
 +                console.log("Error:  " + errorThrown );
 +                console.log("Status: " + status );
 +                console.dir( xhr );
 +            },
 +            dataType: "json"  // return data type
 +        });
 +     ',
 +]) ?>
 +</code>
 +
  
 === Examples === === Examples ===
Line 184: Line 213:
   $( "body" )   $( "body" )
     .append( "Name: " + data.name )  // John     .append( "Name: " + data.name )  // John
-    .append( "Time: " + data.time ); //  2pm+    .append( "Time: " + data.time ); // 2pm
 }, "json" ); }, "json" );
 </code> </code>