How to call servlet from jQuery $.ajax without getting HTTP 404 error -


i trying call servlet using ajax call below:

$.ajax({   url: 'checkingajax',   type: 'get',   data: { field1: "hello", field2 : "hello2"} ,   contenttype: 'application/json; charset=utf-8',   success: function (response) {     //your success code     alert("success");   },   error: function (errorthrown) {     //your error code     alert("not success :"+errorthrown);   }                          }); 

however, goes error function , shows alert:

not success :not found

how caused , how can solve it?

when specify relative url (an url not starting scheme or /), become relative current request url (the url see in browser's address bar).

you told servlet available at:

http://localhost:8080/fullcalendarproject/checkingajax

imagine web page ajax script runs opened via:

http://localhost:8080/fullcalendarproject/pages/some.jsp

and specify relative url url: "checkingajax", interpreted as:

http://localhost:8080/fullcalendarproject/pages/checkingajax

but not exist. return http 404 "page not found" error.

in order work, need specify url using 1 of below ways:

  1. url: "http://localhost:8080/fullcalendarproject/checkingajax"

    this not portable. you'd need edit everytime move webapp domain. can't control inside webapp.

  2. url: "/fullcalendarproject/checkingajax"

    this not portable. you'd need edit everytime change context path. can't control inside webapp.

  3. url: "../checkingajax"

    this not portable, although can control inside webapp. you'd need edit everytime move around jsp folder, if you're moving around jsps you're busy coding, done @ same time.

  4. best way let jsp el dynamically print current request context path. assuming js code enclosed in jsp file:

    url: "${pagecontext.request.contextpath}/checkingajax"

    or when it's enclosed in own js file (good practice!), create either global js variable:

    <script>var contextpath = "${pagecontext.request.contextpath}";</script> <script src="yourajax.js"></script> 

    with

    url: contextpath + "/checkingajax"

    or html5 data attribute on document element:

    <html data-contextpath="${pagecontext.request.contextpath}">     <head>         <script src="yourajax.js"></script> 

    with

    url: $("html").data("contextpath") + "/checkingajax"


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -