1

Hi I am using one AJAX function for 7 API sync calls so that I tried this code:

<a href="javascript:void(0)" class="sync-commands" data-name="order-sync" >Shopify Order Sync</a>
<a href="javascript:void(0)" class="sync-commands" data-name="shopify.order.sync">Shopify Product</a>

and in ajax call, I am using this code:

$('.sync-commands').on('click', function (e) {
    e.preventDefault();
    var route_name =$(this).attr("data-name");

    $.ajax({
        url: "{{route(route_name)}}",  //error line here no route/undefine variable etc

How can I access this variable in my URL? I just want to call only one ajax call of 10 calls for different routes. How can I do this?

2 Answers 2

4

I'm guessing the ajax call is inside a JS file and not in a script tag at the bottom of blade template. So from this, maybe it would be easier to use the route helper function in the blade template:

<a href="javascript:void(0)" class="sync-commands" data-name="{{route('order-sync')}}">Shopify Order Sync</a>

<a href="javascript:void(0)" class="sync-commands" data-name="{{route('shopify.order.sync')}}">Shopify Product</a>

This is then rendered as the full route, then your JS event will work with a slight change:

$('.sync-commands').on('click', function (e) {
    e.preventDefault();
     var route_name =$(this).attr("data-name");
    $.ajax({
        url: route_name,
Sign up to request clarification or add additional context in comments.

1 Comment

thats also awsom.
2

Cleaner way to do it without using data tags by using a natural workaround of anchor tags and by using preventDefault() in your js file.

<a href="{{route('order-sync')}}" class="sync-commands" >Shopify Order Sync</a>
<a href="{{route('shopify.order.sync')}}" class="sync-commands">Shopify Product</a>

JS

$('.sync-commands').on('click', function (e) {
    e.preventDefault();
     var href = $(this).attr("href");
    $.ajax({
        url: href,

2 Comments

ok, that's great. Will it reload the page or not in your condition?
@MuhammadAmirShahzad it won't refresh the page. preventDefault() default action of the event won't trigger if you have this. You can check it from jquery docs here api.jquery.com/event.preventdefault

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.