HuntingForIrish
HuntingForIrish

Reputation: 29

jquery script not being executed in html

I am attempting to retrieve information from the Movie DB API and the jquery code doesn't seem to be executing. I thought my JSON code may be off but after testing before important functions I realised that it wasn't being run. Here is the script:

<script type="text/javascript">
//test 0
$("#title").html('<h1>JS Loaded</h1>');
$(document).ready(function(){
  //test 1
  $("#title").html('<h1>Document Ready</h1>');
  var getPoster = function(){
    //test 2
    $("#title").html('<h1>Get poster Executed</h1>');
    $.getJSON(
    "http://api.themoviedb.org/3/discover/movie?with_cast=31&sort_by=popularity.desc&api_key=d34d1c194fd655e99cc15a631bad6760&page=1",
   function(data) {
     if (data != "Nothing found."){
       $('#poster').html('<img alt="Film/Show Poster" width="101px" height="150px" src=' + data.results[0].poster_path + ';>');
     } else {
       $('#title').html('<h1>NO POSTER WAS FOUND</h1>');
     }
    });
  }
  $('#poster').click(getPoster);
});

jQuery is declared in the header, like so:

script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">

Any insight onto what the problem may be would be much appreciated.

Upvotes: 0

Views: 363

Answers (2)

sayanriju
sayanriju

Reputation: 570

In all probabilities, this is just a CORS related error.

Your AJAX request is failing, because the origin of the request (made by JavaScript within your html file) and the API server are "Cross Origin" (basically different domains and/or ports), and browsers tend to restrict "Resource Sharing" between them for security.

If you are using Chrome, try adding an extension like CORS Toggler, enable it and retry.

Upvotes: 0

Raults
Raults

Reputation: 306

I've had this happen to me in a similar situation, except with a get and a post. I ended up just swapping to an ajax call. try this:

$.ajax({
  dataType: "json",
  url: "http://api.themoviedb.org/3/discover/movie?with_cast=31&sort_by=popularity.desc&api_key=d34d1c194fd655e99cc15a631bad6760&page=1",
  success: (data) => {
if (data != "Nothing found."){
       $('#poster').html('<img alt="Film/Show Poster" width="101px" height="150px" src=' + data.results[0].poster_path + ';>');
     } else {
       $('#title').html('<h1>NO POSTER WAS FOUND</h1>');
     }
},
});

Don't quote me on this, because it doesn't explicitly say so in the documentation, but I think the .getJSON() call has the response the get is sending back as the second parameter and not the actual response data you got from the endpoint.

Upvotes: 0

Related Questions