I would like to call an external page (which I can control) from another domain (which I cannot control). Below is the script I use to call, but the page is not being called.
$(function () {
var val = window.location.hostname;
alert(val);
$.ajax({
type: "GET",
async: false,
crossDomain: true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "http://somedomain.com/validate.aspx/validfunction",
data: "{domain: '" + val + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
console.log(jqXHR, textStatus, errorThrown);
}
});
});
No idea, why I cannot call. Is there any better way to call the page. Please advice.
Use XMLHttpRequest object to make a request like below
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET",URL,true);
xmlhttp.send();
The request is obviously GET and 'URL' is the url you want to execute/open. The 3rd parameter is for async request, it can be either true or false.
Create a div element for eg: with id - result and append the result received in #result element, you can simply use this in the next line:
document.getElementById("result").innerHTML = xmlhttp.responseText;
contentType is set to "application/json; charset=utf-8" though value of data option, for example
"{domain: '1'}"
is not valid JSON. Property names should be surrounded by double quotes.
Create a javascript plain object, populate with properties, values, then pass javascipt plain object to JSON.stringify(), set data as valid JSON result.
See $.ajax([settings])
contentType (default: 'application/x-www-form-urlencoded;=UTF-8'`)
Type: Boolean or String
When sending data to the server, use this content type. Default is
"application/x-www-form-urlencoded; charset=UTF-8", which is fine for
most cases. If you explicitly pass in a content-type to $.ajax(), then
it is always sent to the server (even if no data is sent). As of
jQuery 1.6 you can pass false to tell jQuery to not set any content
type header. Note: The W3C XMLHttpRequest specification dictates that
the charset is always UTF-8; specifying another charset will not force
the browser to change the encoding. Note: For cross-domain requests,
setting the content type to anything other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain
will trigger the browser to send a preflight OPTIONS request to the
server
$(function () {
var val = window.location.hostname;
alert(val);
var data = JSON.stringify({"domain": val});
$.ajax({
type: "GET",
async: false,
crossDomain: true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "http://somedomain.com/validate.aspx/validfunction",
data: data,
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
console.log(jqXHR, textStatus, errorThrown);
}
});
});
You can alternatively try to use $.getJSON() both with and without "?callback=?" appended to URL.
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.
var val = window.location.hostname;
var data = JSON.stringify({"domain": val});
$.getJSON("http://somedomain.com/validate.aspx/validfunction?callback=?", data)
.then(function(data) {
// do stuff with `data`
})
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
});
Whenever we request web-method from ajax method, it should be type 'POST' and for cross domain the datatype is 'JSONP'. The web method should return data as in JSON format.
$.ajax({
type: "POST",
async: false,
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
url: "http://somedomain.com/validate.aspx/validfunction",
data: "{domain: '" + val + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
console.log(jqXHR, textStatus, errorThrown);
}
});
Related
I'm making a cross domain ajax call. When I heat the link directly from my browser, I get the json strin as follows:
But when I'm making an ajax call to this same URL, I'm not getting the json in my response. My ajax request is as follows:
$.ajax({
url: "http://172.16.201.14:801/api/apiclearing?trackNo=" + $scope.BillClearingModel.BillTrackingNo + "&&tokenNo=~Ice321",
dataType: 'jsonp',
success: function(response) {
console.log(response);
alert("Success");
},
error: function(response) {
console.log(response);
alert("Failed");
}
});
What Im getting in console is as follows:
Full Object is as follows:
What I'm missing here? Thanks.
Would you mind trying this:
var datastring = { "trackNo" : "160822000037" };//try this
//var datastring = "trackNo=160822000037"; //or this
$.ajax({
type: 'POST',//you may try the GET type
url: "https://172.16.201.14:801/api/apiclearing",
dataType: 'json',// try jsonp as well
data: datastring,
contentType: 'application/json',
crossDomain: true, //newly added
success: function(data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(JSON.stringify(data));//to string
alert("Success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Status:"+ textStatus + " Error:" + errorThrown);
}
You may consider as well to add Access-Control-Allow-Origin to your server like Access-Control-Allow-Origin: http://yourdomain-you-are-connecting-from.com in php
With Chrome REST service I do this: a post to a certain url, I send a json string in the body, I set the content type as application/json and when I execute the post I get the proper answer.
I am trying to do the same post with jquery.
I first try with:
var beacon = {"beaconid.minor":2,"beaconid.UUID":"beaconnr","beaconid.major":1};
$.ajax({
type: "post",
data: JSON.stringify(beacon),
contentType: "application/json",
dataType: "jsonp",
crossDomain: true,
url: "myurl"}).done(function() {
alert("success");
}).fail(function()
{
alert("error");
});
by I seem to get no answer, I don't get the success alert nor the error alert.
I have then tried with:
var jqxhr = $.post( "myurl", {"beaconid.minor":2,"beaconid.UUID":"beaconnr","beaconid.major":1}).done(function(data, textStatus, jqXHR)
{
}).fail(function(jqXHR, textStatus, errorThrown)
{
alert(textStatus);
});
At least now I get an alert with the textStatus as an error. It is something...but not enough. I could I do a successful post?
The issue is you're setting dataType: "jsonp" for a POST request. JSONP doesn't support POST requests, only GET requests.
I suggest changing to dataType: "json" to see if the service supports CORS. If it doesn't then you'll have to do something like proxy the request through the local server, to get around CORS.
You should not be sending "post" as "type", rather as "method"
And like pointed above, the data type should be json and not jsonp.
$.ajax({
method: "post",
data: JSON.stringify(beacon),
contentType: "application/json",
dataType: "json",
url: "myurl"}).done(function(response) {
alert("success");
//if in chrome
//console.log(response);
}).fail(function(error)
{
//if using Chrome
//console.log(error);
alert(error);
});
While calling MVC webservice from my html page it was always going to error; please help me
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (msg) {
alert(Response.ErrorMessage )
},
error: function (e, status) {
alert(e + " Fail " + status)
}
});
You have to setup CORS (http://www.html5rocks.com/en/tutorials/cors/) or use JSONP. If you decide to use JSONP then you have to send proper callback function name with JSON data.
I am unable to catch response from C# to jQuery using $.ajax. I get an error "SCRIPT ERROR". How can I catch response using JSONP? This is what i am using:
$.ajax({
async: true,
context: mrq,
cache: false,
type: "GET",
url: MYURL,
crossDomain: true,
dataType: 'jsonp',
data: MYDATA,
processData: false,
jsonp: "jsonREQ",
jsonpCallback: "onJSONPsuccess",
success: function (jsonText, textStatus) {}
});
As far as I understand, dataType: 'jsonp' means that as soon as it's returned it's put into the callback function as an argument. So, I'd try this:
onJSONPsuccess = function(response) {
// do something with response, e.g.
results = response["results"]
}
$.ajax({
crossDomain: true,
dataType: 'jsonp',
data: { /*params you're sending in*/ },
jsonp: "jsonREQ",
jsonpCallback: "onJSONPsuccess",
success: onJSONPsuccess
});
You say the server side is C# - are you using WCF? There's a great article here about it:
http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/
Basically you need to set up WCF (or whatever server-side code you're using) to return the json wrapped in a call to your callback function.
However, with jquery, you can simply add "?Callback=?" to your URL, change the dataType to 'jsonp', and forget about the rest of that stuff. You don't need the jsonp or jsonpCallback options set.
In contrast to a json request, the jsonp request will return your data not wrapped in a 'd' property, so your call back function is:
function(data) { var a = data.myProperty ... }
rather than
function(data) { var a = data.d.myProperty ... }
and the whole method is along the lines of:
var url = configuration.serviceUrl + "/" + method + "?callback=?";
var options = {
type: 'GET',
url: url,
data: args,
dataType: "jsonp",
contentType: "application/json",
success: function(data) {
if (callback != null) callback(data);
}
};
if (typeof errorCallback != 'undefined')
options.error = errorCallback;
$.ajax(options);
I have a php script, which return serialized in php data. And I try to receive this data by using $.ajax() method from jQuery 1.7. Here is the example.
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res) {
alert('COMPLETE() done');
console.log(res);
}
});
In console I see only
Object { readyState=0, status=0, statusText="error"}
So, what I do wrong? Could you help me please?
UPD
Interesting notice: if I use JSONP dataType request can receive data, but can't process it.
Here is an example.
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
dataType: 'jsonp',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Instead of complete: use success: then res will be the returned data from your ajax request.
Remember to use error: as well incase there is an error with you call, as it seems that there might be in your console output.
Code:
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Your code is probably fine, but you're trying to violate the same origin policy. Basically, if your site is http://aaa.com/, you cannot make AJAX called to http://bbb.com/.
There are a few ways around it:
Getting around same origin policy in javascript without server side scripts
But most of them require that both sides play nice.
The response is the second parameter of complete function:
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res,response) {
alert('COMPLETE() done');
console.log(response);
}
});
More info: http://api.jquery.com/jQuery.ajax/
You should also consider using JSON, not php serialized data