Ajax request using Javascript - javascript

I have to make ajax request for mobile web app, I used the following code
$.ajax({
type: type, //GET or POST or PUT or DELETE verb
url: requestURL, // Location of the service
// contentType: "application/x-www-form-urlencoded", // content type sent to server
dataType: "xml", //Expected data format from server
processData: false, //True or False
success: successCallback, //On Successfull service call
error: serviceFailed// When Service call fails
});
But it failed with error "Error: Access is denied. I am calling .aspx service from javascript

You cannot submit AJAX requests to domains other than the one serving the web page. If it is a sub domain causing the problems, you can use this code to resolve it.
document.domain = location.host.replace(/^.*?([^.]+\.[^.]+)$/g,'$1');

Related

Getting parse error while fetching text file content in JQuery

I am trying to fetch data from text file which resides on server. I have access of that location and able to see content when I put URL in browser tab.
I am trying to make AJAX call and get file content, but I am getting Error: Uncaught SyntaxError: Unexpected identifier
Code
function logResults(json){
console.log(json);
}
$.ajax({
url: u,
dataType: "jsonp",
jsonpCallback: "logResults"
});
on console,
I tried below code too, but same result,
$.ajax({
type: 'GET',
url: u,
crossDomain: true,
dataType: 'jsonp',
async: false,
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function(succ) {
console.log("Success: ", succ)
},
error: function(err) {
console.log("Error: ", err)
}
});
This code is always going into error block.
You said:
dataType: "jsonp",
But the URL is responding with:
Deployment automatically finished…
Which is not JSONP, it is plain text.
You get the error when it tries to execute the plain text as JSONP.
Don't put wrong information in the dataType field.
async: false,
That's deprecated. Don't use it. It's also pointless since you are using callbacks.
It's also incompatible with JSONP so it is ignored (until you remove the incorrect dataType).
crossDomain: true,
This has no effect unless you are making a:
non-JSONP request
to the same origin
which gets redirected to a different origin
… which is very rare.
headers: {
"Access-Control-Allow-Origin": "*"
},
Access-Control-Allow-Origin is a response header. It doesn't belong the request. Trying to add it to the request will cause extra problems as it will make the request preflighted.
(At least, that would be the case if you hadn't said dataType: 'jsonp' because adding request headers is incompatible with JSONP).
All you need on the client
The only code you need on the client is:
function logResults(result){
console.log(result);
}
$.ajax({
url: u,
success: logResults
});
The server you are requesting the data from will need to use CORS to grant you permission to access it if it is a cross-origin request.
It is because you have added dataType as jsonp, so that it will try to parse the response to JSON and if the response is not a JSON it will throw error.

Cross domain ajax causing issues to render data

I trying to capture data from an HTML form which will be placed on another website. From that form I need to capture data into my website. But when I tried jQuery Ajax call for cross domain it shows me 302 error with no response.
I've tried this
$('button[type="button"]').on('click', function(){
var data = $('.data-capture-form').serialize();
$.ajax({
type : 'POST',
url: 'http://prospectbank.co.uk/leads/test',
dataType: 'jsonp',
crossDomain : true,
data : data,
contentType: 'application/jsonp'
}).done(function(res){
var resp = $.parseJSON(res);
console.log(resp);
});
});
Where is problem with this code? Any help?
Fiddle Code
If you have access to the server, add the following header:
Access-Control-Allow-Origin: *
And then make JSONP calls
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ....
If you do not have access to the external server, you have to direct the request to your server and then make a proxied call to the external server.

Authenticating ajax queries in CouchDB with jQuery

When accessing a localhost's protected CouchDB database via $.ajax, it prompts an alert asking for the username/password. If i cancel the prompt, CouchDB alerts an error and my $.ajax error callback is never executed. If i pass in an authorized user to the url (http://user:pass#local...), the success callback is executed properly.
So, is possible to make authenticated ajax queries to Couch and use my own error handling functions?
Edit, code:
var request = $.ajax({
url: myUrl,
type: "GET",
dataType: "jsonp",
success: function(){
console.log("ok");
},
error: function(){
console.log("error");
}
});
If myUrl does not include credentials, like http://localhost:5984/mydb/handshakeDoc, error callback is never executed after cancelling the prompt.
If myUrl include invalid credentials, like http://user:invalidpass#localhost:5984/mydb/handshakeDoc, error prompt still appears and error callback is never executed after cancelling the prompt.
If myUrl include valid credentials, success callback is executed
----- possible solution -----
So, I got a solution that worked for me. However I had to use apache as a Proxy server to circumvent the cross origin policy.
The idea here is to remove the problems with the cross domain policy and use an http-server to proxy our request locally to the couchdb service. Every request for example.com/couch will be redirected to the couchdb service. That way you don't have to use a jsonp request anymore.
The initial problem you asked about whether or not you can use your own error handling is directly linked to jsonp requests in jQuery as they do not use the error handlers - They never get called at all.
Apache configuration:
<VirtualHost 123.123.123.123:80>
ServerName example.com
ProxyPass /couch http://localhost:5984
ProxyPassReverse /couch http://localhost:5984
</VirtualHost>
jQuery ajax request:
var request = $.ajax({
url: "http://example.com/couch",
dataType: "json",
}).done(function() {console.log("done");})
.fail(function() {console.log("fail");})
.always(function() {console.log("always");});
});
----- Original post -----
You could try this:
var request = $.ajax({
url: myUrl,
type: "GET",
username: user,
password: pass,
dataType: "jsonp",
success: function(){
console.log("ok");
},
error: function(){
console.log("error");
}
});
jQuery gives you the possibility to use the http basic auth via two ajax parameters (username and password).
Or you might wanna try the CouchDB jQuery plugin.

