jQuery AJAX response always returns nothing - ajax

The following code returns a blank response no matter whether or not the Function exists, or even the Web Service file entirely:
$.ajax({
url: "/ws.asmx/HelloWorld"
, type: "POST"
, contentType: 'application/json; charset=utf-8'
, data: '{ FileName: "' + filename + '" }'
, dataType: 'json'
, success: function (data) {
}
});
Why is this?
Also, might be worth noting, $.load() works fine!

Your error is that you try to construct JSON data manually and do this in the wrong way:
'{ FileName: "' + filename + '" }'
You should fix the code at least to the following
'{ "FileName": "' + filename + '" }'
because correspond to the JSON specification the property names must be also double quoted.
Next problem can you has if the filename has some special characters. For example, in case of
var filename = '"C:\\Program Files"'; // the '\' must be escaped in the string literal
you should has as the data the corresponding JSON string
'{ "FileName": "\\"C:\\\\Program Files\\"" }'
as the corresponding JSON data because of '\' and '"' must be escaped. It looks dificult. So I stricly recommend you to construct JSON strings with respect of JSON.stringify function from the json2.js. Then the code will be
$.ajax({
type: "POST",
url: "ws.asmx/HelloWorld",
data: JSON.stringify({ FileName: filename }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error Occured!" + " | " + XMLHttpRequest.responseText +
" | " + textStatus + " | " + errorThrown);
}
});
which is simple and clear enough. The next advantage of the usage JSON.stringify is that the most modern web browsers has native support of the function and the function work very quickly.
By the way in case of the usage of JSON.stringify you can easy call web service methd having very complex data structures (classes) as the parameters and not only strings.
UPDATED: One more remrk to reduce possible misunderstanding. It you later deceide to use HTTP GET instead of HTTP POST to call the web method you will have to change the data parameter from
JSON.stringify({ FileName: filename })
to
{ FileName: JSON.stringify(filename) }
UPDATED 2: You can download this Visual Studio 2010 project which I used to test all before I posted my answer. I included as "Web-3.5.config" the web.config for .NET 3.5. All different commented data values included in the default.htm work. If you want make tests with HTTP GET you should uncomment the section in web.config which allows HttpGet and use ScriptMethod having UseHttpGet = true. All the lines are included in the demo as comments.

just to try use:
$.getJSON("/ws.asmx/HelloWorld", function(data){
alert(data);
});
Check if you get the data back.

Use AJAX-Enabled Web Service

Make sure you have loaded the jquery.js file properly.

Does the service return a value? If not, it will just POST and not give you back anything, because there is no data to see...

If you want to watch for errors, you can add an error callback
$.ajax({
url: "/ws.asmx/HelloWorld"
, type: "POST"
, contentType: 'application/json; charset=utf-8'
, data: '{ FileName: "' + filename + '" }'
, dataType: 'json'
, success: function (data) {
}
, error: function (a, b, c) {
}
});
From jQuery:
error(jqXHR, textStatus, errorThrown)Function
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery
1.4.x, XMLHttpRequest) object, a string describing the type of error
that occurred and an optional
exception object, if one occurred.
Possible values for the second
argument (besides null) are "timeout",
"error", "abort", and "parsererror".
This is an Ajax Event. As of jQuery
1.5, the error setting can accept an array of functions. Each function will
be called in turn. Note: This handler
is not called for cross-domain script
and JSONP requests.

I read somewhere that the contentType header for POST must be:
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
and I use it blindly: it's always worked.
-- pete

Related

forge.request.ajax returns: "Invalid parameter not satisfying: url"

