Route does not execute controller method

Asked

Viewed 1,972 times

1

Good afternoon. I have a problem with my php code developed in Laravel 4. I have a Javascript function that executes an action using $.post and if successful, calls another Javascript function, this second one using $.ajax. Both on .blade.’s pages. The problem is that when entering the second function, I suspect that the path passed in the url field is not found, but I can’t find the error. Can someone help me? Follow the codes:

javascript functions:

function form_variations_submit()
{
    $.post(
        '{{route('admin.ajax.save')}}',
        $('#form').serialize(),
        function(data) {
            if(data.sucesso) {
                alert("Alterações Salvas! "+data.pvid);
                var pvid = data.pvid;
                alert("pvid = "+pvid);
                var flagOrder = envia_pvid(pvid);
                alert("FlagOrder = "+flagOrder);
            } else {
                alert(data.erro);
            }
        }
    );
    return false;
}

function envia_pvid(id){
    var pId = id;
    alert("Entrou na 2 função! Envia_id "+ pId);
    $.ajax({
        type: 'POST',
        url: '{{route('admin.ordem')}}',
        data: { pId : pId
        },
        sucess: function(data) {
            if(data.pvid){
                var ret = data.pvid;
                alert(ret);
                return ret;
            } else{
                alert("ERRO!");
            }
        },
        dataType: "json"
    });
}

Route:

Route::post('p_var', array('as' => 'admin.ordem', 'uses' => 'Admin_Controller@setaOrdem'));

Function setOrder present in Controller:

public function setaOrdem()
{
    $pvid = Input::get('pId');

    return Response::json(array('sucesso' => true,'pvid' => $pvid));
}

The Alerts are run nomally to Flagorder Alert which returns "Undefined".

  • When the page is rendered what appears instead of '{{route('admin.ajax.save')}}'?

  • When inspecting the element appears: http://.... /admin/ajax_save (real name of the function corresponds to admin.ajax.save)

  • I will assume that the http://.... is abbreviated. The route /admin/ajax_save is there? How did you state it? In your question just as for admin.ordem

  • Yes '...' is the abbreviation of the url that has the name of the local server that is running the application and the folder hierarchy of the project. I declared the previous route the same way I declared the route that is not running: 'Route::post('ajax_save', array('as' => 'admin.ajax.save', 'uses' => 'Admin_controller@ajax_save'));'

  • I advise you to debug in the google console Chrome.

  • This could be the problem so far as I know the folder public of Laravel should be used as the main path, using Virtualhost for example, if it is in a subfolder you will probably have to point it as well.

  • then, but for the first function everything runs normally, but for the second function, located in the same folder, which executes a function in the same controller as the previous one, nothing happens. I think the error is on the route, but I may be wrong.

  • It would be interesting to separate PHP from javascript. You used the Blade syntax in the middle of javascript.

Show 3 more comments

2 answers

0


I’ll give you some tips that can help you solve the problem:

First I would like to emphasize about Javascript.

What the hard part $.post of jQuery concerning the $.ajax is that $.post does not have the error key to making error treatments, already $.ajax does. So if one function depends on the other in case of success, I advise you to use $.ajax in both functions to capture errors:

$.ajax({
  url: '//sua url',
  type: 'tipo da requisição',
  data: //dados de envio,
  success: function(response)
 {
    //retorno
 },
 error: function(xhr)
 {
   console.log(xhr.responseText);
 }
});

This is important because certain types of errors are only possible to capture through the error function and many people do not know the differences between the $.post, $.get and $.ajax. But that was just a hint, this situation does not interfere with the location of the route.

Now about the Laravel

I noticed that you are using named routes. As you did not leave the real url splash I will exemplify the possible errors:

Creation of routes in the Laravel

When you use requesting routes POST

Route::post('url','Controller@metodo');

To GET

Route::get('url/{identificador}','Controller@metodo');

For any request

Route::any('url','Controller@metodo');

If you are on localhost and have not created the virtual host you have to specify the full url in javascript for the route to be found. Already in production it does not have this problem if it is configured to point to the public folder. If you created the virtual host it is important that you pass the URL as follows:

$.ajax({
    url : '/url real não nomeada' //EX: '/admin/ajax-savar-dados'
});

I do not advise you to use the named route in javascript. First, because it is a terrible practice to put PHP in the middle of javascript. It may even be one of the reasons for the errors. Ideally, you can put javascript in a separate file.

to test your $.ajax request use the browser console in option

network > xhr

0

If you look at the network tab in your browser’s developer tools you will probably notice error 404.

From what I understand the folder public your project is not the main folder, the Laravel to work properly need that folder public be the root server (for example apache), otherwise you will have to declare the subfolders and it will be difficult to move to production.

Laravel works exactly like this, oriented to folder public of your project, as it being the main of everything, if your project is in a folder like this:

  • /etc/www/projeto1

And you try to access:

  • http://localhost/projeto1/ or http://localhost/projeto1/public/

The routes will not understand the way, as they work from the first / after the localhost at the url http://localhost/

Apache:

If you are Apache you can change the documentroot:

DocumentRoot "/home/user/projeto-em-laravel/public"
<Directory "/home/user/projeto-em-laravel/public">
    AllowOverride all
</Directory>

Ngnix:

On Nginx you use the root to point out:

root /home/user/projeto-em-laravel/public/;

These examples are for development, for production you will probably have to edit the virtualhost, or do like this answer:

  • So, but the Network shows no error, the tbm console shows no error! It simply does not run, does not change the URL, or anything.

  • @Joabnunes The error should be checked not only at the time you load the page, but also at the time you make the ajax requests. The network tab should contain codes such as 200 (Ok), 404 (Notfound) and 500 (Internal error server). The Laravel may even show "200 ok", but this may be because your mod_rewrite is disabled. I edited the answer. See the part I explain "Laravel works exactly like this, oriented to the public folder of your project".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.