XmlHttpRequest status 0 even when the call to service succeeded

I call to Wcf Service via Jquery(JS), after a long time of trying it works.
The call to service is as follows:
function CallService() {
var request = { userName: "aaa", password: "123" };
var jsondata = JSON.stringify(request);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:xxxx/Service1.svc/GetUser", // Location of the service
data: jsondata, //Data sent to server
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
crossDomain: true, //True or False
success: function (result) {
alert('success');
},
complete: function () {
alert('completed');
},
error: function (xhr, status, message) {
alert('error with status - ' + xhr.status);
}
});
}
I put BreakPoint in GetUser function that is in service and when I call the function CallService I go to the BreakPoint of Service (which means it works!).
Service function works great and returns the correct data, but to Jquery I get the Error function with status 0.
In addition, in the console I see a red error:(Not generally understood as an error)
POST http://localhost:xxx/Service1.svc/GetUser
What could be the problem?
It could be that you're making a cross-domain request. Note that the same host name with different ports are considered different domain. For example: http://localhost:20 and http://localhost:40 are considered different domains.
In your case, it could be that your browser supports CORS and therefore requests to a different domain are still sent. That's why when you debug on server side you see it works, but when the browser receives response from the server, the response is discarded and an error is raised because of missing Access-Control-Allow-Origin header from the response or having the Access-Control-Allow-Origin header but with a value different than your domain.
My problem was that in User object I had DateTime.
When I turned it to String it worked.

Rails: Get remote page via ajax

I use Rails3 and I try to get remote page via ajax. (https://play.google.com/store/apps/details?id=).
$.ajax({
url: app_url,
type: 'GET',
data: "id=<id>",
crossDomain : true,
dataType: 'jsonp',
success: function ( code ) {
alert("Good.");
}
});
When I run the script, the I see: "Uncaught SyntaxError: Unexpected token < " error message.
By the way, I tried do it as:
$.ajax({
url: app_url,
type: 'GET',
data: "id=<id>",
crossDomain : true,
dataType: 'jsonp',
success: function ( code ) {
alert("Good.");
}
});
But I see "Origin http://example.com:3000 is not allowed by Access-Control-Allow-Origin." error message.
How can I fix the error and get the page ?
Thanks.
If you are trying to access remote pages via AJAX, that page may be blocking your request. The error message would suggest this: https://developer.mozilla.org/en-US/docs/HTTP_access_control
EDIT
For clarity, Access-Control-Allow-Origin is the server setting which "origins" are allowed to retrieve from it. You could possibly grab this page server-side, and depending on google's level of security, you may have to spoof a browser. PHP CURL comes to mind. You would then set up an ajax call to your server script, your server would go get the page for you, then return it to you ajax call.

Categories

Resources