Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup...

The Code I'm Using:

            <input type="text" id="MajorsIds" name="MajorsIds"  />
            <script type="text/javascript">
                $(document).ready(function () {
                    $("#MajorsIds").tokenInput("/AjaxAPI/Major/GetMajors"
                    , {
                        prePopulate: [
                            { "id": 501, "name": "Test 1" },
                            { "id": 502, "name": "Test 2" },
                            { "id": 503, "name": "Test 3" }
                        ]
                    });
                });
            </script>

Server ActionResult:

    public ActionResult GetMajors(string q)
    {
        var majors = _majorService.GetAllMajors()
            .Where(m=> m.Department.ToLower().Contains(q.ToLower()))
            .Select(m => new {id = m.Id, name = m.Department});

        return Json(majors,"text/html",JsonRequestBehavior.AllowGet);
    }

Issues arise when typing "a" in the search input - data is fetched from the server but not displayed. Instead, a frozen "searching ..." message persists.

Response Headers:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 26 Apr 2011 00:18:48 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 24
Connection: Close

Request Headers:

GET /AjaxAPI/Major/GetMajors?q=a HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
X-Requested-With: XMLHttpRequest
Referer: http://localhost:5000/Home/GettingStarted

Response Message:

The JSON content received on the page output is as follows:

[{"id":1,"name":"ACCT"},{"id":3,"name":"AE"},{"id":4,"name":"ARC"}, {"id":5,"name":"ARE"},{"id":20,"name":"MATH"},{"id":21,"name":"STAT"}]

Despite valid JSON response, data isn't displaying as expected. Can't pinpoint the issue or solution.


Running the provided demo worked smoothly with an external link. Noticed some additional parameters included in the demo request.

Demo Setup:

    <input type="text" id="demo-input" name="blah" />
    <script type="text/javascript">
    $(document).ready(function() {
        $("#demo-input").tokenInput("http://shell.loopj.com/tokeninput/tvshows.php");
    });
    </script>

Headers of Response:

HTTP/1.1 200 OK
Server: nginx/0.6.32
Date: Mon, 25 Apr 2011 22:53:34 GMT
Content-Type: text/html
X-Powered-By: PHP/5.3.3-1ubuntu9.1
Via: 1.1 cache4.ruh
Age: 0
Transfer-Encoding: chunked
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Content-Encoding: gzip

Request Headers:

GET http://shell.loopj.com/tokeninput/tvshows.php?callback=jQuery151008570635266447713_1303770077700&q=a&_=1303771352965 HTTP/1.1
Host: shell.loopj.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Proxy-Connection: keep-alive
Cookie: __utma=71995406.317557806.1303476969.1303642425.1303757215.5; __utmz=71995406.1303476969.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmc=71995406

Response Content:

If directly accessing the link found at here, the result appeared differently:

[{"id":"978","name":"cha$e"},{"id":"1530","name":"The Life and Times of Tim"},{"id":"1210","name":"Kenny vs. Spenny"},{"id":"1393","name":"Sex and the City"},{"id":"1394","name":"Shark"},{"id":"1395","name":"Shaun the Sheep"},{"id":"1398","name":"Side Order of Life"},{"id":"1397","name":"Shear Genius"},{"id":"1396","name":"Seinfeld"},{"id":"1399","name":"Sinchronicity"}]

However, using Firebug reveals a slightly modified response:

jQuery151008570635266447713_1303770077699([{"id":"978","name":"cha$e"},{"id":"1530","name":"The Life and Times of Tim"},{"id":"1706","name":"The Peter Serafinowicz Show"},{"id":"1389","name":"Sea Patrol"},{"id":"1390","name":"Secrets of a Small Town"},{"id":"1211","name":"Kitchen Nightmares"},{"id":"1212","name":"L.A.P.D.: Lekanopedio Attikis Police Department"},{"id":"1214","name":"Lab Rats (2008)"},{"id":"1215","name":"La Femme Nikita"},{"id":"1216","name":"L.A. Ink"}])

Unexpected presence of "callback" and "_" parameters in the response. Unable to determine their origin; something peculiar happening.


Seeking assistance to find solutions for this dilemma.

