How to resolve uncaught syntax error in jsonp - c#

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',

Related

.Net Core ValidateAntiForgeryToken throwing web api 400 error

Visual Studio 2017 with Web Api using .net Core 1.1 I'm using, but I am getting a 400 Bad Request Error.
Error Occurs in every way:
Angular http
Fiddler
Postman
SoapUI
Swagger
ASP.NET Web API “400 Bad Request” on POST Request
[HttpPut]
//[ValidateAntiForgeryToken]
public IActionResult Put([FromBody]VeteranInteraction sessionTracker)
{ //.... }
Why is this happening ?
ValidateAntiForgeryToken is the problem , if I comment it out it works.
You must send the AntiForgery token on every request
var arr = { City: 'Tehran', Age: 25 };
$.ajax({
url: "#Url.Action("SaveAccess", "Access")",
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
beforeSend: function (request) {
request.setRequestHeader("RequestVerificationToken", $("[name='__RequestVerificationToken']").val());
},
success: function (msg) {
alert(msg);
}
});
You need to send the AntiForgery token on every request where it's being validated either as a cookie or as a http header.
Refer to the documentation here. They have a section on how to configure angular js to do it.

ajax post call return 200 but handle error [duplicate]

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");
}

How to view soap service data from my browser

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

AJAX requests from jquery in android application to WCF Service always fails

I have an application where I fetch a list of requests made by the user based on the idNo provided. The android application uses AJAX to make a request to a .NET WCF Service which in turn returns a IEnumerable of DTO for that request.
Following is the AJAX Code:
$.ajax({
url: baseURL + "RequestStatusList/"+idNo,
cache : false,
type : "GET",
dataType : "json",
contentType : "application/json; charset=utf-8",
crossdomain : true,
success : function(data, tst, xhr) {
//do something here
},
error: function (xhr, tst, err) {
alert(' Please Try Again ' + xhr.status);
}
});
A similar piece of code works in another page in the application, where only the process in success is different, rest all is same.
Here every time the request fails and enters the error section and displays undefined/0 as error. No details about error, hence i cannot get what maybe the problem.
When I debug the server side code I get proper value in the parameter passed and a IEnumerable is formed and returned. What fails is the client side code after successful execution of server code.
Please Help.
Thanks in advance.

JQuery Ajax Getting Response, but Always invoking Error function JSONP

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

Categories

Resources