so I can't seem to get my dropdown menu to work. Here's the code:
$.ajax({
url:"/json/testjson",
cache:true,
success: function(j){
console.log(j);
alert(j);}
});
This returns a valid json string:
{"data": ["test", "data"], "result": "OK"}
I can't get the success function to fire at all. There is no error anywhere (neither in the firebug log, nor in the netlog, and the response from the site is okay. The firebug parser cannot parse that JSON but the JLINT validator validates it correctly. I have tried the setting the content-type to application/json, no success. I have also tried, $.getJSON, $.get, and nothing is firing. I have also tried
Any ideas?
Thanks
Jon
Thank you HaBo - the answer was to remove the cache: true!
Thanks!
J
I believe you need to set dataType to json to make sure the data coming from the server is treated as a json object.
$.ajax({
url: "/json/testjson",
dataType: "json",
cache: true,
success: function(j) {
console.log(j);
alert(j);
}
});
Take a look at the $.ajax API.
Related
Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
I have an ajax call that works fine locally, but when I published it into the server, the code is never executed but returns "200 OK" anyway. No "success" code is ejecuted, nor the "error" code. Here's my ajax call:
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
for (var i = 0; i < myObj.length; i++) {
var element = document.getElementById("LbItem " + myObj[i].MenuItemID);
element.innerHTML = "<b>" + element.innerHTML + " (" + myObj[i].Cantidad + ")</b>";
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I also tried to put the complete url in the "url" field but still no luck.
The weird thing is that when I put the complete url directly into the browser, it is still not executing the code. And it works fine locally!!
I know there's a similar post (jQuery $.ajax failing silently, no error messages, and server responded with 200 OK) but is not resolved and it's driving crazy here.
PD: this is NOT cross-domain, my ajax code is in a .ascx and I am trying to call a method on an .aspx
Thanks very much!!!!
EDIT: I tried to remove the System.web.extensions reference of my web project and add the dll to my bin, but it's still not working (the 1.0.61025.0 version). Besides, I am running the ASP.NET website in IIS with framework 2.0, and I don't have framework 3.5 installed on my server (but locally I do). Maybe that's the problem? I can't install it because of the client security policies, what shall I do?
EDIT 2: I tried doing a simple response from my .aspx, just to test if the problem was in that method, but it is still not executing the success function. Here's my .aspx code:
[WebMethod]
public static string ObtenerContadores()
{
return new JavaScriptSerializer().Serialize("true");
}
and adapted the .ascx
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(dictionary) {
alert("hello");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
Here's your problem: "The weird thing is that when I put the complete url directly into the browser, it is still not executing the code." Your JavaScript is expecting -- requiring -- a JSON response, and is apparently getting no response at all. This is not a JavaScript problem, but a problem with your .aspx page.
EDIT: Based on your comments below, it's clear that the problem is that your .aspx page is not returning what you expect. Because the .aspx doesn't produce the expected output even when you go to it directly, the problem is in that page, not in the jQuery.
Pretend the .aspx produces {}, false, or true. Your success code will run, but not do anything. Try putting an alert("Foo"); in there and watch what happens. The problem isn't that your jQuery is busted; it's that it isn't getting meaningful input from your .aspx page.
P.S. I would recommend using a variable name other than data in your success function, just in case it's getting messed up by the data object attribute in your .ajax call.
Okay, I believe I've figured this out, so I'm posting a second answer to preserve the prior discussion.
Here's the fix. Remove this line:
contentType: "application/json; charset=utf-8",
In my test script, this caused jQuery to send the Content-Type header application/json; charset=utf-8, as expected, but the actual contents of the request were not properly sent as JSON. For example, rather than sending {"foo":"bar"}, it was sending foo=bar. As a result, the receiving script acted as if no data was posted at all. When I commented out the line above, my test script worked fine and did whatever I expected with the values received from the target URL.
Note that this will post your data as normal post data. For example, if your $.ajax() call looks like this, the posted data will contain a variable named foo and one named who:
$.ajax({
...
data: {foo : "bar",
who : "what"},
...
});
If you want to post already-serialized JSON, do it like this:
$.ajax({
...
data: { somevariablename: '{"foo":"bar","who":"what"}' },
...
});
Then, you just have to parse the POST parameter somevariablename on the server side.
Hope this helps!
If its VS2012, try for adding Mime Type Handler, since VS2012 has IIS express and it need to add Mime type handler externally,
Add below code to web.config
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
.. and if its not VS2012 then follow this link
add .json handler support in IIS 7
I want to thank everyone for your help.
I finally had to install the 3.5 Framework on the server, I had no choice.
The second I installed it, and updated the web.config dll's references to 3.5, it worked like a charm.
Thanks again!!!!!
I have to dynamically get data from another domain dynamically and I want to use ajax and jquery.I have done the following.
<script type="text/javascript">
$(document).ready(function(){
$('#getdata').click(function(){
var sitename = $('#sitename').val();
var listname = $('#listname').val();
getdata(sitename, listname);
})
});
function getdata(sitename, listname){
$.ajax({
url : 'http://192.168.10.34:8576/home/GetJsonData?site='+sitename+'&listname='+listname+'&viewname=',
datatype : 'JSON',
type : 'GET',
crossDomain: true,
contentType: "application/json; charset=utf-8",
success : function(data){
console.log(data)
},
error : function(){
alert('error');
}
})
}
</script>
But it's just returning error. why? Have I done anything wrong?
any help/suggestions are welcome. thanks.
You cannot request data from any domain other than the domain from where your JavaScript has originated from. For cases like this you should use JSONP(JSON with Padding). Change the dataType to JSONP in jQuery ajax function. Like this...
datatype : 'JSONP'
Also, your cross domain(http://192.168.10.34:8576/home/GetJsonData) should support jsonp or else your request will fail.
The alternative to using the JSONP hack is to allow for Cross-Origin Resource Sharing on your application.
It's painfully simple to handle this, but understand that this opens up minor to intermediate security issues at scale, so make sure to take care of them appropriately.
Simply set the Access-Control-Allow-Origin response header in your server application to *. CORS requests also issue OPTIONS preflight requests, so you can choose whether or not to handle those as well.
I am using Jquery Ajax for calling the methods in controller, but i am always getting invalid json primitive error.
Below is the Code.
Client side Code
$("#something >li").each(function () {
widgetsobj.push({
WidgetId: $(this).attr("dbid"),
ColumnNumber: 2,
RowNumber: 3,
WidgetType: "Graph",
WidgetName: "ddd",
PageName : "Page1"
});
});
$.ajax({
url: "/Home/ABC",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) },
success: function (data) {
alert("ss");
},
error: function (data) {
debugger;
}
});
at controller
[HttpPost, ValidateInput(false)]
public JsonResult ABC(string pagename1, List<XYZ> widgetsobj1)
{
// do something
}
Note XYZ is object with below properties.
WidgetId
ColumnNumber
RowNumber
WidgetType
WidgetName
PageName
So please let me know where i am wrong.
The thing about ajax is that it is very picky about what you send through. You need to make absolutely sure that everything is in the correct format.
i.e. you are using double quotations (") rather than single (') and so on.
The best thing to do, would be to use Firebug or a similar console to view the POST as it is executed or to use alert() to view the POST data before it is sent off. That way you can identify where the problem is.
Remember, when you use json.stringify() it is going to turn whatever you feed it into what it believes will be an acceptable JSON string and because it is just a string there could be syntax errors at any point!
From what I can see here, there may be an issue at:
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) }
You may want to try:
data: { "pagename1": pagename, "widgetsobj1": JSON.stringify(widgetsobj) }
I got the same error. My solution was to add:
dataType: 'json',
to the ajax call. Looks like you already had that in in your ajax call. But Hope this helps someone else.
Trying to get JQuery to post JSON to a server:
$.ajax({
url: "/path/to/url",
type: "POST",
dataType: "json",
contentType: "json",
data: {"foo": "bar"},
success: function(){
alert("success :-)");
},
error: function(){
alert("fail :-(");
}
});
Problem is the data appears on the server as "foo=bar" rather than the desired "{\"foo\":\"bar\"}.
I thought specifying either the dataType or contentType params would do the trick, but no.
Anyone know the correct ajax configuration ? [or alternatively a way of serialising the 'data' parameter as JSON prior to posting ?]
Thanks!
You could use json2.js:
data: JSON.stringify({"foo": "bar"})
Datatype is for returned data. Contenttype is not applicable, see here
It can only send strings, I use JSON.stringify on my created javascript objects, in your case you could just manually code the string.
You will also need to access the string on server side, for that if you are using java I can recommened google's gson