Materialize autocomplete with dynamic data in jquery ajax - javascript

I'm using materialize ui in an ASP.Net MVC application and I'm using an autocomplete control with dynamic data.
Here is my code,
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Autocomplete</label>
</div>
</div>
</div>
</div>
This is the jquery ajax call,
$(function () {
$.ajax({
type: 'GET', // your request type
url: "/Home/GetData/",
success: function (response) {
var myArray = $.parseJSON(response);
debugger;
$('input.autocomplete').autocomplete({
data: {
"Arizona (1)": null,
"Florida (2)": null,
"Georgia (3)": null,
"Hawaii(4)": null,
"Idaho (5)": null,
"Illinois (6)": null
}
});
}
});
});
It can accept data only in this format and this is my response,
"[["Arizona (1)"],["Florida (2)"],["Georgia (3)"],["Hawaii (4)"],["Idaho (5)"],["Illinois (6)"]]"
How do I convert my response into the format that autocomplete understands?

Using ajax API call for materializecss input autocomplete
I have modified as below to obtain autocomplete input for Countries.
You can get the list of country names from API https://restcountries.eu/rest/v2/all?fields=name
$(document).ready(function() {
//Autocomplete
$(function() {
$.ajax({
type: 'GET',
url: 'https://restcountries.eu/rest/v2/all?fields=name',
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<label for="country">Autocomplete</label>
<input type="text" id="country" class="autocomplete">
</div>
</div>
</div>
</div>

Good day. I can suggest a little different approach. Materialize autocomplete has method
updateData
So if we want to get ajax to load data, we may add event listener to input field
$(".autocomplete").each(function () {
let self = this;
$(this).autocomplete();
$(this).on("input change", function () {
$.ajax({
url: '/source/to/server/data',
type: 'post',
cache: false,
data: {"some": "data"},
success: function (data) {
data = JSON.parse(data);
$(self).autocomplete("updateData", data/*should be object*/);
},
error: function (err) {
console.log(err);
}
});
});
});
Not ideal for different data sources, but may be a starting point.

Not very fancy, but give it a try:
$(function () {
$.ajax({
type: 'GET', // your request type
url: "/Home/GetData/",
success: function (response) {
var myArray = $.parseJSON(response);
var dataAC = {};
for(var i=0;i<myArray[0].length;i++){
eval("dataAC." + myArray[0][i] + " = null;");
}
debugger;
$('input.autocomplete').autocomplete({
data: dataAC
});
}
});
});

Try to convert your response through this way, in your case you don't need the first line of code.
var responseData = JSON.parse(`[["Arizona (1)"],["Florida (2)"],["Georgia (3)"],["Hawaii (4)"],["Idaho (5)"],["Illinois (6)"]]`);
var acArray = [];
var acData = {};
responseData.forEach(res => {
acArray.push(res.join())
})
acArray.forEach(acObj => {
acData[acObj] = null;
})
console.log(acData)

you can easily achieve the autocomplete functionality using the Devberidge plugin.
Get Devbridge plugin using https://github.com/devbridge/jQuery-Autocomplete
<script type="text/javascript">
$(document).ready(function() {
$("#country").devbridgeAutocomplete({
//lookup: countries,
serviceUrl:"getCountry.php", //tell the script where to send requests
type:'POST',
//callback just to show it's working
onSelect: function (suggestion) {
// $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
showNoSuggestionNotice: true,
noSuggestionNotice: 'Sorry, no matching results',
});
});
</script>
Here the getCountry.php file returns the JSON data.
For more info visit https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php

Related

In ASP.NET Razor Page Jquery Ajax Function not Working

I have a two onchange function for a page called create delivery request. One is when the dropdownlist of receiver changes, then it should show the phone number & address of receiver selected. Another one is when the dropdownlist of delivery item changes, then it should set the max attribute for the quantity.
The url of both these are linked to the customized OnGet method in razor page.
However, usually the above Onget method is hit but the below one is not. And the above OnGet method can't get the dryfood with the passed ID as well, it is null inside. And the two jQuery ajax function doesn't work at all. I'm totally a beginner. Hope that there is someone who can help me. Thanks in advance.
In create.cshtml:
<div class="mb-3">
Receiver Name
<select id="receiver" asp-for="Delivery.ReceiverID" asp-items="Model.ReceiverList" class="form-control">
<option>--Select the Receiever--</option>
</select>
</div>
<div class="mb-3">
Receiver Phone
<span id="receiverphone" class="form-control">----</span>
</div>
<div class="mb-3">
Receiver Address
<div id="receiveradrs1" class="form-control">----</div>
<div id="receiveradrs2" class="form-control">----</div>
</div>
<div class="mb-3">
Delivery Item
<select id="deliveryitem" asp-for="DeliveryItem.DryFoodID" asp-items="Model.DeliveryItemList" class="form-control">
<option>--Select Delivery Item--</option>
</select>
</div>
<div class="mb-3">
Quantity
<input id="quantity" asp-for="DeliveryItem.Quantity" min="1" class="form-control" />
</div>
In create.csthml.cs, two customized OnGet method here:
public async Task<IActionResult> OnGetSetMaxQuantity(int id)
{
List<DryFoodDonation> dfdlist = await _db.DryFoodDonation.ToListAsync();
var dryfood = dfdlist.Where(d => d.Id == id).FirstOrDefault();
Debug.WriteLine(dryfood.DryFoodName + " " + dryfood.DryFoodRemainQuantity);
return new JsonResult(dryfood.DryFoodRemainQuantity);
}
public async Task<IActionResult> OnGetGetPhoneAdrs(int id)
{
List<User> receiverlist = await _db.User.Where(u => u.UserType.TypeID == 3).ToListAsync();
var selectreceiver = receiverlist.Where(d => d.UserID == id).FirstOrDefault();
Debug.WriteLine(selectreceiver.UserName + " " + selectreceiver.UserPhone);
return new JsonResult(selectreceiver);
}
The jQuery AJAX function in a JavaScript file:
$(document).ready(function () {
$("#receiver").change(function () {
alert('Yes receiver here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=GetPhoneAdrs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
'id': item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#receiverphone').html(data.UserPhone);
$('#receiveradrs1').html(data.UserAdrs1);
$('#receiveradrs2').html(data.UserAdrs2);
}
});
});
$("#deliveryitem").change(function () {
alert('Yes item here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=SetMaxQuantity',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"id": item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$("#quantity").attr({
"min": 1,
"max": data
});
}
});
});
});
Please help me with this. I can't solve this problem for a few weeks. Thank you!
// cshtml.cs
const sendMe = async function (someData) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ControllerName/MethodNameInController',
data: { someData: someData },
success: function (response) {
if (response != null && response.statusCode == 200) {
..
} else {
..
}
}
});
}
//Controller
[HttpPost("MethodNameInController")]
public IActionResult MethodNameInController([FromForm] string someData) {
..
}

