Search code examples
javascriptjqueryurlgetgetjson

getJSON is adding the previos URL. jQuery


I have an Spring Server with HTML pages with Thymeleaf Engine and I am using jQuery for making a getJSON:

When my server is redirecting to that URL localhost:8080/redirect_admin/ where is the the next peace of code:

<table>
    <tr>
     <td>
       <input type="text" class="add_youtube_link" th:id="${id_local}"  />
       <input type="button" id="upload_youtube_links" onclick="add_youtube_link()" value="Add new Youtube Link"/>
    </td>
  </tr>
</table>

Where I can add a link to add in my server. Well, when I click on onclick the next Javascript function will run:

function add_youtube_link()
{
   var url2 = "add_youtube_link/"+$(".add_youtube_link").attr('id')+"/"+$(".add_youtube_link").val().replace(/\//g,"_");
   alert(url2);
   $.getJSON(url2, function (data) {
   //  window.location = "redirect_media/"+$(".add_youtube_link").attr('id');
   });
}

So, the alert function is showing correctly the new URL: add_youtube_link/1/ZyDO4FUVxXk untill this point all is OK.

But, if I take a look in the Network Log on Chrome, the URL called is:

GET http://localhost:8080/redirect_media/add_youtube_link/1/ZyDO4FUVxXk 404 (Not Found) .

So, the problem is that the previous URL redirect_admin/ is adding automatically in the new URL. Anyone knows how to solve it?

Thank you


Solution

  • Its always a good idea to use a base url in your code, so you don't face issues like this:

    var baseUrl = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
    

    Then include that base url with any url

    var url2 = baseUrl + "add_youtube_link/"+$(".add_youtube_link").attr('id')+"/"+$(".add_youtube_link").val().replace(/\//g,"_");