Call post on external Rest API with Ajax - javascript

I am new to angular, and I'm trying to make a call to a Rest API and get its response. My issue is that my JavaScript keeps getting stuck on the Ajax call. I'm not sure if it's the data I am sending or the syntax of the Ajax call. I tried to alert 'Hello world' and that worked, then I alerted the JSON array and that was formatted correctly, but when I do the Ajax post, I don't get any response at all.
Any insight would be nice, thank you.
test.html
<button onclick="myFunction()">Post it</button>
test.js
function myFunction() {
var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
];
$.ajax({
url: '192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
};

You have specified a relative URL, where I think you intended to specify an absolute URL. If the current page URL is http://localhost/myapp/, and you request 192.168.2.164/isapi/rip.dll/rest/session, that URL is resolved as http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session.
If 192.168.2.164 is the ip address of the server you are trying to hit (and not a directory relative to your current path on your server), you will need to add // to the beginning of the URL to make it absolute (well, schema-relative at least):
$.ajax({
url: '//192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});

Your issue has nothing to do with angular. What I will refer you to is the angular docs description of how to do a POST request and a small example of the syntax taken from the docs.
Learn to use $http or something similar if you want to develop with angular. https://docs.angularjs.org/api/ng/service/$http
Small example:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Related

Jquery: Probably a syntax Issue in ajax() method - Value not getting sent

I'm able to dump value of the variable message in console .
But im not able to send it off in POST Request.
AJAX call:
chat.throwmsg = function(message) {
if ($.trim(message).length != 0) {
console.log(message);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'throw', message: message} ,
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
}
}
This maybe due to wrong syntax, but I've tried both single and double quotes, and combination as well .
With a wild assumption, you are not having any error messages in developer console and chat.php has a post handler forthese parameters
Since your data is JSON, please change the code as this way and have a try..
var temp={ method: 'throw', message: message};
var param=JSON.stringify(temp);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: param ,
dataType: "json",
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
after reviewing the code I could not find any issues that restrict the data to be sent along with ajax request,if you are having any syntax errors you should have been warned prior the request initialization, however I recommend you to check the request header in the network tab of browser console and see your sending data along with the request if it's there you probably need to check the code of getting the post data in your server-side implementations

JQuery Ajax petition is modifiying given URL

I want to consume a API Rest aplication using JQuery Ajax. this is the code that I have:
var res=$('#myForm').attr('action');
console.log(res);
$.ajax({
url: res,
success: function (data) {
alert('success!!');
},
dataType: 'html'
});
The console.log sentence is printing the url correctly, I just copied and pasted it into the browser and its correct, it's something like this:
http://localhost/myproject/public/2
But then, the request gives a 404 error, and the URL that is requesting is this one:
http://localhost/localhost/myproject/public/2
So, why it's attaching another localhost line to the url? I just don't understand!
All you need is to get the part after localhost. For this, please use split method.
var res=$('#myForm').attr('action');
console.log(res);
$.ajax({
url: res.split('localhost')[1],
success: function (data) {
alert('success!!');
},
dataType: 'html'
});

$.AJAX Post not working in JS but works in Advanced Rest Client

I'm having an issue with my JavaScript being able to contact the HttpPost service. I can access the same signature using the "Advance Rest Client Application" for chrome. However when I run my code in Console in Chrome I am unable to reach the service. Any thoughts? What am I missing from the signature on one vs the other? Please let me know if you need any more information.
JS AJAX Request (Stuck in Pending status)
$.ajax({
type: 'POST',
url: 'http://local/r/GetSettings',
data: '[{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]',
dataType: "json",
success: function(data){
alert(data)
},
error : function (error) {
alert("Error: " + error);
console.log("ERROR. not working", error);
}
});
C# Service
[HttpPost]
public ActionResult GetSettings(List<Source> sources)
{
return new ContentResult
{
Content = "{}",
ContentType = "application/json"
};
}
Advanced Rest Client Application (Success in returning {})
http://local/r/GetSettings
Content-Type: application/x-www-form-urlencoded
Payload::: [{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]
Change your URL for ajax request
AppContextRootName: Your application context root
$.ajax({
type : 'POST',
url : '/AppContextRootName/GetSettings',
dataType : 'json'
});
Thanks for the answers. I found out my issue why the Ajax call was not executing. I found out you can execute a AJAX statement while paused in the debugger!!! So don't try! It will execute and return and object but it will show pending in the network. Once you unpause the actual call is executed. You should just use Alert("Hello world") in the success and error and you will see it come back once you unpause.

POSTing JSON data to Server URL

I am facing problem when I am posting a JSON data to the server using Ajax call in jQuery the function does not enter success mode. When I post using the POSTER Plugin of Firefox it gets posted successfully. Sharing the code snippet and screenshot of the same:
function showSubscribeContent()
{
alert("*1*------- SUB CLICKED");
var myJSONData = '{"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}}';
alert("*2*------- POSTING--------->"+myJSONData);
$('#subscribePage').html('<h1>POSTING...</h1>');
$.ajax({
type: 'POST',
url: 'https://tt.s2.acc.com/tt/subscribe-service/uid=sagar_mate',
data: myJSONData,
dataType: 'application/xml',
success: function(data) {
alert("*3*------- POSTED SUCCESSFULLY TO THE SERVER");
$('#subscribePage').html('<h1>POSTED</h1>');
} // Success Function
}); // Ajax Call
}
I am getting alert number 1 and 2 but not 3.
Also when I post using POSTER plugin of Firefox, it gets posted easily.
The Response is success.
I am unable to post the same data using AJAX call.
Thanks,
Ankit
Unless and until the URL in your AJAX call is of the same Domain, I don't think it will get posted successfully. POSTER plugin of Firefox doesn't put any such restriction on the domain, but browser will put this restriction on the application.
Try checking in the error: function(){alert(4);}
to see if it reaches the error handler atleast
Please clearify what you want, when using POSTER Plugin of Firefox you have specified datatype as json where as when using ajax you are using xml.
If you what to post data as JSON use JSON.stringify which accepts JSON object and convert it to string.
Try with this code
function showSubscribeContent()
{
alert("*1*------- SUB CLICKED");
var myJSONData = {"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}};
alert("*2*------- POSTING--------->"+myJSONData);
$('#subscribePage').html('<h1>POSTING...</h1>');
$.ajax({
type: 'POST',
url: 'https://tt.s2.acc.com/tt/subscribe-service/uid=sagar_mate',
data: myJSONData,
dataType: 'application/json',
success: function(data) {
alert("*3*------- POSTED SUCCESSFULLY TO THE SERVER");
$('#subscribePage').html('<h1>POSTED</h1>');
} // Success Function
}); // Ajax Call
}
Here I have changed the following lines
Converted myJSONData to a JSON object from string
var myJSONData = {"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}};
Note: try with the string(the way you were doing) if this is not working for you
Changed datatyle to JSON
dataType: 'application/json',
Adding a header in beforeSend Function worked fine for me. Security reasons of CORS.

jQuery $.getJSON not working

I am try to get a URL from a one server and using that URL to get contents of another server.
$.ajax({url : 'http://localhost:8080/geturl.jsp?A=1&B=2,C=3',
success : function (data)
{
alert(data);
$.getJSON(data, function (mydata)
{
alert(mydata);
});
},
error : function (data, status, xhr)
{
}
});
I know that we cannot make cross-domain requests in through ajax call, thats why i am using getJSON, i have the following problems
When i simply pass the data to the url part of getJSON (as shown in the code), the alert-box show the correct URL but no get request is being performed ( get requests were monitored from FireBug).
When a hard-code the data to be "http://www.google.com" then the get request is being performed but the no response comes, although the response headers comes and response code is 200 (but it was marked as RED in the Firebug (Dont know why :( )
When I tries to fetch a webpage host in localhost domain, then it is fetched correctly although the response was not JSON.
I have the following doubts
If the getJSON function accecpts only JSON objects as reponse then why no error came when perform above 3.
Whats the correct code to perform my the required functionality.
Suggestions to what happened in each case
Thanks in advance for the answers :)
The getJSON function can only be used across domains to fetch JSONP.
It does not magically evade any security restrictions.
http://api.jquery.com/jQuery.ajax/
This should be a working example for jsonp:
var request = jQuery.ajax(
{
url: "http://Your url",
success: function (data) { console.log('success!'); console.log(data); },
error: function (data) { console.log('error!'); console.log(data); },
dataType: "jsonp",
type: "GET",
data: { key: 'value' }
});

Categories

Resources