Select2 ajax correctly calls webservice, but after that does nothing after

I create select2 with the following javascript

$j("#" + name).select2({ placeholder: "", width:"300px", minimumInputLength: 3, ajax: { url: "/MyService.asmx/ServiceMethod", dataType: 'json', data: function (term) { return { q: term // search term }; }, results: function (data) { alert('results'); return {results: data}; }, success: function() { alert('success'); }, error: function () { alert('error'); }, }, }); 

The method I call is as follows:

 <WebMethod(enableSession:=True)> <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> Public Function ServiceMethod(q as String) As String Dim temp As String = "[{'id':'35','text':'Drew'}]" Return temp End Function 

I also have <ScriptService()> around the class. The enableSession function exists, because in the end I will run a lot of logic in the service that requires it, but at the moment I'm just trying to return a simple string using JSON.

I set a breakpoint in the web service and I know what it is called. I know that it returns JSON. I also know that select2 expects "id" and "text" in JSON return

My problem is this: after entering 3 characters, the data function calls (I put a warning in it), the webservice breakpoint is deleted, but none of the results, successes or error events light up. Select2 just rotates and nothing happens. Javascript errors are not entered into the console, and I don’t even understand where to look for information on why ajax does not handle the return value from the service.

Can someone point me in the direction, at least, where to see why this does not work?

+4
source share
1 answer

So, I fixed it myself, getting a hint to look at the network log. The service returned correctly, but it returned XML, not JSON. I had to make 2 modifications, and it worked.

My working ajax:

 ajax: { url: "/MyService.asmx/ServiceMethod", type: 'POST', params: { contentType: 'application/json; charset=utf-8' }, dataType: 'json', data: function (term, page) { return JSON.stringify({ q: term, page_limit: 10 }); }, results: function (data) { return {results: data}; }, }, 

Important changes were to the type by placing contentType in the params and JSON.stringify-data wrappers. I am going to change what has passed and how it has passed, but now, at least, they are communicating. Hope this helps anyone looking for a similar solution.

+4
source

Source: https://habr.com/ru/post/1493051/


All Articles