So I am using this code to post:
$.ajax({
url: '/validator/ValidationController/validate',
data : JSON.stringify(parameters),
contentType : 'application/json',
type : 'POST'
})
And this to receive, both being triggered by the same button press. But it's just getting a null object.
def validate(){
Thread.currentThread().sleep(1000)
def parameters = request.JSON;
assert parameters.a == "a_value";
}
When I hover over the validate function, it's referred to as: Object validator.ValidationController.validate() I'm assuming the url is wrong.
Note: I am pretty inexperienced with this, speaking to me like I'm 5 is encouraged!
We would need more code to see how you are sending and receiving but it seems like you are not handling the asynchronous aspect. In simple terms, you are sending out the request and immediately trying to handle the response, even though it is not back yet and even though you tried to sleep. Check out the complete config for the ajax function. Something like this:
$.ajax({
url: '/validator/ValidationController/validate',
data : JSON.stringify(parameters),
contentType : 'application/json',
type : 'POST',
complete: function(request, success){
validate(request)
}
})
def validate(request){
Thread.currentThread().sleep(1000)
def parameters = request.JSON;
assert parameters.a == "a_value";
}
Related
I've the following generic PostTo method which can be used to post data to an ASP.NET MVc Controller, without the need for repetitive mark-up, I'm pretty sure it was working at one point, but for some reason, the success callback (any of it) doesn't get called.
Any thoughts? Everything looks right, and the server is responding with a valid 200 OK response.
It is however, an empty response. I tried a different (and empty) dataType value, but nothing changed.
function PostTo(controller, action, data, successCallback) {
$.ajax({
url: Settings.HostPath + controller + "/" + action,
type: "POST",
cache: false,
dataType: "json",
data: data,
success: function (data, textStatus, jqXHR) {
if (typeof (successCallback) != "undefined")
successCallback.call(this, data);
}
});
}
ajax method in your script, excepts json data from the server, but as you told in comments, your actions returns nothing (i thinks it's returns EmptyResult).
So, add any json result in your action:
public ActionResult Test()
{
return Json(new {Success = true});
}
I am trying to post data to mvc controller and i am unsuccessful doing so..hope i get any help...here is the xhrpost call
var reqObj =
{
Id: dojo.byId("Id").value,
Password: dojo.byId("Password").value
};
console.log(reqObj );
var xhrArgs = {
url: '~/FormController/ValidateRequest',
postData: reqObj ,
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json"},
load: function (data) {
alert(data);
}
}
var deffered = dXhr.post(xhrArgs);
console.log(deffered);
}
I could not even see a post call in firebug....what might be the problem..any clues?
Thanks in advance.
I see a couple issues:
First you populate reqObj with the values you want to post, however, you put "request" into your xhrArgs.
Second, you will need to convert reqObj to json (dojo.toJson), since you are handling the post as json.
Also, I don't see a reference to the dojo.xhrPost method? Are you using sometype of framework that encapsulates that?
I'm using jQuery UI autocomplete with data from a remote datasource. My use case is really similar to the example here:
http://jqueryui.com/demos/autocomplete/#remote
The only difference is that I set my delay to 0. In between the keystrokes, the menu disappears for about 1/10th of a second ~100milli seconds prior to the updated autocomplete list being displayed.
Is there anyway I can prevent the menu from temporarily disappearing between keystrokes? A good use case is google's search, where between keystrokes, the suggestion box does not temporarily disappear.
IMO, it is not a good practice to set a delay of zero when using a remote datasource. It will send more requests than needed and surcharge the server with no benefit.
Anyway, I think you can achieve what you want by defining the source option as a callback yourself.
First a bit of explanaton. I suppose you are using the remote feature passing an url as the source for the plugin. The plugin actually wraps this into a callback implemented this way:
// in case the option "source" is a string
url = this.options.source;
this.source = function(request, response) {
if (self.xhr) {
self.xhr.abort();
}
self.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
autocompleteRequest: ++requestIndex,
success: function(data, status) {
if (this.autocompleteRequest === requestIndex) {
response(data);
}
},
error: function() {
if (this.autocompleteRequest === requestIndex) {
response([]);
}
}
});
};
As you can see, if there is already an ajax request going on, it abords it. This happenning in your case as a request, as fast as your server can be, takes some time and your delay is zero.
if (self.xhr) {
self.xhr.abort();
}
This will actually execute the error callback of the aborted request that will execute itself the response callback with an empty dataset. If you look at the response callback, it closes the menu if data is empty:
_response: function(content) {
if (!this.options.disabled && content && content.length) {
...
} else {
this.close();
}
You can actually define your own source callback to make your ajax request yourself and change the default behavior by not aborting any pending request. Something like:
$('#autocomplete').autocomplete({
source: function(request, response) {
$.ajax({
url: url,
data: request,
dataType: "json",
success: function(data, status) {
// display menu with received dataset
response(data);
},
error: function() {
// close the menu on error by executing the response
// callback with an empty dataset
response([]);
}
});
}
});
I have problem with autocomplete. The code below is returnig me
["foo#foo.com","bar#bar.com"]
$('.autocomplete').keyup(function() {
tid = $(this).attr('id')
$(this).autocomplete({
source: function (req, resp){
$.ajax(
{
url: "autocompl.asp",
data:$("#msgForm").serialize() + "&field="+tid ,
success : function( resp ) {
return resp
}
})
}
});
});
But the suggestions don't appear. It worked for me when I have called autocomplete without any extra parameters.
Any clue?
Thanks in advance
Magda
Note that one of your parameters for the source function is resp, and you're using another resp afterwards. I think you need to use the first resp to send the response object back.
I'm using this as well and this works for me (Instead of sending an array of values, I'm sending an array of objects with two attributes, but I don't think it's mandatory).
id
label
so the code inside the ajax success should look something like this (my data variable is your second resp variable, a different name to avoid mixup):
success: function(data) {
for (i in data) {
a = {}
a.id = data[i]
a.label = data[i]
options.push(a)
}
resp(options)
}
I am having problems with Jquery parsing the JSON I am sending back... however, this is very odd because I am using MVC's JSON method.
Here's my setup. I have a very simple function:
$.ajax({
url: URLd,
dataType: 'json',
data: { Year: $('#VehicleYear').val(), Value: request.term },
success: function (data, textStatus, jqXHR) { alert("Success!"); },
error: function(XMLHttpRequest, textStatus) {
alert(textStatus + ": " + XMLHttpRequest.responseText);
}
});
It always runs the error function which shows:
parsererror: [{"Value":"Toyota","ID":160}]
I cannot figure out why in the world it is doing this... it was working with an older version of JQuery - and I read that the JQuery JSON parser is quite a bit more strict now- but I can't figure out what's wrong with my JSON.
Even if it is wrong, that's very frustrating because I'm using MVC's Json function to generate this:
public ActionResult GetVehicleModels(int Year, int MakeID, string Value = null)
{
var modlMatchs = (from VMYX in ent.VehicleMakeYearXREFs
join VM in ent.VehicleModels
on VMYX.VehicleModelID equals VM.VehicleModelID
join VMa in ent.VehicleMakes
on VM.VehicleMakeID equals VMa.VehicleMakeID
where VMYX.ModelYear == Year && VMa.VehicleMakeID == MakeID && VM.VehicleModelName.StartsWith(Value)
orderby VMa.VehicleMakeName
select new { Value = VM.VehicleModelName, ID = VM.VehicleModelID }).Distinct().Take(10).ToList();
return this.Json(modlMatchs, "application/json", JsonRequestBehavior.AllowGet);
}
I must be missing something glaringly obvious... still getting the hang of JQuery/MVC but these things are really slowing my progress.
Sure enough, the JQuery result looks as follows (according to Chrome's developer toolbar)
[{"Value":"Toyota","ID":160}]
Change your dataType in the jQuery AJAX call to "text json". I suspect there may be a problem with the response content-type header, or something else that's causing jQuery not to acknowledge the dataType as json. Using "text json" will cause jQuery to accept it as plaintext before converting it to a js object.
var parsed = jQuery.parseJSON('[{"Value":"Toyota","ID":160}]');
I've just tried the above and it parses it fine, however remember it has returned it as a single record in an array (due to returning an IEnumerable from the C#).