I am getting a javascript error on firefox 3.5, when trying to call an ajax method.
Please find the error below:
XML Parsing Error: no element found Location: moz-nullprincipal:{1a2c8133-f48f-4707-90f3-1a2b2f2d62e2} Line Number 1, Column 1:
^
this is my javascript function:
function Update(Id) {
$.ajax({
type: "GET",
url: ROOT_URL + "/sevice/udates.svc/Update?Id=" + Id,
success: function(response) {
},
async: false
});
}
I fixed the problem by setting mimeType to "text/html"
The ajax call expects XML back (perhaps due to bad guessing) and tries to parse it and fails if nothing is returned or it is not valid XML..
Use the dataType option to specify the format of the response.
From the comments it looks like some browsers cannot handle an no-content response. So, a workaround for such cases might be to return something from your service (even a single space).
I've come across an alternative cause of this - might help someone.
If you make a $.ajax request (in my case a PUT request) that returns a 200 header but no body content I've seen this same XML Parsing error message occur - even when the dataType is set to json.
(At least) two solutions work:
Make all API PUT requests return some content, or
Return a 204 'No Content' header instead (what I ended up doing)
It's a known FireFox bug.
https://bugzilla.mozilla.org/show_bug.cgi?id=547718
to quick fix this , you maybe can return an response with html structure(but no content).
async is also part of options. Also specify the dataType as xml
function Update(Id) {
$.ajax({
type: "GET",
async: false,
dataType: "XML",
url: ROOT_URL + "/sevice/udates.svc/Update?Id=" + Id,
success: function(response) {
}
});
}
You need to send html document to the output (the output udates.svc in your case) . If you use ASP.NET, you could do the following:
Response.Clear();
Response.Write("<html xmlns=”http://www.w3.org/1999/xhtml”>");
Response.Write("<head><title></title></head>");
Response.Write("<body>");
Response.Write("your output");
Response.Write("</body>");
Response.Write("</html>");
Response.ContentType = "text/HTML";
Response.End();
Related
I have a web service that expects POST requests carrying a JSON string in the body. I'm trying to use this web service using jQuery, but I have two problems :
1) jQuery seems to always use the GET method, no matter what I do ;
2) jQuery seems to append weird things into the URL.
The relevant pice of my code :
var WEB_SERVICE_URL = 'http://localhost/XXXX/';
// ...
$.post({
url: WEB_SERVICE_URL + 'GetConfigLabels/',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
data: JSON.stringify(data),
processData: false,
success: function(response) {
// Whatever
},
error: function(xhr, message) {
// Whatever
}
});
The developper tools of the browser (Firefox Quantum 60.0.2) shows me a weird URL :
http://localhost/XXXX/GetConfigLabels/?callback=jQuery331012146934861340841_1530707758905&{}&_=1530707758906
While the following was expected :
http://localhost/XXXX/GetConfigLabels/
Also the HTML file is openned as a file (using file:///) through the file system, hence the use of JSONP for cross domain.
I failed to find existing questions related to this issue. What could be causing this ? Thank you !
Please refer to the dataType : json section at http://api.jquery.com/jquery.ajax/ :
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests that have a callback placeholder,
e.g. ?callback=?, are performed using JSONP unless the request
includes jsonp: false in its request options. The JSON data is parsed
in a strict manner; any malformed JSON is rejected and a parse error
is thrown. As of jQuery 1.9, an empty response is also rejected; the
server should return a response of null or {} instead. (See json.org
for more information on proper JSON format
overrding random name of callback using jsonpCallback :
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.
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");
}
When I first load a page I make an ajax call to bring some data for the client-side. The call is made to a different domain and the answer comes as JSONP. The call looks similar to:
$.ajax({
type: "GET",
url: url + "?callback=?",
dataType: "jsonp",
contentType: "application/javascript;charset=UTF-8",
async: true,
success: successCallback,
error: errorCallback,
cache: true,
jsonpCallback: jsonCB
});
'application/javascript' would be the possible culprit here as I did my research on the subject but this is present in a previous version of the code which never had this problem.
On all browsers except IE I receive the following error (sometimes, usually the first time and then the problem dissappears) :
script5007 object not found - line 1, char 1
The JSONP received looks like that:
func({"result":"abc"})
The param of the func is a valid JSON as I checked this using jslint.
Any idea will be highly appreciated! Thank you!
You're missing the object brackets { } inside your $.ajax function. Modify it like so:
$.ajax({
url:'',
contentType: 'application/javascript;charset=UTF-8',
crossDomain:true
......
});
The jQuery $.ajax method either takes a url parameter and an optional parameter of additional options specified as an object, or an object parameter including the url.
I am using ckeditor to format some data inside my textarea
<textarea id="editorAbout" rows="70" cols="80" name="editorAbout"></textarea>
Now when i try to post this data using jQuery.ajax like this,
var about=escape( $("#editorAbout").text());
$.ajax({
type: "POST",
url: "../Allcammand.aspx?cmd=EditAboutCompany&about="+about,
type:"post",
async: false ,
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); }
});
I get the error
HTTP Error 414. The request URL is too long.
I am getting the error here: http://iranfairco.com/example/errorLongUrl.aspx
Try clicking on the Edit Text button at the bottom left of that page.
Why is this happening? How can I solve it?
According to this question the maximum practical length of a URL is 2000 characters. This isn't going to be able to hold a massive Wikipedia article like you're trying to send.
Instead of putting the data on the URL you should be putting it in the body of a POST request. You need to add a data value to the object you're passing to the ajax function call. Like this:
function editAbout(){
var about=escape( $("#editorAbout").text());
$.ajax({
url: "Allcammand.aspx?cmd=EditAboutCompany&idCompany="+getParam("idCompany"),
type:"post",
async: false,
data: {
about: about
},
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); ShowMessage("??? ?? ?????? ??????? ????","fail");}
});
}
For me, changing type:"get" to type:"post" worked, as get reveals all queries and hence make it bigger url.
Just change type from get to post.
This should help. :)
In my case, there was a run-time error just before the post call. Fixing it resolved the problem.
The run-time error was trying to read $('#example').val() where $('#example') element does not exist (i.e. undefined).
I'm sure this will, certainly, help someone.
In my case, the error was raised even though I was using 'POST' and the call to the server was successful. It turned to be that I was missing the dataType attribute...strange but now it works
return $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
})
A bit late to the party, but I got this 414, while using POST. It turned out is was a max path length in windows causing this error. I was uploading a file, and the actual request length was just fine (using post). But when trying to save the file, it exceeded the default 260 char limit in windows. This then resulted in the 414, which seems odd. I would just expect a 501. I would think 414 is about the request, and not the server handling.
With help from others I've gotten to the point where I can see the json return from foursquare but any attempts to call it yield an error.
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Try removing the "&callback=?" from the url. I think jQuery adds that for you if you set the dataType to jsonp.
EDIT:
from the jquery ajax documentation describing the dataType parameter:
"jsonp": Loads in a JSON block using
JSONP. Will add an extra "?callback=?"
to the end of your URL to specify the
callback.