skip to Main Content

I’m trying to create a search field on the top navbar with ajax. Since it’s on the navbar, it has to be present on all pages, therefore the URL is constantly changing.

$.ajax({
            type: 'GET',
            url: CURRENT_URL,
            dataType: 'json',
            data: {
                search: userSearch
            },
            success: function (){...

I’m working with Laravel, so i tried this on the navbar page:

<script>
            var CURRENT_URL = "{{url()->current()}}"
</script>

The CURRENT_URL is displayed fine if i try to console log it, but ajax gives an error “Source map error: Error: request failed with status 404”.
How can i insert the current URL into the ajax request?

2

Answers


  1. Hopefully, this can help. Here’s my approach to make my url dynamically I get the URL in every forms var URL = $('#example_form').prop('action'); then the URL variable must append or set via Js/Jquery. check my example below.

    <script type="text/javascript">
    var URL = $('#example_form').prop('action');
    $.ajax({
          type:'GET',
          url: URL+'/clearContent',
          beforeSend: function (xhr) {
            var TOKEN = $('meta[name="csrf-token"]').attr('content');
            if (TOKEN) {
              return xhr.setRequestHeader('X-CSRF-TOKEN', TOKEN);
            }
          },
          data:{
            get_category_id : $('.parent-id').val(),
          },
          success:function(data){
            if (data.response.status == true) {
              // your codes here
            }
          }, 
          dataType: 'json',
          complete: function () {}
        });
    
    Login or Signup to reply.
  2. You can use location.href instead of CURRENT_URL

    $.ajax({
                type: 'GET',
                url: location.href,
                dataType: 'json',
                data: {
                    search: userSearch
                },
                success: function (){...
    

    or

    <script>
                var CURRENT_URL = location.href;
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search