Joss
Joss

Reputation: 555

AJAX not working with Laravel 4

I'm not able to use Ajax from a Blade view with jQuery. As I've researched, it just is as simply as using the function $.get or $.post as usual and taking as first parameter the appropriate root. If I do:

app/views/home/index.blade.php

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
{{Form::button("d",["id"=>"d"])}}
<script>
    $("#d").on("click",function(){
        $.post("/ajax",function(d){
            console.log("d");
        });
    });
</script>

app/routes.php

Route::post("/",['as'=>'ajax'],function(){
    return 'returned form route';
});

I'm always taking a 500 Internal server error, same case if I try with a get request. Also made:

$.post("{{{route('ajax')}}}",function(){ ...

But also does not work.

I've realized problem is I have an extra http:// at the beginning which shouldn't be there. How could I take appropriate localhost:8000 making it also working on a server?

Also checked Michael Calkins' video How to submit ajax with Laravel video but I think I've done the same and still not working.

If I write as the route the whole URL (localhost:8000/) I take a security error cross origin request and appart from this, it's clear this is not the best solution.

Upvotes: 0

Views: 1962

Answers (1)

Safeer
Safeer

Reputation: 714

From the details posted it looks like you're doing a GET on a POST route, try changing

Route::post("/",['as'=>'ajax'],function(){

to

Route::post("/ajax", ['as'=>'ajax', function()
{
    // Your code...
}]);

or alternatively change the AJAX from a $.get to a POST

Upvotes: 3

Related Questions