Reputation: 11
I have gone through Laravel Blade tutorial. I have using it in my project. But I want to add different blade template views on basis of Item selected in drop-down list.
Example:- I have one create Question.blade.php page.
Question.blade.php
<div class="question_type">
<?php $question_type= array('--' => '--- Select Question Type ---')
+QuestionType::lists('name', 'id') ?>
{{ Form::select('question_type', $question_type,'--' ,array('id'=>'question_type','class' => 'form-control')) }}
</div>
Now I want to add different type of views on basis of option selected in Question_Type drop-down. I am trying to do it in Java Script.
Java Script Code:-
function addQuestion()
{
var question_type=$("#question_type").val();
switch (question_type)
{
case 1:
$("#Questions").load("questions/type1.blade.php");
case 2:
$("#Questions").load("questions/type2.blade.php");
default:
$("#Questions").load("questions/default_type.blade.php");
}
}
But I am getting error localhost/mywebsite/question/questions/type1.blade.php 404 (Not Found)
Is there any solution to include blade view using @if @else or @switch on basis of dropdown selected item's value?
My Pseudo Code:-
@if {{question_type.selected.val='1'}}
@include(question.type1);
@elseif {{question_type.selected.val='2'}}
@include(question.type2);
@else
@include(question.default_type);
@endif
Upvotes: 0
Views: 4219
Reputation: 24661
If you're making a request to laravel, you need to have a route with a method associated with it (whether its a simple closure as in their hello world examples or a method inside of a controller class).
Inside of that method is where you can perform your logic on which view to return:
if($someCondition) {
return View::make('template1');
} else {
return View::make('template2');
}
In your javascript, send your question_type
along as a parameter in the AJAX request. Then in your controller method you can make your decision:
$("#Questions").load("questions/type", "question_type="+question_type);
Your route:
Route::get('questions/type', function() {
switch(Input::get('question_type')) {
case 1:
return View::make("questions/type1.blade.php");
case 2:
return View::make("questions/type2.blade.php");
default:
return View::make("questions/default_type.blade.php");
}
});
Your call to jQuery.load()
will implicitly set the contents of the DOM element with ID Questions equal to the entire output of the request (whatever is contained in the returned view). From the jQuery docs:
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data.
Upvotes: 2