No data receive in Jquery from php json_encode

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.
My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.
car_detail.js
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
cache: false,
data: { car_rent_id: this.car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
car_detail.php
$car_rent_id = $_GET['car_rent_id'];
$query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour,
c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status,
r.pickup_location
FROM car_rent c
JOIN rental r ON c.car_rent_id=r.car_rent_id
WHERE c.car_rent_id = $car_rent_id");
$users = array();
while($r = mysql_fetch_array($query)){
$user = array(
"car_name" => $r['car_name'],
"car_type" => $r['car_type'],
"car_colour" => $r['car_colour'],
"plate_no" => $r['plate_no'],
"rate_car_hour" => $r['rate_car_hour'],
"rate_car_day" => $r['rate_car_day'],
"car_status" => $r['car_status'],
"pickup_location" => $r['pickup_location']
);
$users[] = $user;
// print_r($r);die;
}
print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]
car_detail.html
<label>ID:</label>
<input type="text" name="car_rent_id" id="car_rent_id"><br>
<label>Car Name:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
</div></br>
<label>Car Type:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
</div></br>
Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
car_rent_id.value = car_rent_id1; // where was this declared?
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
You can also use $.post(), post is just a shorthand for $.ajax()
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
console.log(users);
$('#car_name').val(users.car_name);
});
});
and in your PHP change
$car_rent_id = $_GET['car_rent_id'];
to
$car_rent_id = $_POST['car_rent_id'];
Here is a code skeleton using .done/.fail/.always
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$.ajax({
url: 'theurl',
dataType: 'json',
cache: false
}).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
}).always(function(data){
console.log(data);
});
});
</script>
I've adapted your code, so you can see the error, replace the ajax call with this one
<script>
$.ajax({
url: "theurl",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
},
error: function(data) {
console.log(data);
alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
}
});
</script>
A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

How to Update data to HTML , when an ajax request is being called multiple times

