0

I've been twisting around my code for a couple of hours now but no luck in getting the right approach of putting a javascript variable inside laravel url(). The variable is taken as a string whenever I placed it as a parameter inside the url(). Below is my code. Please help.

javascript file

function generateSchedule( id, loan_type ){

          var txt_url;           

          if( loan_type == "Business" ){
            txt_url = 'addamortbusinessloan'; 
          }else{
            txt_url = 'addamortization';
          }


          $.post('{{ url("'+txt_url+'") }}', {'loanId':id}, function(data){


       },"json");

    }

This is not working {{ url("'+txt_url+'") }}. I have been twisting the quotes placement but no luck at all. The result of this is http://localhost:8000/txt_url. I want it to be like this http://localhost:8000/addamortbusinessloan or http://localhost:8000/addamortization

1
  • putting a javascript variable inside laravel url(). you can't this way. Your code above is a php template, I assume. But generateSchedule is called in the browser. So that txt_url variable doesn't exist in JavaScript at all, which is why your template engine renders the static value you see. Commented Jul 8, 2019 at 17:03

4 Answers 4

2

You do not need to put it in commas it works fine without comma. Check this

function generateSchedule( id, loan_type ){

          var txt_url;           

          if( loan_type == "Business" ){
            txt_url = "addamortbusinessloan"; 
          }else{
            txt_url = "addamortization";
          }

        var base_url="http://localhost:8000/"

        $.post( base_url+txt_url, {'loanId':id}, function( data ) {

         }, "json");

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

Comments

0

Use this blade directive to export variables to JS the easy way: spatie/laravel-blade-javascript

Comments

0

Actually you can't but if you need you can define global variable into your app.blade file like this

var BASE_URL='{{url('')}}'
</script>

Or another way you can define it in meta tag in head like this: and in your javascript file you can get it by jquery $('meta[name=base_url]').attr('content')

Comments

-1
function generateSchedule( id, loan_type ){

    var txt_url;

    if( loan_type == "Business" ){
        txt_url = '/addamortbusinessloan';
    }else{
        txt_url = '/addamortization';
    }

    var url = "{{ url('') }}" + txt_url;

    console.log(url);

    $.post(url, {'loanId':id}, function(data){


    },"json");

}

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.