I've read through thread after thread on here and elsewhere trying to get a cross domain ajax call to work. I have a Restful WCF service that returns a simple bool. I have it setup with the proper response format (Json) and the expected url with the callback parameter:
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "ShowCreditCardTextJQUERY?memberNumber={memberNumber}&callback={callback}",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
My Ajax looks like this:
$.ajax({
url: "http://example.com/service/service.svc/ShowTextJQUERY",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
crossDomain:true,
data: "{'memberNumber':'" + memberNumber + "'}",
cache: false,
//success: alert(memberNumber),
success: function (data) {
var output = data;
if (!data) {
$("#dialog").dialog(
{
modal: true,
width: 735,
height: 550
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
I receive a 200 for the response but that is coming in the error block. I am at a loss (and still pretty new to jquery/ajax). Any help would be greatly appreciated.
May be these lines of code solve your problem, which is for regular web service call
var jsonData = [YOUR JSON PARAMETER];
$.ajax({
async: false,
type: "POST",
url: [YOUR WEB SERVICE URL],
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ json: jsonData }),
dataType: "json",
success: OnSuccess,
failure: function(err) {
alert("Error : " + err.d);
}
});
function OnSuccess(data) {
alert("Success:" + data.d);
}
You can do one thing for that just need to set Access-Control-Allow-Origin & Access-Control-Allow-Headers in CustomeHeaders your web service web.config file.
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
If you want to allow only for specific domain , you can do that with specific value of domain instead of * value
Related
I have a js when i do a ajax call to one server. When i call to this service using localhost, works. But when i call to this service using the server where i upload it, its ERROR 500. The call return a json.
$.ajax({
url: "https://www.example.com/example",
dataType: "json",
data: {
'data': xml,
'message': message,
'customer_id': customer_id,
'subscr_id': subscr_id
},
type: 'POST',
success: function (devol) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert("no ha entrado");
}
});
Try to update your code below:
var model = {
'data': xml,
'message': message,
'customer_id': customer_id,
'subscr_id': subscr_id
};
$.ajax({
url: "https://www.example.com/example",
type: 'POST',
dataType: 'json',
data: JSON.stringify(model),
//headers: { 'authorization': `Bearer ${token}` },
async: false,
processData: false,
contentType: "application/json",
error: function (err) {
},
success: function (data) {
}
});
It might be because of CORS (Cross-Origin Resource Sharing)... Usually, you cannot make calls to other domains from the browser unless the other domain you are making calls allows CORS to all sites or specific sites.
enter link description here
I have a web form IndexPage.aspx. The script part of this front end code is calling a code-behind function using ajax call.Here's the code:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~//IndexPage.aspx//SaveXml")%>',
data: JSON.stringify(logic),
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: true,
//cache: false,
success: function (msg) {
alert("AJAX received : " + msg.d);
},
error: function (msg) {
alert("Failed : " + msg.d);
}
});
The "Failed" alert box is shown with return value 'undefined' after I run the code.
The code behind function is:
public static string SaveXml(string logic)
{
return logic;
}
This code-behind function is not getting called. The breakpoint which I have set at the code-behind function is not getting hit. I have tried almost all solutions from stack overflow. Please see if anythig is wrong in this code.
Thanks friends,
The issue was resolved. Checking browser console and network helped me a lot to solve the error.
I did two changes
1) Added [System.Web.Services.WebMethod] to code-behind function
2) Changed my => data: JSON.stringify(logic) ..... to ....=> data: '{ logic:\''+ logic +'\'}'
I did the second change after referring to this link: "Invalid JSON primitive" in Ajax processing
While sending just a string you need to add escape sequence.
Resolved
Ajax call:
$.ajax({
type: "POST",
url: '<%=Page.ResolveUrl("~/WebForm1.aspx/SaveXml")%>',
data: JSON.stringify({ "logic": "logic value" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: true,
//cache: false,
success: function (msg) {
alert("AJAX received : " + msg.d);
},
error: function (msg) {
alert("Failed : " + msg.d);
}
});
Web Method
[WebMethod]
public static void SaveXml(string logic) {
}
Web.config
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
I have hosted a service sucessfully on IIS.
Made sure that application is running.
I have given call to this service through ajax as:
var parameters = {
'EmailID':EmailID,
'Password':Password
};
$.ajax({
url: "http://localhost:85/MobileECommerceTesting/Service1.svc/validateLogin",
data: JSON.stringify(parameters),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
cache: false,
success: function (Data) {
alert("asdsad");
},
error: function () {
alert("Error in Saving.Please try later.");
}
});
But its not giving call to the service.
What can be the problem?
EDIT:
EDIT2 :
Network Tab:
Take a look at this question:
the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'
It might be related to your binding, which does not expect the content type application/json. You must use webHttpBinding to create "REST-like" services with WCF.
I'm trying to get some information from a different domain, the domain allows only jsonp call - others get rejected. How can I get the content instead of execution? Because I get an error in response. I don't need to execute it, I just need it in my script. In any format (the response is json but js doesn't understand it).
I can't affect on that domain so it's impossible to change something on that side.
Here's my code:
$.ajax({
url: url + '?callback=?',
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
window.jsonpCallback = function(response) {
console.log('callback success');
};
There are a few issues with your $.ajax call.
$.ajax({
url: url + '?callback=?',
// this is not needed for JSONP. What this does, is force a local
// AJAX call to accessed as if it were cross domain
crossDomain: true,
// JSONP can only be GET
type: "POST",
data: {key: key},
// contentType is for the request body, it is incorrect here
contentType: "application/json; charset=utf-8;",
// This does not work with JSONP, nor should you be using it anyway.
// It will lock up the browser
async: false,
dataType: 'jsonp',
// This changes the parameter that jQuery will add to the URL
jsonp: 'callback',
// This overrides the callback value that jQuery will add to the URL
// useful to help with caching
// or if the URL has a hard-coded callback (you need to set jsonp: false)
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You should be calling your url like this:
$.ajax({
url: url,
data: {key: key},
dataType: 'jsonp',
success: function(response) {
console.log('callback success');
},
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
JSONP is not JSON. JSONP is actually just adding a script tag to your <head>. The response needs to be a JavaScript file containing a function call with the JSON data as a parameter.
JSONP is something the server needs to support. If the server doesn't respond correctly, you can't use JSONP.
Please read the docs: http://api.jquery.com/jquery.ajax/
var url = "https://status.github.com/api/status.json?callback=apiStatus";
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'apiStatus',
success: function (response) {
console.log('callback success: ', response);
},
error: function (xhr, status, error) {
console.log(status + '; ' + error);
}
});
Try this code.
Also try calling this url directly in ur browser and see what it exactly returns, by this way You can understand better what actually happens :).
The jsonpCallback parameter is used for specifying the name of the function in the JSONP response, not the name of the function in your code. You can likely remove this; jQuery will handle this automatically on your behalf.
Instead, you're looking for the success parameter (to retrieve the response data). For example:
$.ajax({
url: url,
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
success: function(data){
console.log('callback success');
console.log(data);
}
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You can also likely remove the other JSONP-releated parameters, which were set to jQuery defaults. See jQuery.ajax for more information.
I need to get xml document from a server, then client signs it and sends back to server.
At server side I have web method which saves document:
[WebMethod]
public static void SaveSignedDocument(string SignedData)
{
SignedCms signedCms = new SignedCms();
....
}
Then, I get document from a server and after success receive it I make client to sign it and send back. Here is Javascript
// get xml to sign
$.ajax({
type: "POST",
url: "Default.aspx/GetXMLReceipt",
data: "{'ITN': " + ITN + " }",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (xml) {
// xml file was got
var xmlString = xmlToString(xmlData);
// Sign data
var SignedData = SignData(xmlString);
// Send it to server
$.ajax({
url: 'Default.aspx/SaveSignedDocument',
data: "{ 'SignedData': '" + SignedData + "' }",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){
alert('Document was successfully sent!');
}
error: function (data, status, jqXHR) {
alert('Send signed data failed - ' + jqXHR);
}
});
},
error: function (data, status, jqXHR) {
alert('Get data failed - ' + jqXHR);
}
});
The problem is that none of the alert at second requests ever fire. If I change request to synchronous everything is ok but why it does not work like written above? The server receives nothing and if we look to network traffic I see that request was interrupted. Why?
Encode your data properly, do not use any string concatenations. Here's the correct way:
data: JSON.stringify({ ITN: ITN }),
and on your second AJAX request:
data: JSON.stringify({ SignedData: SignedData })
The JSON.stringify method will ensure that you are sending valid JSON to your server by properly encoding the argument.