0

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.

6
  • Where is your external.js in your html file? Make sure it's loaded after the dom is loaded. Commented Nov 21, 2016 at 20:49
  • @Garuuk It's at the bottom of the page before the closing body tag. The ajax function is contained in a document ready function. Commented Nov 21, 2016 at 20:52
  • check your console. Do you see an API call being made? Is your ajax being called by a button/listener event? Commented Nov 21, 2016 at 20:54
  • @Garuuk The console error that keeps displaying infinitely says, Uncaught TypeError: Cannot read property '0' of undefined(…) which is referring to a line that contains this: currentPosition = data.Positions[0].Position;. I don't understand why this could be throwing an error. Commented Nov 21, 2016 at 20:56
  • You need to display your entire code if you want help. What you posted is fine. It looks like you have other code we can't see causing this. Commented Nov 21, 2016 at 21:05

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

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.