Link to home
Start Free TrialLog in
Avatar of KP3280
KP3280

asked on

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>
Avatar of Francisco Igor
Francisco Igor
Flag of Canada image

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"
Avatar of KP3280
KP3280

ASKER

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
Avatar of KP3280

ASKER

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
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.
Avatar of KP3280

ASKER

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': '*'},
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
<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