I have a HttpListenerContext class, that always listen to port 13001. when ever an ajax call comes I am passing data as follows
context.Response.Close(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("jsonp({'Status':'Good'})")), false);
Next I am invoking that Server by using Jquery ajax as follows
$.ajax({
url: "http://localhost:<13001>/hit/number',
type: "GET",
async: false,
contentType: "application/json",
dataType: "jsonp",
jsonp: "jsonp",
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error");
}
});
Ajax Get Request getting Success, I am able to see the response in Chrome Network->Response Tab as follows
"jsonp({"Status":"Good"})"
But I can't get this message in Ajax Success function. It's always displaying error. Can any one please tell me where I did mistake.
Response Headers
Access-Control-Allow-Origin:*
Cache-Control:private
Content-Length:23
Content-Type:application/javascript
Date:Fri, 27 Sep 2013 01:12:25 GMT
Server:Microsoft-HTTPAPI/2.0
My gut tells me that you are not passing back a full HttpResponse. You are just passing back a text string. Since it isn't a valid HttpResponse jQuery is going to think it failed.
Solution: try adding context.Response.StatusCode = 200; this before you send the response. You might need to add a content-type as well to the response.
context.Response.StatusCode = 200;
context.Response.Close(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("jsonp({'Status':'Good'})")), false);
Same issue I have faced with oData service, its fixed by by adding the "$callback" keyword by end of the url.
So the ajax URL will be like
https://example.com/ApplicationData.svc/Products?$format=json&$callback=?
courtesy :http://www.kendoui.com/blogs/teamblog/posts/11-08-24/cross-domain_queries_to_odata_services_with_jquery.aspx
Related
I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}
I have the following basic code. I tried to debug this code but the javascript is very painful to debug, and I do not know where it is failing:
jQuery.support.cors = true;
var packet = {
Image: imageAsString,
PhnType: phoneType,
PhnMdl: phoneManufacturer
};
$.ajax({
url: "https://molecheckerservices2.azurewebsites.net/api/Testing/SubmitTestingData",
type: "POST",
dataType: "json",
data: JSON.stringify({ packet }),
success: function(data, textStatus, xhr) {
alert('yes');
window.localStorage.setItem("dataObject", JSON.stringify(data));
window.location = "results.html";
},
error: function (xhr, textStatus, errorThrown) {
alert('no');
window.localStorage.setItem("dataObject", JSON.stringify([.33, .33, .33]));
window.location = "results.html";
}
it gives me back an alert no, which corresponds with a failure. Additionally as I debug I see in my Javascript console that the error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
Pops up. I tried to look up what this mean but I would be incredibly grateful for any problem specific advice!
Open up Fiddler and manually POST to your endpoint. If you do that, you will see the same error message I saw:
{"message":"No API version was specified in the request, this request needs to specify a ZUMO-API-VERSION of '2.0.0'. For more information and supported clients see: http://go.microsoft.com/fwlink/?LinkId=690568#2.0.0"}
It has a handy-dandy link in there for you. Also, here is a SO answer that possibly applies to you.
I did add the header mentioned above, resent the request and I received that sweet 200 response from your service, so I'm pretty sure that's your issue.
P.S. If you don't want random strangers inserting data into your app like I just did, you should secure your service or at least obfuscate the URL when mentioning it in public.
I'm completely new to how soap services work, please correct me if my understanding is wrong. I would like to pass parameters and call a function from a soap service by typing in a url on my browser (Chrome) and then would like to see the results. I tried searching and following the information from here, but I'm not sure what I'm doing wrong. I have tried the following variations:
http://<servername>/apppath/MyService.asmx?op=GetData?loc=01&status=OPEN
http://<servername>/apppath/MyService.asmx/GetData?loc=01&status=OPEN
This is what I get when I go to the url.
http:/<servername>/apppath/MyService.asmx?op=GetData?
Please help.
Maybe you are requesting wrong urls? If you have .asmx in your application - you should be able to see the description page on the url
http://{servername}/{apppath}/MyService.asmx
Of course you should replace {servername} the {apppath} with your values.
You have to send an HTTP POST request in order to call your web service GetData.
Your JS code should be something like:
//url should be MyService.asmx/GetData
function callWS(url) {
var loc = "01";
var status = "OPEN";
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "webmethods.aspx/UpdatePage",
data: JSON.stringify({ loc: loc, status: status }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(response) { alert(response); }
};
$.ajax(options);
}
So the error was my understanding of SOAP and host to use Postman. In short, I wasn't able to accomplish a SOAP request through the browser. Also, the picture supplied, it showed I was missing 2 things. 1) The SoapAction 2) The parameters were not supplied in the url but rather in the <soap:Body> tag. These were supplied in the POST and I was able to view my results in Postman
I am accessing a cross domain api using jquery ajax but I can't achieve it . Iam getting error as "uncaught syntaxerror : unexpected token <" in the console, How to fix this.
Code:
$.ajax({
url: "http://..............",
type:"GET",
dataType: 'jsonp',
crossDomain: true,
contentType:"application/javascript",
success: function (data) {
alert(data);
},
error: function (errorMEssage, Errtext) {
alert(Errtext);
}
});
Error:
uncaught syntaxerror : unexpected token <
You cannot make cross domain AJAX calls using JSONP to a server that returns XML. If you want to be able to make a cross domain AJAX call you have 2 possibilities:
use JSONP -> your server needs to support it.
use CORS -> your server AND client browser need t support it.
If your server supports CORS your request may look like this:
$.ajax({
url: "http://..............",
type:"GET",
crossDomain: true,
success: function (data) {
alert(data);
},
error: function (errorMEssage, Errtext) {
alert(Errtext);
}
});
change the dataType to xml
dataType: 'xml',
I have code like this:
$.ajax({
cache: false,
url: "/xx"
}).done(onAjaxDone).fail(function (jqXHR, textStatus, errorThrown) {
Dialog.Alerts.ajaxOnFailure(jqXHR, textStatus, errorThrown);
});
and
$.ajax({
cache: false,
url: "/xxxxx"
}).done(onAjaxDone).fail(function (jqXHR, textStatus, errorThrown) {
Dialog.Alerts.ajaxOnFailure(jqXHR, textStatus, errorThrown);
});
When I check with fiddler I notice more than one ajax call. Is there some way I can add some meta to the ajax calls that would not be used but that would allow me to see where the call is coming from in my code. Something like a comment that I could place within the ajax() and that would be visible going across the network?
You could send some meta-data in a non-standard header, using the headers option:
$.ajax({
//...
headers: { MyCustomHeader: "Location #1" }
});
Then check for it on the server side using Request.Headers["MyCustomHeader"].
You could also append a key to the query string, but I suppose using an HTTP header is less invasive.