response error from ajax http post crossdomain request with json - javascript

I am using asp.net and on client side in javascript and I try to make an ajax HTTP request:
$.ajax({
type: 'POST',
url: url,
crossDomain: true,
data: trip,
dataType: 'json',
success: function (responseData, textStatus) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
on the other side i have an azurecloud project and this method (c#):
[ActionName("test")]
[HttpPost]
public IHttpActionResult Test([FromBody] SetTripRequestEntity trip)
{
return Ok("year it works!");
}
If I run the code, the server jumps into the c# method and the trip has the correct object, so everything is fine.
But after he returns Ok("year it works!"); on the javascript side he runs into the error function:
responseData is an object with nulls and 0 parameters,
textStatus is "error" (really only "error" not more)
errorThrown is ""
I don't understand why he does not go to the success function.
I have tried to make the request in fiddler2 and there I got the right answer.
So the problem is at the javascript (ajax) side.
does somebody know how to run it?
Thanks a lot!

Related

jQuery ajax error but the server is responding fine

I am trying to make request to server using jQuery ajax() but onResponse error block is being executed . The server response is working fine when the request is done from any other resources. This is my ajax:
$.ajax({
type:'post',
url: url,
data:{adminname: admin.ADMIN_NAME, adminID: admin.ADMIN_ID, modulename: moduleName },
dataType:'json',
success:function(data){
alert("hello world");
},
error:function(xhr, status, error) {
//when the response is returned this is being displayed
alert("error");
}
});
The request is being sent and even the data is being is updated but when the response is returned error block is being executed. There no errors on the server side. Where am I going wrong?

$.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.

jQuery invalid label jsonp

I use jQuery to get php-script result with ajax-function. Problem is php-script is on the another domain, so I should use "jsonp" as returned dataType, BUT php-script returns json, not jsonp (maybe script is not correct) and I get syntax error. How can I handle it? I suppose, that I can somehow get json string before ajax-function handles it and rises error, is it possible?
This is my ajax function:
$.ajax(
{
type: "POST",
dataType: "jsonp",
url: "http://www.pecom.ru/bitrix/components/pecom/calc/ajax.php",
data: res,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.status);
},
success: function (data) {
alert("Data Loaded: " + data)
}
}
)
Thank you!
The short answer is that you can't.
The longer one is that you have to set up some sort of proxying: make the request on the server side from a machine you control, transform the results to proper JSONP there, and connect to that server via AJAX.
(Or, in the very unlikely event that the target server supports CORS, you can use that instead of JSONP.)

How do i read simple json result with jquery and how to post new

I built a WCF service which produces JSON. I want to make an external website which uses this webservice. For now I am executing the WCF service over LAN by IIS, so I can connect to the service by going to http://myownaddress/blabla.svc/
I tried to learn some json and to get some results from my service.
For example if I want to use this method:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/{id}")]
string JSONData(string id);
I'll go to http://myownaddress/blabla.svc/json/123
And as result I get:
{"JSONDataResult":"You requested product 123"}
Now I have tried to receive this result with the JQuery statement getJSON. But I don't see any results.
My question is how can I get this simple data?
And secondly how can I post data(with javascript) back on to the wcf service is it also possible with json?
-edit-:
I have now updated my code and put this into my document ready function which is located between the <head> <script> .... on my page:
$.getJSON(
'http://myownaddress/blabla.svc',
function(data)
{
alert(data.JSONDataResult);
});
But this won't give the alert with the result. It doesn't even give an alert.. Besides that, in the function I need to give a parameter of id, so for example 123 (look in text above) don't I need to put that in the function also?
To get data use getJSON():
$.getJSON(
'http://myownaddress/blabla.svc/',
function(data) {
alert(data.JSONDataResult);
}
);
To post data you can use this:
$.post('http://myownaddress/postservice.svc', function(data) {
$('.result').html(data);
});
or this (if you need more control):
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You can also use the ajax for getting the data instead of the getJSON method .
UPDATE:
try using ajax method as it gives you more control:
$.ajax({
type: 'GET',
url: "http://myownaddress/blabla.svc/json/123",
success: function(data){alert(data)},
dataType: "json",
complete: function(data){alert(data)},
error: function(jqXHR, textStatus, errorThrown){alert(errorThrown)}
});
Also, if you use firefox, check out firebug extension, it will help you greatly.
If you use chrome then use chrome developer tools.
In order for your to get the json data from a WCF service that is outside your website using Jquery you need to use JSONP.
You can perform the call as shown below:
$.ajax({
url: "http://myownaddress/blabla.svc/",
dataType: "jsonp",
type: "GET",
timeout: 10000,
data: null,
jsonpCallback: "MyCallback",
success: function (data, textStatus, jqXHR) {
alert(action.toLowerCase());
},
error: function (jqXHR, textStatus, errorThrown) {alert('error is:' + errorThrown);
},
complete: function (jqXHR, textStatus) {alert('complete');
}
});
JSONP is used when you want to perform a cross domain calls using Javascript.
Also your WCF service should be compatible to handle JSONP calls by injecting the results to the response stream using the callBack method specified in the URL.
Do you have your code like this ?
$.getJSON(
'http://myownaddress/blabla.svc/',
function(result) {
alert(result.JSONDataResult);
}
);
Remember getJSON will not immediately return you the data, you have to make use of the result in a callback function.
Why did you change your url?
$.getJSON(
'h t t p://myownaddress/blabla.svc' ==> 'h t t p://myownaddress/blabla.svc/123',
function(data)
{
alert(data.JSONDataResult);
});

jQuery.ajax() sends POST requests as GET in a Chrome extension

I'm building a small Chrome extension that must send messages through a POST http request to a server in my company network, and I'm using jQuery 1.4.1 to speed up the development of the javascript part.
I have this code to send the request:
function send() {
$.ajax({
url: "http://mycompany.com/update",
method: "POST",
data: {status: "sometest", in_reply_to_status_id: "anId"},
success: function(data, textStatus) {
console.log("success");
console.log(data);
console.log(textStatus);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("error");
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
},
complete: function(XMLHttpRequest, textStatus) {
console.log("complete");
}
});
}
The request done this way fails, in the Chrome log I see that the server responds with a http status 400 and with the text "This methods requires POST".
If I change to code above with this:
function send() {
$.post("http://sunshine.emerasoft.com/statusnet/api/statuses/update.xml", {status: "sometext", in_reply_to_status_id: "anId"}, function(data) {
console.log(data)
});
}
everything works fine, the http status is 200 and server side I can see that the data I sent is correctly saved.
I need to use the full $.ajax() method because I need to do some work in case of success or failure, and some other when the request is complete, so $.post() is not enough.
Am I doing something wrong calling $.ajax(), or there is an issue of some kind, maybe because I am in the xontext of a Chrome extension?
Thanks
I believe the $.ajax() function takes a 'type' option, not a 'method' option.
The default type is GET.

Categories

Resources