I am getting Loading failed error when searching for something in a select2 box using ajax. My code is as follows:
$("#drugSearch").select2({
placeholder: "Search for a drug by drug id or name",
minimumInputLength: 3,
ajax: {
url: "#Url.Action("SearchDrug", "Drug")",
dataType: 'jsonp',
quietMillis: 100,
data: function (term, page) {
return {
query: term
};
},
results: function (data, page) {
debugger;
return {
results: data.drugs
};
}
},
formatResult: drugResult,
formatSelection: drugSelection,
escapeMarkup: function (m) { return m; }
});
function drugResult(drug) {
debugger;
return drug.Name + " (" + drug.DrugBankRef + ")";
}
function drugSelection(drug) {
debugger;
return drug.Name + " (" + drug.DrugBankRef + ")";
}
The breakpoints are also not hitting the above debugger; lines
My JSON is returned as:
{ drugs: {[...]} }
It also has the properties Name and DrugBankRef and I have confirmed a valid JSON is returned from the URL after searching.
What am I doing wrong here? Anything else you need to trace the issue?
I was using JSONP instead of JSON, changing the data type to JSON fixed the issue.
It is not an error. There is a real difference between JSON and JSONP. In JSONP, your JS will send in a supplementary parameter, named callback, that contains the name of expeted enclosing function name.
Select2 supports the two modes :
JSON, which expects { drugs: {[...]} } as data
JSONP, which provide a callbackName and expects callbackName({ drugs: {[...]} }); as data
Both works, and are correct, differents, way of processing.
Feel free to read http://en.wikipedia.org/wiki/JSONP
Related
i have a datatable which i'm loading via Ajax.
in the server side i'm prepering the data for the table and prepare another data for another thing
i want, beside the table loading, to do another thing with the other data i've prepared
so i added to my ajax code a success event, but it replace the table loading and i only can do the other thing
i can't separate between the table loading and the other thing because they are connected, meanning the other thing is influenced by the table loading(changes)
i tried also fnDrawCallback but i don't know how to pass the data of the other thing
Here's the Ajax code with success event:
"ajax": {
"url": "/Entreaties/GetEntreaties",
"data": function (d) {
d.status = 0;
d.firstLoad = firstLoad;
d.jAdvanceSearch = JSON.stringify(new AdvanceSearch());
d.freeText = $("#table_filter input").val();
},
"type": "POST",
"dataType": "json",
success: function (data) {
$.each(data.contactWaySum, function (key, value) {
alert(key + ": " + value.ContactWay);
});
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.responseText);
}
},
Thank you all for your help
If I understand you right, you were using the built in DataTable ajax but stopped because you wanted to do several things at once. If so, go back to using the DataTable ajax and used the dataFilter function to separate them out and apply them.
Here is an example:
// If your server side sends back somehting that looks like this for the data table (this is what it is expecting)
{draw:1, recordTotal:20, recordsFilter:20, data:dataSet }
// adjust your json to look like
// If the json object return looks like what the
{ dataTableData:{draw:1, recordTotal:20, recordsFilter:20, data:dataSet }, otherStuffData: otherData}
$("#sometable").DataTable({
// other data table stuff left out to save space
"serverSide": true,
"ajax": {
"url": "you url" ,
"data": function (ssp) {
// Do the stuff you need to to get your paramerters ready
// server side parameters (ssp) are documented at http://datatables.net/manual/server-side
// in addition to the ssp parameters, the name of the column is pulled from the table header column
return ssp;
},
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (a, b, c, d) { debugger; },
dataFilter: function (data) {
// call function or what ever you need to do with the other data here
doOtherStuff(data.otherStuffData);
// the web method returns the data in a wrapper
// so it has to be pulled out and put in the
// form that DataTables is expecting.
//return just the datatable data here
return JSON.stringify( data.dataTableData);
}
}
});
Hope there is some out there that can help!,
While debugging a WCF service that a phonegap application connects to it seems to post twice.
When the application runs normally no Break points etc it all works fine and i only receive 1.
It appears to me that ajax reposts itself if no response is returned from the server after a few seconds.
I will need to confirm this threw wireshark but just wanted to know if anyone else has come accross this before.
$.ajax({
type: "POST",
url: ServicePATH ,
data: JSON.stringify({ objs: arrayobj, parm2: var2, parm3: var3, parm4: 1 }),
contentType: "application/json",
dataType: "json",
success: function (data, textStatus, jqXHR) {
CallonSuccess(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error ' + textStatus);
console.log('XMLHttpRequest ' + XMLHttpRequest);
var str = '';
for (prop in XMLHttpRequest) {
str += "prop " + prop + " value :" + XMLHttpRequest[prop] + "\n"; //Concate prop and its value from object
}
console.log(str);
console.log('errorThrown ' + errorThrown);
console.log('passing ' + JSON.stringify({ objs: arrayobj, parm2: var2, parm3: var3, parm4: 1 }));
}
}).done(function () { console.log('Finished ajax'); });
Thanks Lmac
Perhaps no solution (see update below) for you but the same behaviour here.
Without the jquery Mobile framework everything works okay, with the framework embedded it fetches my json file a second time. In Chrome's Console you can see it under Network: GET status 200 and GET status 304 (not modified).
I have the option to throw out jQuery Mobile and I surely will. But would be also interested in knowing what's happening there.
UPDATE:
I had the xmlhttprequest within the $(document).ready(function() { }); It seems as if both jQuery and jQuery Mobile react to that.
If I put the script at the end of the site and make my xmlhttprequest outside the ready-method it fetches my json file only once.
var display_message="";
$('input:checked').each(function(index) {
var profile_id=$(this).val();
$.ajax({
type: 'post',
url: 'myUrl',
data: data,
success: function(data) {
if(data=="ok")
display_message = display_message + data +", ";
}
});
});
alert(display_message);
alert(display_message);
if($.trim(display_message)!=""){
jAlert("Your birthdate already exits in "+display_message.substring(0, display_message.length - 2)+".", "Bdate");
return false;
}
in this code, i use two alert-box for display display_message variable value.
when i run successfully this code, in 1st alert-box i get blank value and second alert-box i get value which i needed, then it will go in if condition.
if i doesn't use alert box then it will always take null value in display_message variable and never enters into the if condition. so what i need to change to run this code without alert box?
You are making an asynchronous call via AJAX, but your code is executing synchronously. So it is returning before the AJAX call completes. The first alert box just gives the function time to catch up. You need to handle all this code in your success callback.
var display_message="";
$('input:checked').each(function(index) {
var profile_id=$(this).val();
$.ajax({
type: 'post',
url: 'myUrl',
data: data,
success: function(data) {
if(data=="ok")
display_message = display_message + data +", ";
if($.trim(display_message)!=""){
jAlert("Your birthdate already exits in "+display_message.substring(0, display_message.length - 2)+".", "Bdate");
return false;
}
});
});
You want all your ajax queries to finish and return results, right?
Then this is a synchronization problem.
I would suggest this approach (code is simplified for clarity).
var inputs_processed = -1;
var inputs_to_process = -1;
function queryData() {
inputs_to_process = $('input:checked').length;
$('input:checked').each(function() {
$.ajax({success: function(data) {
inputs_processed += 1;
// build up that message
}});
});
}
function displayResult() {
if (inputs_processed == inputs_to_process) {
// display result
} else {
// not all queries finished yet. Wait.
setTimeout(displayResult, 500);
}
}
queryData();
displayResult();
Basically, you know how many requests should be made and you don't display result until that number of requests returns.
Why your data is "data"? I cant see any variable called data is declared here. You should pass in the value you want to use as the parameter into the data options.
Edit: This is why u getting the null value. data is not initialize into anything. Only after the success function, your "data" will have the value since you declare the return value with the same name
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'm having a problem similar to jQuery $.ajax Not Working in IE8 but it works on FireFox & Chrome, but with a different use case.
I'm using the jQuery Form plug-in to handle a file upload to an ASP.NET MVC controller, which sends the file off for parsing and processing. If an Exception is thrown, it should alert the user to the issue.
//client side code
//make an ajax call, sending the contents of the file
$("#ajaxUploadForm").ajaxSubmit({
dataType: 'json',
url: '/plan/Something/ExcelImport',
iframe: true,
beforeSend: function () {
$(".ui-dialog-buttonpane").find("#my_progress").fadeIn();
},
success: function (data, textStatus) {
output = "<center><span class='flash'>" + data.message + "</span></center>";
$("#flash_message").html(output).fadeIn('slow');
setTimeout(function () { $("#flash_message").fadeOut() }, 5000);
cleanup();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest is " + XMLHttpRequest);
var contents = "";
for (prop in XMLHttpRequest) {
contents += "\na property is " + prop + " it's value is " + XMLHttpRequest[prop];
}
alert("the contents are " + contents);
alert("textStatus is " + textStatus);
alert("errorThrown is " + errorThrown);
//comes back in an HTML envelope. This should be parsed with regex, but I can't get it to work. Dirty hack
response = XMLHttpRequest.responseText.substring(XMLHttpRequest.responseText.indexOf("<body>"));
response = response.replace("<body>", "");
response = response.replace("</body>", "");
alert("There was a problem with the upload.\r\n" + response);
},
complete: function (XMLHttpRequest, textStatus) {
$(".ui-dialog-buttonpane").find("#my_progress").remove();
something_import.dialog('close');
something_import.dialog('destroy');
}
});
//server side code
public FileUploadJsonResult ExcelImport()
{
FileUploadJsonResult result = new FileUploadJsonResult();
HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
return new FileUploadJsonResult { Data = new { message = "File contained no data" } };
String fileName = Path.GetFileName(hpf.FileName);
String timeStampedFile = fileName.Insert(fileName.IndexOf('.'),"_"+DateTime.Now.ToFileTimeUtc());
string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "tempo", timeStampedFile);
hpf.SaveAs(savedFileName);
try
{
result = ProcessFile(savedFileName, Request["Id"]) as FileUploadJsonResult;
}
catch (ArgumentException e)
{
this.Response.StatusCode = 500;
this.Response.StatusDescription = System.Net.HttpStatusCode.BadRequest.ToString();
Response.Write(e.Message);
result = Json(new { message = e.Message, stackTrace = e.StackTrace }) as FileUploadJsonResult;
}
return result;
}
This works perfectly in Chrome and Firefox. In IE, the XMLHttpRequest object coming back is different:
FF:
IE:
I've been Googling around for differences between the browser implementations of XMLHttpRequest, but haven't found anything that deals specifically with this case. Stymied.
The reason this is happening is because of the iframe fallback strategy that ajaxSubmit employs. I think since the response gets posted into the iframe IE tries to figure out how to dipslay it and decides that it wants to ask you to download the response instead of just putting it in the iframe.
I came across this same situation a while ago and found an article (that I can't find now) that offered a workaround.
If you surround your json response in a textarea nobody is going to complain(IE,FF,Chrome,probably Safari) and you'll get your response parsed correctly.
E.g. if you are returning
{Id: 1, Name: 'Me'}
just return:
<textarea>{Id: 1, Name: 'Me'}</textarea>
You see now IE thinks it's html so it inserts it into the hidden iframe. Your ajaxSubmit function still gets called and parses the json correctly and then everybody's happy. :)
If you're using ASP.NET MVC you could shamelessly copy this extension method :)
public static class ControllerExtensions
{
public static ActionResult JsonSafe(this IController controller, object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return new WriteResult(string.Format("<textarea>{0}</textarea>", serializer.Serialize(obj)));
}
}
The wikipedia article on XMLHttpRequest seems to give a good overview of the history behind the XMLHttpRequest. It seems Microsoft and Mozilla developed/adopted their own versions of the object and hence why you are probably seeing different properties.
Here is a link to Microsoft's implementation of the XMLHttpRequest interface members, which seem to match the properties in your alert.
Here is the a link to Mozilla's implementation of XMLHttpRequest.
So while we wait for the W3C to standardize the XMLHttpRequest you will continue to have different implementations across the browsers like you are seeing in this case.
For some added fun here is Apple's and Opera's specifications on XMLHttpRequest.