Make an ajax POST request to a server through ajax/jQuery - javascript

I am trying to send a post request through ajax to another domain and get a json response. The server is situated in my company premise and through the logs, I can see that it is sending response with a json.
Following is a sample of my tries:
1)
function makeRequest(strURL){
$.get(strURL+"?callback=rest.draw_table_dyn", "{}",
function(resp){
rest.draw_table_dyn(resp);
});
}
2)
xmlhttpPost : function(strURL) {
var xmlHttpReq = false;
var self = this;
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader("Content-Type", "application/json");
self.xmlHttpReq.onreadystatechange = function() {
rest.draw_table_dyn(self.xmlHttpReq.responseText);
}
self.xmlHttpReq.send(null);
}
However, following are the problems I encounter:
1) Always the server is hit with a "OPTIONS" request rather than a "GET" or "POST" request. I understood from this link(http://engin.bzzzt.biz/2010/01/25/cross-domain-xhr-access-control-preflight/) that it is a preflight request as per the standards.
But is it possible for me to make a POST request? I tried using $.post, $.ajax or even $.get, but to no avail.
2) The response data is empty. I require the data to populate the page with items. Is there a way to read the json? Currently I am getting only an empty string with the return status a 0.
I tried xmlHttpRequest, $.ajax, $.get and $.post to send the request and receive the json to no avail.
I read here(http://stackoverflow.com/questions/4221458/how-to-make-a-jsonp-call-to-an-api-using-jquery) about keeping the script in the tag. This also didn't worked for me. Any ideas what I am doing wrong here?

Currently, the only way to POST to another origin via Ajax is if the server responds with an appropriate CORS Allow-* header:
Access-Control-Allow-Origin: your.origin
Without such a header, the request will be refused by the browser due to the Same-Origin Policy.
In your 1st example, it appears you're attempting to use JSONP (?callback=...). Such requests are strictly limited to GET as they are made by appending a new <script> element to the page rather than via XMLHttpRequest:
<script src="http://remote.origin/resource?callback=rest.draw_table_dyn"></script>
CORS is also limited in browser support to those with either XMLHttpRequest Level 2 or XDomainRequest (IE8/9).
Beyond that, you're limited to having to create a server-side proxy that mediates between the browser and the remote server.

It is possible to make a POST request using $.post and $.ajax.. Use $.ajax and provide functions for 'success' and 'failure'. In the 'error' function read the error message. This is should provide you a idea on why the ajax request is failing.
My guess is the ajax request is returning a 404 error..
P.S. $.get and $.post are shorthand versions of $.ajax ..

You can not make an ajax call to a page sitting outside your site (different domain) because of the Same Origin Policy
There are some workarounds available including using JSONP as datatype.

Related

XMLHttpRequest() JSON throws a network error but similar jQuery .getJSON code works

I have a JSON script loaded from an external website. In its simplest form, the code has been like this (and working):
jQuery.getJSON("http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?",
function(data){
document.querySelector("output").textContent = data.postal_codes[0].city;
});
However, the website owner don't want jQuery if it's not crucial, so I recoded .getJSON to the request = new XMLHttpRequest(); model:
request = new XMLHttpRequest();
request.open("GET", "http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?", true);
request.onload = function() {
var data = JSON.parse(request.responseText);
document.querySelector("output").textContent = data.postal_codes[0].city;
};
request.onerror = function() { /* this gets called every time */ };
I've modified my code many times, read documentations over and over again, yet the .onerror function is the only one always displaying. This is the console:
Which in Norwegian says that this script requested CORS, that it can't find the origin in the head of Access-Control-Allow-Origin, and that the XMLHttpRequest had a network error, and says "no access".
There could be several reasons as to why this occurs:
1: There's something wrong with the new code
2: There's something in the .getJSON jQuery function (a hack?) that prevents the error from happening
3: There's something crucial in the new code that I have forgot adding
4: There's something with my browser (IE 11 at the moment)
5: Something else?
It would be lovely with some help on this.
DEMO: http://jsbin.com/muxigulegi/1/
That isn't a network error. It's a cross origin error. The request is successful but the browser is denying access to the response to your JavaScript.
Since you have callback=? in the URL, jQuery will generate a JSONP request instead of an XMLHttpRequest request. This executes the response as a script instead of reading the raw data.
You are manually creating an XMLHttpRequest, so it fails due to the Same Origin Policy.
Create a JSONP request instead.
From http://api.jquery.com/jquery.getjson/:
JSONP
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
You do have a callback. Which means that the JQuery function can request data from another domain, unlike your XHR call.

Getting Access Denied Error

Getting Access Denied Error on https in IE. while executing ajax call (to my server1) response which has another ajax call While my Ajax call url is on http .By implementing cors I able to execute on http.Tried JSONP also but then it execute my response till it find another ajax call .How to solve ?
below is on myserver1
alert('aaa');
var xhr2 = new XMLHttpRequest();
xhr2.open('GET', 'http://myserver2.com', true);
xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr2.send();
xhr2.onload = function () {
alert('fff');
var appCreds = xhr2.responseText;
alert(appCreds);
};
alert('xxx');
In addition to the trusted site requirement I found that the problem was not fixed until I used the same protocol for the request as my origin, e.g. my test site was hosted on a https but failed with any destination using http (without the s).
This only applies to IE, Chrome just politely logs a warning in the debug console and doesn't fail.

"Security Err: Dom Exception" thrown when nesting ajax calls

Here's the issue. I'm extracting gmail contacts through an ajax call in javascript/jquery like this:
function getUserInfo() {
var xml_parse = "";
$.ajax({
url: SCOPE + '?max-results=9999&access_token=' + acToken
data: null,
success: function (resp) {
xml_parse = $.parseXML(resp);
callGmailHelperWebService(xml_parse);
},
dataType: "jsonp"
});
}
function callGmailHelperWebService(xml_parse) {
GmailHelperService.ConvertXMLToList(xml_parse, onSuccess, onFailed, null);
}
So, as you can see, if the initial ajax call is successful, i call a function which calls a web service that sits on the save server as my project (in fact, it's part of the project).
My web service (GmailHelperService) is wired up correctly, as I can definitely call it in other places (like right after this ajax call, for example). However, when I try to call it within the "success" portion of the ajax call, i get the following error:
Uncaught Error: SECURITY_ERR: DOM Exception 18
My theory is that this has something to do with cross-domain issues, but I can't understand why. And I certainly can't figure out how to fix this.
I'd appreciate any help.
JSONP is a data transfer method that involves sending your data in this format:
callback({"foo":"bar"});
As you can see, this is NOT xml. It is JSON wrapped in a callback method that will get executed when the request is done loading, thus allowing it to be cross-domain because it can be requested using a <script> tag.
You cannot simply change your dataType to JSONP and return xml, expecting it to work. XML != JSONP. You can however return XML in jsonp, for example, callback({"xml","... xml string here "}) but be mindful of quotes, all json keys and values must be wrapped in double quotes, inner-quotes need to be handled appropriately.
If your request is a same domain request (Same protocol, same subdomain, same domain, and same port,) then you can change your dataType to "XML" if you are returning XML. Otherwise, you need to either setup a proxy script to get the xml for you, or have your webservice return JSONP.
For example, the following urls are all considered cross-domain from each other.
http://example.com
http://www.example.com
https://example.com
https://www.example.com
http://example.com:8080
All of the above urls would be considered cross-domain, even if they are on the same server.

Why does this $.getJSON request error?

I have the following script that call a http handler. It calls the http handler, and in fiddler, I can see the JSON returned correctly, however this script always ends up in the error block. How can I determine what is wrong?
<script type="text/javascript">
function GetConfig() {
$.getJSON("http://localhost:27249/Handlers/GetServiceMenuConfiguration.ashx", function(d) {
alert("success");
}).success(function(d) {
alert("success");
}).error(function(d) {
alert("error");
}).complete(function(d) {
alert("complete");
});
}
</script>
I see that you're including the server name (localhost) and port (27249). Ajax requests are controlled by the Same Origin Policy, which forbids cross-origin requests in the normal case. (If you're not doing a cross-origin call, you don't need to include the http://localhost:27249 portion of your URL, which is what makes me think you might be doing one.)
You can do cross-origin calls if the browser supports them and if your server code handles the CORS requests properly. Alternately, you might look at using JSON-P.
JQuery's built-in JSON parser is rather picky, even well formatted JSON can sometimes fail if the headers are not set perfectly. First try to do a $.ajax request with type:text property and log the response. This will differentiate between a connection problem and parse problem.
$.ajax({
dataType:'text',
url: '/Handlers/GetServiceMenuConfiguration.ashx',
success: function(data) {
console.log(data.responseText);
}
});
If the problem is the connection, and you do need to request JSON across domains, then you could also use a library loader like LAB, yep/nope or Frame.js.

How to use JSONP to overcome XSS issue?

I have a piece of javascript executing on a jetty server which is sending a XMLHTTPRequest to a scoket on another server(wamp server). The request gets sent to the socket, however the XHR response seems to be getting blocked.
I have heard that I can use JSONP to overcome this problem.
However as I am new to both javascript and I have never used JSONP technique before I would greatly appreciate any help in how to use this technique?
function sendPost(url, postdata, callback) {
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request")
return
}
xmlHttp.onreadystatechange=callback
xmlHttp.open("POST",url,true)
xmlHttp.send(postdata);
}
function sendInitRQ(width, height) {
var post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><command type=\"init\"><width>" + width + "</width><height>" + height + "</height></command>";
sendPost("http://localhost:80/socket.php", post, initReturned);
}
I know that the php socket is recieving the post as when i check the server log i get a 200 on the get request.
I just want to know how can I use the JSONP approach?
I have seen exampples of the approach but Iam stilll unsure of how to do it.
The JSONP technique uses a completely different mechanism for issuing HTTP requests to a server and acting on the response. It requires cooperating code in the client page and on the server. The server must have a URL that responds to HTTP "GET" requests with a block of JSON wrapped in a function call. Thus, you can't just do JSONP transactions to any old server; it must be a server that explicitly provides the functionality.
The idea is that your client-side code creates a <script> block dynamically, with the "src" attribute set to the URL of the JSONP server. The URL should contain a parameter telling the server the name of the Javascript function you expect it to call with the JSON data. (Exactly what parameter name to use depends on the server; usually it's "callback", but I've seen some that use "jsonp".) The client must of course have that function in the global scope. In other words, if you have a function like
function handleJSON(json) {
var something = json.something;
// ... whatever ...
}
then your URL tells the server to call "handleJSON", and the server response should look like this:
handleJSON({"id": 102, "something": { "more": "data", "random": true }});
Thus when the <script> block is loaded from the "src" URL you gave, the browser will interpret the contents (the response from the server) and your function will be called.
It should be clear that you should only make JSONP requests to servers you trust, since they're sending back code to execute in your client, with access to any active session(s) your client has with other secured sites.
edit — Here's a nice article: http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

Categories

Resources