0

I am trying to have my site use Ajax from another file but it never works unless the code is actually in the view.

The site successfully calls my other Javascript file but does not seem to recognize the one with Ajax in it.

The following is in my external Javascript file with Ajax in it (ajax.js):

$(document).ready(function(){

    $("#idForm").submit(function(e) {
        $.ajax({
            type: "POST",
            url: "{{ url('/auth/login') }}",
            data: $("#idForm").serialize(),
            success: function(data)
            {
              location.reload(); 
            }
        });

        e.preventDefault(); // avoid to execute the actual submit of the form.
    });

});

And the following is in my master layout file that successfully uses the form.js file but not ajax.js .

<html>
<body>

<!--Other Stuff-->

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/forms.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/ajax.js"></script>

</body>
</html>

Any ideas?

2
  • can you try e.stopImmediatePropagation(); just a quick guess. Commented Feb 1, 2016 at 18:37
  • blade templating will not wok on js file extensions but on .blade only.You have to set the url manually i guess Commented Apr 26, 2016 at 5:27

1 Answer 1

3

By default, external js file don't support blade syntax. So, to send the ajax request from external js file need to do the followings:

  1. create a global variable to ur template.blade.php file as follows:

    var SITE_URL = "{{URL::to('/')}}";
  2. then when to send the ajax request do:

    $.ajax({ url: SITE_URL + '/route_name' });

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.