We have an ios application built with trigger.io. this application is using forge.request.ajax to send data to our servers. one of our requests occasionally throws an error and returns this:
{"message":"Invalid parameter not satisfying: url","type":"UNEXPECTED_FAILURE"}
since the input parameters are sent in json format I suspected that some characters inputted by users, could break the structure and cause this error. my code looks like this:
forge.request.ajax({
url: "someurl.php",
dataType: "json",
data:"some=data&and=some&more=data&which=is inputted by user",
success: function (data) {
},
error: function (error) {
forge.request.ajax({
url: "errorlog.php",
dataType: "json",
data:"data=" + encodeURIComponent(JSON.stringify(error)),
success: function (data) {
},
error: function (error) {
}
});
}
});
this code gives the above error half the time. and work on the other half. are there any limitations for input parameters in ajax request? since i can't edit objective-c code, i need a solution - preferably a filter- which ensures this function to work with whatever input is entered.
Using encodeURIComponent may help:
var data = "some=data&and=some&more=data&which=is inputted by user";
forge.request.ajax({
url: "someurl.php",
dataType: "json",
data: encodeURIComponent(data)
...
Passing request data as URL Parameters has more than it's share of gotchas though so it may also be worth taking a look at this StackOverflow question: When are you supposed to use escape instead of encodeURI / encodeURIComponent?

is there any difference between those AJAX methods?

I have two questions about jQuery AJAX.
1) Is there any difference between $.load() and $.ajax() used with type: 'GET'? They seem to do the same job.
2) This question is related to the code below. What happens, if I don't write the "type: GET" line at all? Does it mean the same thing?
$(document).ready(function() {
$('#update').click(function() {
$.ajax({
type: 'GET',
url: 'hello-ajax.html',
dataType: 'html',
success: function(html, textStatus) {
$('body').append(html);
},
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + ( errorThrown ? errorThrown :
391
xhr.status );
}
});
});
});
Is it any different from
$(document).ready(function() {
$('#update').click(function() {
$.ajax({
url: 'hello-ajax.html',
dataType: 'html',
success: function(html, textStatus) {
$('body').append(html);
},
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + ( errorThrown ? errorThrown :
391
xhr.status );
}
});
});
});
This is straight from jQuery Docs (http://api.jquery.com/load/)
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted. This is achieved with a special
syntax for the url parameter. If one or more space characters are
included in the string, the portion of the string following the first
space is assumed to be a jQuery selector that determines the content
to be loaded.
Since $.get() is simply the $.ajax() shorthand for "data: 'Get'", it would appear the only major difference is the ability to do the aforementioned (import partial sections of a document).
Edit: To answer your second question, GET is the default data type for the $.ajax() call, POST being your other option. You can read a bit about POST here (http://api.jquery.com/jQuery.post/)
Extracted from jQuery manual .load
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data. This means that most uses of the
method can be quite simple:
$( "#result" ).load( "ajax/test.html" );
If no element is matched by the selector — in this case, if the
document does not contain an element with id="result" — the Ajax
request will not be sent.
I guess the difference is that .load() function allows to target the result into a DOM element. Like so
$( "#target" ).load( "source.html" );
And the ajax() method returns an object (eg. JSON) that can be the manipulated. etc. apart from more attributes.

$(document).ready doesn't work however page is loaded

As you can understand my title, browser doesn't call the GetReleatedProducts method. I put breakpoint $(document).ready(function () line but it doesn't enter into ajax call.
I checked that I have jquery reference. Do you have any idea?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:2782/AjaxCallPage.aspx/GetReleatedProducts",
data: "{productId:" + productId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {...}
You've told the server you're sending it JSON:
contentType: "application/json; charset=utf-8",
...but what you're sending it:
data: "{productId:" + productId + "}",
...is not valid JSON. To be valid JSON, the key productId must be in double quotes:
data: '{"productId":' + productId + '}',
// ^ ^
(Here I'm assuming productId is a number. If it's a string, it will also need to be in double quotes.)
So I suspect the server side is rejecting the call because the JSON is invalid.
It's also a bit unusual to send JSON to the server, although it's perfectly valid if that server is coded to expect it and if you send it correctly. It's more typical to send data to the server using the default application/x-www-form-urlencoded.
So unless you've coded your server side to expect to receive JSON, remove the contentType option from your $.ajax call and change data to:
data: {productId: productId}
...which tells jQuery to do the encoding for you.

JSON returned AJAX post jQuery undefined

I am using jQuery to get a list of Names as JSON string -
`
$.ajax({ type: 'POST', url: "../Names.aspx", dataType: 'json', contentType: "application/json; charset=utf-8", data: "NAME=ALL_PROFILES", success: function (data, textStatus, jqXHR)` {
var html = '';
var obj = jQuery.parseJSON(data);
$.each(obj, function (key, val) {
html += '<option value="' + val + '">' + val + '</option>';
alert("Success" + val);
})
$('#selName').append(html);
$('#selName').selectmenu('refresh');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error ' + jqXHR.val + errorThrown.val + textStatus.val);
}
});
The back end is an asp.net page, and when I debug I get the string as "{"Name":["Maria","John","Raj","Rosh","Tony","Name","test3","test4","test5","test6"]}", which I put in JSONLint and validated. It returns an undefined error in the AJAX request above. If I try with a single string "Name":"John", it works perfectly. The function for adding option is not correct for an array of JSON strings(I will work on it once it enter the success block), but I don't understand why it returns an undefined error when it is returning a valid JSON string. Any help would be appreciated.
If your aspx page returns valid JSON and you are using dataType: 'json', you should not use jQuery.parseJSON() on the returned data, since jQuery already parses the returned JSON string into an object.
If you use "Name":"John" it is not valid JSON, so JQuery enters the error callback.
Put an extra paranthesis around the result and it works.It is strange since JSONLint is not validating it now

jQuery ajax - blank response returned

I am trying to use jQuery ajax to get some values from the database and then return them in an array.
I have used the same code several times before but this time, no response is being returned. Although the post values are the correct values that I would expect. Here is the javascript code that I am using:
$.ajax({ url: '/BlogArchive.asmx/ChangePost'
, type: 'POST'
, contentType: 'application/json; charset=utf-8'
, data: '{FileName:"' + FileName + '"}'
, dataType: 'json'
, success: function (data)
{
var arrayList = data.d;
var BlogPostTitle = $(".BlogPostTitle")[0];
var BlogPostDate = $(".BlogPostDate")[0];
var BlogPostContent = $(".BlogPostContent")[0];
$(BlogPostTitle).html(arrayList[0]);
$(BlogPostDate).html(arrayList[1]);
$(BlogPostContent).html(arrayList[2]);
}
// , error: function (XMLHttpRequest, textStatus, errorThrown)
// {
// //There was an error
// alert('dfd');
// }
});
The only javascript error that I am receiving is that data is null, which I would expect as the response is blank.
It seems that the name of the web method that I am calling from my javascript is not even being read, because if I changed 'ChangePost' to 'ChangePost1' for example, it still returns a blank response, although I would expect an error message saying that the web method can't be found.
It seems that it does recognise that the BlogArchive.asmx web service exists because if I put something that would create an error in the VB code, the error appears as the response.
I am sure this must be something simple that I am doing wrong. Any help would be appreciated.
, data: '{FileName:"' + FileName + '"}'
Seems odd. You probably meant:
, data: {FileName: FileName}
(or 'FileName=' + FileName)
Furthermore, did you inspect the request (and response) via FireBug or similar?
You should try using jQuery getJSON with the minimal arguments.
Another thing, when you are using JSON with jQuery, if the answer data are not wellformed
(like a space before / after the starting JSON string) could lead to a blank answer from
jQuery.
Be sure using traditionnal AJAX with jQuery that your answered data are correct.

Resources