micah micah - 1 year ago 81
Ajax Question

Pass data-url attribute to jQuery ajax url

I have a form with a data-attribute containing a URL to an API JSON file:

<form class="product" action="#" data-url="dist/scripts/main.js">

I want to pass the URL from the data attribute into an Ajax call in an external script.


var apiUrl = $('.product').data('url');
console.log(apiUrl) // This returns the correct URL set above

$.ajax(apiUrl).done(function(data) {

I even condensed it like this and same result:

$.ajax($('.product').data('url')).done(function(data) {

When I do this, my doing a feedback loop, possibly because of the (data) parameter that's being used in the ajax function.

Cannot read property '0' of undefined
referring to a line that contains
currentPosition = data.Positions[0].Position;

I'm not sure why the URL isn't passing to the ajax function correctly.

Answer Source


It works here - you can see the 404 in console. Make sure you load external.js after the dom loads. In this case it's just script.js Or you can use the $( document ).ready()


    <script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <link rel="stylesheet" href="style.css" />

    <h1>Hello Plunker!</h1>
    <form class="product" action="#" data-url="dist/scripts/main.js">
    <input type="text">

 <script src="script.js"></script>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download