Call ActionResult from Ajax.BeginForm - asp.net-mvc-3

I using Ajax begin form and when I click submit button, post method doesn't call, here is code:
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "personListDivforReturnPerson"}))
{
<div class="ReturnPersonGeneralPageBody">
<div class="returnPersonHeader">
საზღვრის კვეთისას დაფიქსირებული მონაცემები
</div>
<div class="fieldNameForMIA">
<span>#Html.LabelFor(model => model.LastName, "გვარი")
<br />
#Html.EditorFor(model => model.LastName)
</span>
<div class="fieldNameInnerForMIA">
<span>#Html.LabelFor(model => model.FirstName, "სახელი")
<br />
#Html.EditorFor(model => model.FirstName)
</span>
</div>
</div>
<div class="fieldNameForMIA">
<span>#Html.LabelFor(model => model.PersonalNo, "პირადი ნომერი")
<br />
#Html.EditorFor(model => model.PersonalNo)
</span>
<div class="fieldNameInnerForMIA">
<span>#Html.LabelFor(model => model.DateOfBirth, "დაბადების თარიღი")
<br />
#Html.EditorFor(model => model.DateOfBirth)
</span>
</div>
</div>
<div class="fieldNameForReturnCheckBox">
#Html.LabelFor(model => model.IsIdentified, "სხვა სახელით დაბრუნდა")
#Html.CheckBoxFor(model => model.IsIdentified)
</div>
<div class="saveReturnPerson">
<input type="image" name="submit" id="submit" src="/Content/Resources/SaveGeo.gif" />
</div>
</div>
}
and here is post method which is never called:
[HttpPost]
public ActionResult EditReturnPerson(int id, FormCollection collection)
{ ....
but this method is called when first is loaded:
public ActionResult EditReturnPerson(long parentObjectId, int parentObjectTypeId, bool readOnly = false)
{
....

Mention the method as POST in AjaxOptions
new AjaxOptions { UpdateTargetId = "personListDivforReturnPerson",
HttpMethod ="POST"}
If you do not mention, It will take the Default which is GET.
EDIT : Also If you want to handle it with your own code, You can do it with handwritten JavaScript. Pretty clean and full control.
Get rid of the AjaxBeginForm and use a normal form in your view.
#using(Html.BeginForm())
{
#Html.EditorFor(model => model.FirstName)
#Html.EditorFor(model => model.PersonalNo)
<input type="submit" class="ajaxSubmit" />
}
Now have some javascript to handle the form submit
<script type="text/javascript">
$(function(){
$(".ajaxSubmit").click(function(e){
e.preventDefault();
var item=$(this);
$.post("#Url.Action("EditReturnPerson","YourControllerName")",
item.closest("form").serialize(), function(response){
$("#personListDivforReturnPerson").html(response);
});
});
});
</script>

ბიჭო აქ ვერ გეტყვიან ვერაფერს :D გეუბნები სერვერს მიმართავს და იქ უშლის რაღაცა ხელს. კლიენტის მხარეს ყველაფერი კარგადაა. ეს კიდე მაგარი კაცია, ფორმას უკეთებ სუბმით-ს და default მეთოდი არის პოსტი მაგ დროს.

I found my problem, the problem was [HttpPost] public ActionResult EditReturnPerson(int id, FormCollection collection) { .... in this part, id was int and my id in DB was bigint, so I changed int to long in controller and everything worked, thanks for advice.

Related

Why doesn't my autocomplete work MVC3 Razor Engine

I using code from this blog Autocompletion Textbox in MVC Using jQuery
but my jQuery isn't firing. I suspect its to do with my selector. I am using MVC as well but I don't see how that would make the javascript any different.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManager.Models;
namespace UserManager.Controllers
{
public class UserManagerController : Controller
{
//
// GET: /UserManager/
public ActionResult Index()
{
try
{
var data = new UserManager.Models.UserManagerTestEntities();
return View(data.vw_UserManager_Model_Add_Users.ToList());
}
catch (Exception ex)
{
return View(ViewBag);
}
}
public ActionResult CreateUser()
{
var data = new UserManager.Models.UserManagerTestEntities();
ViewBag.Message = "Create New User";
return View();
}
public ActionResult LookUpGroupName(string q, int limit)
{
//TODO: Map list to autocomplete textbox control
DAL d = new DAL();
List<string> groups = d.groups();
var GroupValue = groups
.Where(x => x.StartsWith(q))
.OrderBy(x => x)
.Take(limit)
.Select(r => new { group = r });
// Return the result set as JSON
return Json(GroupValue, JsonRequestBehavior.AllowGet);
}
}
}
#model UserManager.Models.vw_UserManager_Model_Add_Users
#{
ViewBag.Title = "Create New User";
}
<h2>
CreateUser</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>New User Details</legend>
<div class="editor-label">
#Html.LabelFor(Model => Model.salutation)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.salutation)
#Html.ValidationMessageFor(model => Model.salutation)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.firstname)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.firstname)
#Html.ValidationMessageFor(model => Model.firstname)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.lastname)
#Html.ValidationMessageFor(model => Model.lastname)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.password)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.password)
#Html.ValidationMessageFor(model => Model.password)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.email)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.email)
#Html.ValidationMessageFor(model => Model.email)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.isactive)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.isactive)
#Html.ValidationMessageFor(model => Model.isactive)
</div>
<div class="editor-label">
#Html.Label("Group Name")
<!-- GroupName -->
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.group_name)
#Html.ValidationMessageFor(model => Model.group_name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$("#group_name").autocomplete('#Url.Action("LookUpGroupName")',
{
dataType: 'json',
parse: function (data) {
var rows = new Array();
alert("before loop");
for (var i = 0; i < data.length; i++) {
rows[i] = { data: data[i], value: data[i].group, result: data[i].group }
}
return rows;
},
formatItem: function (row, i, max) {
return row.group
},
width: 300,
highlight: false,
multiple: true,
multipleseparator: ","
});
});
</script>
HTML rendered to browser:
<input name="group_name" class="text-box single-line" id="group_name" type="text" value=""/>
Probably something simple I just cant see it. Any ideas? Thanks!
I don't believe #Html.EditorFor(model => Model.group_name) adds and ID to the element it creates, therefor your selector will not match. You could add an ID like this:
#Html.EditorFor(model => Model.group_name, new { ID = "group_name"})
In addition, if you wan't to select on an ID with jquery it is better to use the ID-selector #group_name instead, unless you actually have a number of elements where the ID actually start with group_name for all of them, and you want to select all of the elements at once.
Update
You use the attribute start with selector input[id^=group_name, and have a typo in it. You are missing the closing ] in your selector. Even so, if you don't intent to select multiple elements that all have ID's that start with group_name, which your markup indicate that you don't. Then you should really use the ID selector instead.
Do a test run with this
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"Scala",
"Scheme"
];
$( "#group_name" ).autocomplete({
source: availableTags
});
});
When using MVC3 Razor this syntax will not work:
$("#postTags").autocomplete('<%=Url.Action("LookUpGroupName",) %>',
This is because Razor Engine doesn't understand WebForms Engine Syntax. Instead I used:
$("#group_name").autocomplete('#Url.Action("LookUpGroupName")',
I used the overloaded method which accepts ActionResult name only. This worked for me but you if your solution is setup differently you might have to supply both Controller and ActionResult arguements.
Finally I was getting error code 500 when my AJAX request was being made. This is because in my LookUpGroupName method I had to refactor this line of code:
return Json(GroupValue);
To:
return Json(GroupValue, JsonRequestBehavior.AllowGet);
My original post has all the correct code for anybodys future reference.

MVC3 custom server-side data annotation validation not working in partial view

I am trying to add custom data validation via data annotations. I am only concerned about server-side validation at this point. Everything I have seen here and elsewhere references client-side validation. I've stripped down all my code, ran a few test cases and I can get this working just fine on a regular view but as soon as the form is in a partial view, the code no longer breaks in the method to override IsValid.
In either case I can see the custom attribute being initialized. When the form is in a regular view I can see the override method being executed upon submitting the form, but when in a partial view the code never gets executed and it goes right to the HttpPost action.
I have spent the better parts of two days trying to figure this out and am at a loss. Any help would be GREATLY appreciated.
Note:
The code below does return the same view when it enters the HttpPost action. I have it like this for testing purposes. I know my override is never getting called from the partial view and thus IsValid is always true.
View showing form where the validation works
#model eRecruitBoard.ViewModels.HomeIndexViewModel
#{
ViewBag.Title = "eRecruitBoard";
}
#*<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>*#
<h2>Login/homepage</h2>
<br /><br />
<div class="errorMessage">
#Html.DisplayFor(m => m.LoginErrorMsg)
</div>
<br />
#using (Html.BeginForm("Index", "Home")) {
<div id="loginControlBox">
<fieldset>
<legend>Welcome to eRecruitBoard</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
<div class="editor-label">
#Html.EditorFor(m => m.Date)
#Html.ValidationMessageFor(m => m.Date)
</div>
<p>
<input type="submit" value="Log In" />
</p>
</fieldset>
</div>
}
<div>
#Html.Action("BlankForm", "TestForm")
</div>
Partial View (these script calls also come in via _Layout, but I had them here for testing as well)
#model eRecruitBoard.ViewModels.TestFormViewModel
<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>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
#using (Html.BeginForm("NewActivity2", "TestForm", FormMethod.Post))
{
<fieldset>
<legend>Test Form</legend>
<br />
#Html.LabelFor(m => m.Date)
#Html.EditorFor(m => m.Date)
#Html.ValidationMessageFor(m => m.Date)
<input id="activityTimelineSubmit" type="submit" value="Submit" />
</fieldset>
}
ViewModel (for partial view)
namespace eRecruitBoard.ViewModels
{
public class TestFormViewModel
{
[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[NonFutureDate()]
[Display(Name = "Date")]
public DateTime Date { get; set; }
}
}
Controller (for partial view)
namespace eRecruitBoard.Controllers
{
public class TestFormController :BaseController
{
public ActionResult BlankForm()
{
var viewModel = new TestFormViewModel
{
Date = DateTime.Today
};
return PartialView("_TestForm", viewModel);
}
[HttpPost]
public ActionResult NewActivity2(DateTime Date)
{
if (!ModelState.IsValid)
return RedirectToAction("Index", "Home");
else
return RedirectToAction("Index", "Home");
}
}
}
Validation code
using System;
using System.ComponentModel.DataAnnotations;
namespace eRecruitBoard.WebLibrary.Validation
{
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public class NonFutureDateAttribute : ValidationAttribute //public sealed class
{
public NonFutureDateAttribute(): base("Activity can only be saved for today or dates in the past.")
{
}
public override bool IsValid(object value)
{
DateTime dateToCheck = (DateTime)value;
return (dateToCheck <= DateTime.Today);
}
}
}
If you RedirectToAction you lose all validation. You have to return PartialView(model) in your POST action. That would require changing the parameter type of NewActivity2 to TestFormViewModel instead of DateTime.
Update your code with example of how you display the partial view (#Html.Partial() or javascript) if it still doesnt work.

Receiving a NullReference Exception error during HttpPost Action when using a ViewModel

I am trying to create what I feel is a very simple form submission using a ViewModel. I have worked on this off and on all day and for some reason cannot understand why when my app gets to my HttpPost action my EmailViewModel is empty. I get a "NullReference Exception Occurred" "Object reference not set to an instance of an object" error.
Can you take a look at my code and tell me where I am being crazy?
Here is my httpPost action:
[HttpPost]
public ActionResult SendStudentAnEmail(EmailViewModel email)
{
Debug.Write(email.Subject); // First NullReferenceException
Debug.Write(email.Body);
Debug.Write(email.Email);
etc. . .
My ViewModel:
namespace MyApp.ViewModels
{
public class EmailViewModel
{
public string Email { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
}
and My View:
#model MyApp.ViewModels.EmailViewModel
#{
ViewBag.Title = "SendStudentAnEmail";
}
<h2>SendStudentAnEmail</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>EmailViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Subject)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Subject)
#Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Body)
#Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Thank you.
*UPDATE*
If I change my HttpPost Action to use FormCollection, I can use the values just fine, I can even re-cast the FormCollection values back to my EmailViewModel. Why is this?
[HttpPost]
public ActionResult SendStudentAnEmail(FormCollection emailFormCollection)
{
Debug.Write(emailFormCollection["email"]);
Debug.Write(emailFormCollection["subject"]);
Debug.Write(emailFormCollection["body"]);
var email = new EmailViewModel
{
Email = emailFormCollection["email"],
Subject = emailFormCollection["subject"],
Body = emailFormCollection["body"]
};
. . . . then the rest of my code works just how I wanted. . .
Why do I have to cast from FormCollection over to my EmailViewModel? Why isn't it giving me the NullReference Exception if I attempt to simply push an EmailViewModel into my Action?
Your EmailViewModel class has a property called Email of type string. And your controller action takes an argument called email of type EmailViewModel. This confuses the default model binder. So either rename the property inside the view model or the action argument:
[HttpPost]
public ActionResult SendStudentAnEmail(EmailViewModel model)
{
Debug.Write(model.Subject);
Debug.Write(model.Body);
Debug.Write(model.Email);
...
}

inconvenient when editing models

I have a problem trying to edit. I work with Areas for better management the application.The problem is in the areas called "Administrator".
Next is the controller code (OfficeControlle), I use a session variable has been previously created and functions to edit the model data I get.
public ActionResult Edit()
{
decimal id;
id = (decimal)Session["consul"];
CAMPUS_UNIVERSITY campus_university = db. CAMPUS_UNIVERSITY.Single(s => s.Idoffice == id);
ViewData.Model = db.OFFICE.Single(c => c.Idoffice == id);
ViewBag.University = db.UNIVERSITY.Single(u => u.IdUniversity == campus_university.IdUniversity);
ViewBag.campus = db.CITY_CAMPUS.Single(u => u.IdCity == campus_university.Idcitycampus);
return View(sede_universidad);
}
[HttpPost]
public ActionResult Edit(CAMPUS_UNIVERSITY campus_university, OFFICE office)
{
if (ModelState.IsValid)
{
db.CAMPUS_UNIVERSITY.Attach(campus_university);
db.ObjectStateManager.ChangeObjectState(campus_university, EntityState.Modified);
db.SaveChanges();
db. OFFICE.Attach(office);
db.ObjectStateManager.ChangeObjectState(office, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.IdCitycampus = new SelectList(db.CITY_CAMPUS, "IdCity", "Name", campus_university.IdCitycampus);
ViewBag.IdConsultorio = new SelectList(db.OFFICE, "Idoffice", "addressoffice", campus_university.Idoffice);
ViewBag.IdUniversidad = new SelectList(db.UNIVERSITY, "IdUniversity", "Name", campus_university.IdUniversity);
return View(campus_university);
}
Next is the view code
#model RolMVC3.Models.CAMPUS_UNIVERSITY
#{
ViewBag.Title = "Edit";
}
<h2>edit</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)
<h2> #ViewBag.University.Name - #ViewBag.Campus.Name </h2>
<fieldset>
<legend>OFFICE</legend>
#Html.HiddenFor(model => model.IdUniversity)
#Html.HiddenFor(model => model.IdCitycampus)
#Html.HiddenFor(model => model.Idoffice)
<div class="editor-label">
#Html.LabelFor(model => model.addresscampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.addresscampus)
#Html.ValidationMessageFor(model => model.addresscampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.phonecampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.phonecampus)
#Html.ValidationMessageFor(model => model.phonecampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.emailcampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.emailcampus)
#Html.ValidationMessageFor(model => model.emailcampus)
</div>
<fieldset>
<legend>OTHER DATE</legend>
#Html.Partial("_office", Model.OFFICE)
</fieldset>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("back", "Index")
</div>
The problem appears when I press the "Save" button, get the following error:
The parameters dictionary contains a null entry for parameter 'Id' of non-nullable type ''System.Decimal' ' for method ''System.Web.Mvc.ActionResult Index(System.Decimal)' in ''RolMVC3.Areas.Administrator.Controllers.OfficeController''
When you are redirecting here:
return RedirectToAction("Index");
make sure that you pass the id in the query string as it looks like your Index action requires it as parameter:
return RedirectToAction("Index", new { id = campus_university.IdUniversity });
I'm assuming that your Index action method looks something like this (please correct me if I am wrong):
public ActionResult Index(decimal id)
{
// Your method's code
}
So where you do return RedirectToAction("Index"); you are trying to redirect to an action method that takes no parameters. But in this case there is an action method that requires a parameter, namely id. So when redirecting you need to change your code and supply this id parameter.
This is what you could do:
return RedirectToAction("Index", new { id = /* put your id here */ });

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);
}
#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.
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);
?>

Resources