1

I have an ajax call that has some blade templating inside. This ajax call is used repeatedly over multiple views. I would like to define it once and link to it in each view but I get errors due to blade syntax. What can I do so I only have it defined in one place?

/public/myapp.js

//checkbox validation
    $(document).ready(function(){
    //Check age and display dialog box to over-ride age if administrator
    $('input:checkbox').click(function(e) {
        if( $(this).prop('checked') &&  $(this).val()=='on' )
        {
            e.preventDefault();

            var name = $(this).attr('name');
            var pivot_attendee_program = name.split(/\]\[|\[|\]/);
            var data = {
                        'pivot' : pivot_attendee_program[0],
                        'attendee_id' : pivot_attendee_program[1],
                        'program_id' : pivot_attendee_program[2]
                       };
                $.ajax({
                    type: "GET",
                    url: '{{ route('ageCheck') }}',
                    data: data,
                    context: this,
                    success: function(result){
//...code goes on but is irrelevant

I get error

Error: SyntaxError: missing } after property list
Source Code:
                    url: '{{ route('ageCheck') }}', 

1 Answer 1

3

You can't just use PHP code (that's what Blade essentially is) in JavaScript files. A simple workaround for this problem is to inject the route url as a JavaScript variable.

This has to be inside a blade file (usually your layout)

<script>
    var ageCheckUrl = '{{ route('ageCheck') }}';
</script>

And then you can use that variable in your external JS files:

type: "GET",
url: ageCheckUrl,
data: data,
context: this,
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.