PlayHardGoPro PlayHardGoPro - 6 days ago 6
Ajax Question

Using ajax with laravel

I'd like to know if it's possible to use

Ajax
with
Laravel
without writing the code inside a .js file.

Script.js



$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '',
data: ...

});
})


I don't know how to get the
URL
that I want (which is my currently page,

I just want to change the < select> value then reload the data that's already shown on the page).

Do I have to write the ajax inside my
.php
files? Is this a 'good practice'?

I'm asking this because I already have another script inside that same .php file.

Update

Following the answer posted by @ohgodwhy

Now nothing happens when the ajax executes.

It hits the
success
code but nothing happens, the URL does not change. Is it because I'm redirecting to the same page am at?

file.php



<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: { anoSemestre: anoSemestre },
success: function(){
console.log('HELLO WORLD');
}

});
})
</script>


MyController:



public function getProfessorList()
{
$professor = Professor::all();
if( Request::ajax() )
{
echo 'yolo';
}
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres'));
}

Answer

What I usually do is add a @yield('scripts') section to my layout that I extend.

Then in the child templates that require specific JS, I'll add that in there.

@section('scripts')
     <script>
         //your javascript here.
     </script>
@endsection

There is 1 caveat however. If you use an @include from within a child template, and that included file has it's own javascript, it must invoke the parent first, like this:

@section('scripts')
    @parent
    <script>

    </script>
@endsection.
Comments