micah micah - 12 days ago 4
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">
[...]
</form>


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

external.js:

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.

Error:
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

https://plnkr.co/edit/RT0cHEAjDHFssXg2YbC4?p=preview

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()

<html>

  <head>
    <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" />
  </head>

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

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

  </body>

</html>
Comments