Note: Attempts made with POST method were unsuccessful. Utilizing complete URL (http://localhost:500/AjaxAPI/Major/GetMajors) instead of relative path also yielded no changes.

Answer №1

After some troubleshooting, I managed to resolve the issue successfully:

While the plugin's documentation stated that the default value for the crossDomain option is false, upon inspection, it was evident that this setting was not explicitly defined. To rectify this, I included crossDomain: false, in the plugin's default settings array, which ultimately fixed the problem.

It's perplexing why specifying crossDomain: false directly in the function call didn't work before, but my theory is that it could be related to caching issues.

Special thanks to Hogan for your assistance and introducing me to jsonp!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bootstrap: Retrieve an image from a modal

I am working on a modal that contains a variety of selectable images. When an image is clicked, I want to change the text of the button in the modal to display the name of the selected image. Additionally, I would like to grab the selected image and displa ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

Converting nested JSON data into a Pandas Dataframe: A step-by-step guide

There have been numerous instances of this question being raised, yet none of the solutions seem to work for my specific issue. Query: import urllib, json url = 'https://api.carbonintensity.org.uk/regional' params = 'Accept: application/ ...

Calculating the total sum of data in a JSON file by grouping it based

I have an online JSON file with the following information: {'skladiste': 1, 'sifra': '7138', 'nc': 0.8, 'vpc': 47.01, 'mpc': 55.0, 'stanje': 5.0, 'aktivan': 255, 'lokacija ...

Issue: The npm module 'moment' cannot be located

My Meteor app works flawlessly on localhost, but when deployed to a remote heroku server, I encounter these errors. (I am following this) Any suggestions on how to resolve this issue? 2016-09-09T13:26:02.533532+00:00 heroku[web.1]: Starting process with ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

The issue with Angular-gettext is that it fails to update dynamically generated strings in the code

Whenever I try to set the language using the code gettextCatalog.setCurrentLanguage(langString);, it doesn't seem to affect my side-nav menu. My side menu has two possible states: expanded or collapsed, and I use ng-include to control its content base ...

What is the best way to retrieve the values of various input fields using their numbered IDs and then store them in a MySQL

I attempted to design a form that allows for multiple inserts, where users can add as many titles and languages as they desire by entering a number. The display of titles and languages is functioning correctly, but I am struggling to retrieve the individua ...

Is there a way to transform MySQL geographic coordinates into JSON format with Ruby on Rails?

Can someone help me figure out how to use Ruby on Rails to generate a JSON object using the "latitude" and "longitude" data from my MySQL table named "Locations"? I want to create a Google Map with multiple markers pulled from a MySQL database. While I kn ...

What is the process for utilizing a custom plugin within the <script setup> section of Vue 3?

//CustomPlugin.js const generateRandomValue = (min, max) => { min = Math.ceil(min); max = Math.floor(max); const random = Math.floor(Math.random() * (max - min + 1)) + min; console.log(random); }; export default { install(Vue) { Vue.conf ...

Retrieve the html code from a PHP backend by utilizing core-ajax within the Polymer framework to store the information

Is there a way to retrieve JSON data from a PHP script that contains HTML tags, and display the data properly in an HTML format without seeing the tags? Currently, HTML tags are displayed as: <h1>hello</h1> instead of rendering as: hello I am ...

jsTree eliminates the hashtag from the URL

Utilizing a JSON generated jsTree to efficiently navigate through a directory structure has been my recent task. I have successfully implemented the select_node event to capture the path of the selected node as a string and then update the location.hash ...

Is there a way to exclude specific fields from a JSON file when filtering it?

Currently, I am working on a project that requires the use of my Google Maps Location History Json file (obtained via google takeout). The issue I am facing is that this json contains over a million location objects with certain fields, like "activity", wh ...

Tips for combining enable and disable properties in flatpickr.js?

I'm facing a challenge with using both the enable and disable properties in flatpickr.js. The enable property returns a range of dates that should be enabled, but I specifically want to disable certain days within that range, like weekends. datePicker ...

Bringing in data from <script> to use in <script setup>

To ensure unique ids for instances of a Vue component, I am using a simple generator to enumerate them. Typically, I would initialize the generator outside of the setup function like this: const idGen = generateIds("component:my-component"); export defaul ...

Issue: Error encountered while trying to use the removeAttribute() function in Selenium and Java: missing closing parenthesis after argument list

WebElement removeReadOnly=driver.findElement(By.xpath("//input[@id='mat-input-0']")); js.executeScript("document.getElementBypath('//input[@id='mat-input-0']').removeAttribute('readonly');",&quo ...

VueJS - Harnessing the power of the Document Object Model for dynamic template rendering

Essentially, I am in need of VueJS to provide warnings for unregistered components when in DOM template parsing mode. It seems that currently Vue does not pay attention to custom HTML when using DOM templates, although errors are correctly displayed with s ...

I'm puzzled about what could be behind this error message Error [ERR_HTTP_HEADERS_SENT], especially since I've only sent the response header once. How can I figure out the cause

Here is a snippet of code from my routes file: router.get('/api/', async function(request, response){ let entries = await Entries.find({}, function(error){ if(error) console.log(error); }); let catArray = []; entrie ...

Using ngrx to automatically update data upon subscription

Background The technology stack I am using for my application includes Angular 4.x, ngrx 4.x, and rxjs 5.4.x. Data is retrieved from a websocket as well as a RESTful API in order to share it between multiple components through ngrx. Currently, data is ref ...

Creating a sequence of HTTP calls that call upon themselves using RxJs operators

When retrieving data by passing pageIndex (1) and pageSize (500) for each HTTP call, I use the following method: this.demoService.geList(1, 500).subscribe(data => { this.data = data.items; }); If the response contains a property called isMore with ...