Mansour hassan
Mansour hassan

Reputation: 635

How to write the correct AJAX URL in Laravel

My AJAX file

function getLead(id) {
  $.ajax({
    type: "GET",
    url: "{{ url('leads/get_lead') }}",
    data: id,
    cache: false,
    dataType: 'json',
    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
    success: function(data) {
      console.log(data);
    }
  });
}

The result in console

GET http://127.0.0.1:8000/reservation/%7B%7B%20url('//leads/get_lead/')%20%7D%7D?_=1537345882551 404 (Not Found)

As you see it prints the whole URL as if it is a string.

Do I write the URL in a wrong way?

Upvotes: 0

Views: 1330

Answers (1)

Mahmoud Shiref
Mahmoud Shiref

Reputation: 56

This can be a good way - even if it has a problem - but what if you want to access the main url from an external JS file? For me. I define the main url in my header file

<script>
    APP_URL = '{{url('/')}}' ;
</script>

And access this variable from anywhere.

So for your case your ajax request will be:

function getLead(id) {
  $.ajax({
    type: "GET",
    url: APP_URL + '/leads/get_lead',
    data: id,
    cache: false,
    dataType: 'json',
    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
    success: function(data) {
      console.log(data);
    }
  });
}

Upvotes: 2

Related Questions