Muhammad Nauman
Muhammad Nauman

Reputation: 213

autocomplete json

i have follow the following wave for autocomplete and datepicker but the auto complete can't work Secondly is there any razor syntax to show the datepicker and autocomplete

javascriptfile

/// <reference path="jquery-1.5.1-vsdoc.js" />
/// <reference path="jquery-ui-1.8.11.js" />

$(document).ready(function () {
    $(":input[data-autocomplete]").each(function () {
        $(this).autocomplete({ source: $(this).attr("data-autocomplete") });
    });
    $(":input[data-datepicker]").datepicker();    
})

The View File

    @model TestDateTimePicker.Models.TestClass

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>TestClass</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.City)
        </div>
        <div class="editor-field">
            <input data-autocomplete="@Url.Action("AutoComplete", "City","City")" class="text-box single-line" id="City" name="City" type="text" value="" />                        
            @Html.ValidationMessageFor(model => model.City)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Date)
        </div>
        <div class="editor-field">            
            <input class="text-box single-line" data-val="true" data-val-required="The Date field is required." id="Date" name="Date" type="text" value="" data-datepicker="true"/>
            @Html.ValidationMessageFor(model => model.Date)            
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>



  }

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

The Json Controller

public ActionResult AutoComplete(String s)
        {
            var d = db.Cities
                .Where(r => r.Name.Contains(s))
                .Select(r => new { label = r.Name });            
            return Json(d, JsonRequestBehavior.AllowGet);
        }

Upvotes: 0

Views: 1482

Answers (2)

Sachin
Sachin

Reputation: 39

The key to this solution is: We need to use item.label name because the AJAX will return the value in list format so we need to extract the value as shown in the below example.

<html>
    <head>
            <title>Ajax</title>
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            <script>
                 $(function() { 
                    $("#myname").autocomplete({
                      source: 'emp.php',
                      select: function (event, ui) {
                        $("#myname").val(ui.item.label);
                        $("#myid").val(ui.item.id);
                    },
                       minLength: 0,
                       autoFocus: true,
                    }); 
                });
            </script>
    </head>
    <body>
        <h2>Ajax Testing</h2>
        <input  name="myname" id="myname" type="text">
        <input  name="myid" id="myid" type="text">
    </body>
</html>
-------------- Below is the code of PHP for emp.php page --------------------------
<?php
require_once 'connection.php';
$query  = "SELECT myname as label , myid as id  FROM emp WHERE name LIKE ? ORDER BY name";
$rsTable = sqlsrv_query($conn, $query,array('%'.$_REQUEST['term'].'%'));
while ($row_rsTable = sqlsrv_fetch_array($rsTable, SQLSRV_FETCH_ASSOC)) {

    $emparray[] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $row_rsTable);
}
echo json_encode($emparray);
sqlsrv_close($conn);
?>

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

@Url.Action("AutoComplete", "City", "City") 

should be

@Url.Action("AutoComplete", "City")

The third argument that you are using represents route values which must be an anonymous object and not a string. As far as the autocomplete plugin is concerned, it uses the term query string when performing the AJAX request to fetch the data. So you will have to rename your controller action parameter as well:

public ActionResult AutoComplete(string term)
{
    var d = db.Cities
              .Where(r => r.Name.Contains(term))
              .Select(r => new { label = r.Name });            
    return Json(d, JsonRequestBehavior.AllowGet);
}

Also make sure that that jquery-ui-1.8.11.min.js script is referenced in your page (cannot see it in your code example).

If it still doesn't work make sure that the AutoComplete action doesn't throw an exception when performing the query. Also look with FireBug or Developer Tools if there aren't some javascript errors and if the AJAX request is correctly sent.

Upvotes: 1

Related Questions