Consume Rest Post API from Jquery Ajax

I need to consume a rest  post from a html page and display the values. i am unable to call the Rest post api

Requirmet is i need to take a the text value and call a rest post api with the entered text value  the rest will return a json and i need to  display a table from json

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        function callme(){
        alert("hello");
 var playerid = document.getElementById("t1").value;
 alert(playerid);
    $.ajax({
          url: "http://localhost:8080/",
            contentType: "application/x-www-form-urlencoded",
          type: "POST",
        dataType:"jsonp",
            data: { serialNo: playerid },
             contentType: "application/x-www-form-urlencoded",            
         success: function(resp){alert("Server says" + resp);},
         error: function(e){ alert("An error has occured");},

     });
   }
  </script>
</head>


<form id="form1" method="POST" onsubmit="callme();">
            <input type="text" name="t1">
            <input type="submit" Value="SUBMIT">
        </form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<p>
<table id="records_table" border='1'>
    <tr>Name</th>
    </tr>
</p>
</table>
KP3280Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

F IgorDeveloperCommented:
In this code

 $.ajax({
          url: "http://localhost:8080/",
....

Open in new window


You are posting to the root document of server?

Make sure your page in "url" parameter  is the page that process the POST / REST request  

eg: url: "http://localhost:8080/path/to/REST_controller.php"
0
KP3280Author Commented:
Hi

yes i am pointing to the location of the request . to make it simple i made as get with path param and  changed the code as below
$.ajax({
          url: "http://localhost:8080/ax/services/MS/getModules/"+playerid,
          type: "GET",
        dataType:"jsonp",            
         success: function(resp){alert("Server says" + resp);},
         error: function(e){ alert("An error has occured");},

     });
   }

when i directly run the http://localhost:8080/ax/services/MS/getModules/avc12345  on the browser i get a json result

"modelList":[{"pd":122,"bomModuleId":21402,"timeStamp":"2015-08-04 22:22:07","RD":"","station":"","ms":"asde12345","lc":"","dc":"","ic":"","pn":"123096","description":"CGS","mvc":"peg","bas":1}]

but i am not getting when i call from html page
0
KP3280Author Commented:
Hi I guess the problem is with JSONP it is expecting a call back function . can anyone suggest how to go proceed with the above problem
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

hieloCommented:
The last $.ajax() call example you posted looks fine.  What jquery does for you under the hood is that is appends to your url a GET callback parameter with some random value.  To clarify, even though you specified:
"http://localhost:8080/ax/services/MS/getModules/"+playerid

jquery "transforms" that to something similar to:
"http://localhost:8080/ax/services/MS/getModules/"+playerid+"?callback=jq123"

where "jq123" is the "random value" I was referring to.  You need to take the value of the callback parameter and use it to form a "javascript function call" and put your json within the parenthesis of the function call. So instead of a raw/bare json string, you need to emit:
jq123( {"modelList":[{"pd":122,"bomModuleId":21402,"timeStamp":"2015-08-04 22:22:07","RD":"","station":"","ms":"asde12345","lc":"","dc":"","ic":"","pn":"123096","description":"CGS","mvc":"peg","bas":1}]} );

In PHP $_GET['callback'] will give you the value of the callback parameter.
In classic ASP Response.Querystring("callback") will give you the value of the callback parameter.
0
KP3280Author Commented:
I don't have control on the service part. i cant change anything on the service part. i tried to change the code   to json . but below code works fins in safari not in chrome and firefox
dataType:"json",
            data: { "user": username },
         contentType: "application/x-www-form-urlencoded",
         async: false,
         headers: {'Access-Control-Allow-Origin': '*'},
0
hieloCommented:
>> I don't have control on the service part
OK, then if the service is not emitting the CORS header -- Access-Control-Allow-Origin: *
then client-side scripting will not work.  You are restricted by cross-domain restrictions.

Instead, you need to have the browser submit to your server -- let's say you have a script on your server named proxy.php.  On your webpage, you submit the ajax requests to your proxy.php page.  In turn, proxy.php needs to submit the POST request to the server.  The cross-domain restrictions are in effect on the browser, not on the server.

BTW:
>> headers: {'Access-Control-Allow-Origin': '*'},
That header is not meant to be sent from the browser (via the ajax call) to the server.  When you make the request to the third-party site, the third-party site needs to send that header to the browser.  If the browser sees that header, then it will not impose the cross-domain restrictions.  Contact the service provider and find out if they have an API that you can use from the client-side. If that is not the case, you'll need to use a proxy script on your server as I discussed above.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Nrupendra Nath PanigrahiCommented:
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        function callme(){
        alert("hello");
 var playerid = document.getElementById("t1").value;
 alert(playerid);
var postdata={'playerid':playerid};
    $.ajax({
            url: "http://localhost:8080/file.php",
            type: 'POST',
            data: postdata,
            success: function (response) {
                //console.log(response);
                var obj = JSON.parse(response);
var row="<tr><td>"obj.key"</td></tr>";
$('#records_table').append(row);
},
         error: function(e){ alert("An error has occured");},

     });
   }
  </script> 
</head>


<form id="form1" method="POST" onsubmit="callme();">
            <input type="text" name="t1">
            <input type="submit" Value="SUBMIT">
        </form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<p>
<table id="records_table" border='1'>
    <tr>Name</th>
    </tr>
</p>
</table>

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.