I have a page which lists multiple shops details.For every shop ajax call is being made to get the product details.
function init_product_data(shop_id) {
var uri = parseUri(location.href);
var qs_product = uri.queryKey;
qs_product.device = "desktop";
qs_product.shop_id = shop_id;
qs_product.rows = 3;
$.ajax({
url: search_ajax_product_url_v3,
type: "GET",
data: (qs_product),
dataType: "json",
timeout: 5000,
success: function(result){
// $('#official-product_detail').html('');
$('.official-product_detail').html(buildMicroBrandProductHtml(result));
},
complete: function() {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
Call init_prod_data for each shop:
for (var i=0; i<n; i++){
init_product_data(result[i].shop_id);
}
HTML:
<div class="grid-shop-product pull-right">
<div class="official-product_detail">
</div>
</div>
Problem is that the product details of the last ajax call result are being updated for all shops. How can I update the product detail for each shop inplace when the result is recieved.
Eg:
<div class="grid-shop-product pull-right">
<div class="official-product_detail">
<!-- Products of Shop1-->
</div>
</div>
<div class="grid-shop-product pull-right">
<div class="official-product_detail">
<!-- Products of Shop2-->
</div>
</div>
.
.
.
<div class="grid-shop-product pull-right">
<div class="official-product_detail">
<!-- Products of ShopN-->
</div>
</div>
Basically, you have to loop through each div and then update that current div only with ajax result data.You can try following code in which, I am traversing through each .official-product_detail and passing it as a parameter to the function which further calls ajax and render only the same control with result data.
$(".official-product_detail").each(function(){
init_product_data(shop_id,$(this));
});
function init_product_data(shop_id,control) {
var cn = control; //YOU CAN FIND THE CONTROL IF ITS DEEP INSIDE
var uri = parseUri(location.href);
var qs_product = uri.queryKey;
qs_product.device = "desktop";
qs_product.shop_id = shop_id;
qs_product.rows = 3;
$.ajax({
url: search_ajax_product_url_v3,
type: "GET",
data: (qs_product),
dataType: "json",
timeout: 5000,
success: function(result){
// $('#official-product_detail').html('');
cn.html(buildMicroBrandProductHtml(result));
},
complete: function() {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}

innerHTML.value not working?

I've been trying to write a JavaScript program that returns Wikipedia search results. A few days ago, I got it to the point where I could see the item being searched for, as confirmed by the alert() method, but now when I call the same alert() method it just returns "undefined":
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
I swear that this is exactly what I had while it was working, so there must be some subtle issue elsewhere. Any help is appreciated, complete code below:
HTML:
Random
<section>
<form>
<br>
<div class="divid">
<input type="text" value='' id="test" >
<button >Search</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
JavaScript:
$(document).ready(function () {
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
var button = $('button');
var toSearch = '';
var searchUrl = "http://en.wikipedia.org/w/api.php"
var x="England";
input.autocomplete({
source: function (request, response) {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
'action': "opensearch",
'format': "json",
'search': request.term
},
success: function (data) {
response(data[1]);
}
});
}
});
var playListURL = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?';
$.getJSON(playListURL ,function(data) {
$.each(data.query.pages, function(i, item) {
//alert(item.title);
})
})
$.ajax({
//http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: "Carl Sagan", format: 'json' },
dataType: 'jsonp',
success:
function (x) {
//alert( x.query.search[0].title);
}
});
})
Use .innerHTML to get the html in a DOM element
Use .value to get the value of an input, textarea, or other form input
.innerHTML.value is not a thing.
If you are using jQuery, try this:
var search = $("#test").html();
alert(search);

Knockout.js Adding data by using push method not updating view

I'm getting data from WebApi on JSON format and then adding received data to MVC View by using .push() method of KnockoutJS. The JSON data I received on POST response is correct, so I believe it's something wrong on client side - instead of data I'm geting undefined and [Object].
Although after page refresh all data showing correctly.
Here my knockout code:
<script>
var viewModel = {
prepp: ko.observableArray(),
currentPage: ko.observable(-1)
};
$(function () {
getData(viewModel.currentPage() + 1);
ko.applyBindings(viewModel, document.getElementById("prepps"));
});
//This function used for paging, not concern to question directly
function getData(pageNumber) {
if (viewModel.currentPage() != pageNumber) {
$.ajax({
url: "/api/index",
type: "get",
contentType: "application/json",
data: { id: pageNumber }
}).done(function (data) {
if (data.length > 0) {
viewModel.currentPage(viewModel.currentPage() + 1);
for (var i = 0; i < data.length; i++) {
viewModel.prepp.push(data[i]);
}
}
});
};
//Here we call POST action of WebApi.
$(".send-feed").click(function () {
var guid = getguid();
var styles;
var req = { RequestName: $("#request").val(), RequestDescription: $("#request-review").val(), RequestOwner: $("#username").val(), RequestGuid: guid, RequestStyles: [] }
$("div.click").each(function () {
styles = { RequestGuid: guid, StyleId: $(this).text() };
req.RequestStyles.push(styles);
});
var model = JSON.stringify(req);
$.ajax({
url: "/api/index",
type: "POST",
contentType: "application/json, charset: utf-8",
data: model
}).done(function (data) {
viewModel.prepp.push(data);
});
});
}
});
</script>
And here is the MVC View markup:
div class="prepp-blocks-container" data-bind="foreach: prepp" id="prepps">
<div class="prepp-block">
<div class="star" data-bind="if: $data.IsStylistOffer == true">
<img src="../../img/star-yellow.png" alt="added by stylist">
</div>
<a data-bind="attr: {href: 'Request/' + $data.RequestGuid}"><h3 data-bind="text: $data.RequestName"></h3></a>
<span data-bind="foreach: {data: RequestStyles, as: 'style'}">
<div data-bind="text: style" class="taste-prepp"></div>
</span>
<p class="text-small-grey" data-bind="text: $data.PreppsNumber + ' prepps'"></p>
</div>
</div>
I believe your return type from controller should be adjusted so it will match the view model structure like
public model Get()
{
//build your list .
return model ;
}
Try to use ko.mapping.toJS() so knockout advantages are not lost .
Refer knockout doc's you can find more relevant info how we can better use it Here

Categories

Resources