Autocomplete (JqueryUI) returning blank - json

I'm doing assignment, and essentially what I would like to do it have an autocomplete on the input box so the user can select a 'Starter' and 'Main' from a JSON file. When inputting characters, a dropdown list is displayed, but it is not populated with values.
The JSON file (spanish.php) is:
([{"course":"starter","name":"Chorizo Sausage Rolls","price":"5.99"},{"course":"starter","name":"Sardines in Lemon Sauce","price":"6.99"},{"course":"starter","name":"Spanish Tortilla","price":"5.99"},{"course":"starter","name":"Escabeche","price":"4.99"},{"course":"main","name":"Seafood Paella","price":"13.99"},{"course":"main","name":"Albondigas Soup","price":"9.99"},{"course":"main","name":"Linguine with Mussels","price":"13.99"},{"course":"main","name":"Spanish Rice with Shrimp","price":"11.99"},{"course":"main","name":"Roasted Red Pepper Salad","price":"8.99"},{"course":"main","name":"Chorizo Fritatta","price":"10.99"},{"course":"main","name":"Lamb Meatballs","price":"12.99"}]);
Here is my code:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script type="text/javascript">
$( function() {
$( "#starter" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
} );
},
minLength: 2,
} );
} );
</script>
And the HTML:
<label for="starter">Choose starter</label>
<input type="text" name="starter" id="starter"><br>
<label for="main">Choose main</label>
<input type="text" name="main" id="main"><br>
As I said, the list is returning nothing when 2+ digits are entered. Do I need to ask for it just starters? Am I goin about this correctly? I will be asking the user to choose a starter and main, then submitting the form.
Thanks.

I'm giving here a solution for auto-completing the starter menu. Hope that you can do the same for main menu searching. Or comment in this answer, if you're facing any problem implementing this.
<!doctype html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
var starterSearchData;
$(function() {
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
dataType: "jsonp",
async: false,
success: function(data) {
starterSearchData = $.map(data, function(item) {
if (item.course == "starter")
return item.name;
});
EnableAutoComplete();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function EnableAutoComplete() {
$("#starter").autocomplete({
source: starterSearchData,
minLength: 2,
delay: 100
});
}
});
</script>
</head>
<body>
<label for="starter">Choose starter</label>
<input type="text" name="starter" id="starter">
</body>
</html>

Related

Send data to another javascript library with vue

With vue, I create a json file with classic asp from Sql Server and import the data. My goal is to place the data I have received on the page and in apexCharts.
The html page I used, getData.js and json from dataSql.asp is as follows.
index.html
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="vue.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<style> textarea { position: fixed; right: 0; top: 0; width: 300px; height: 400px; } </style>
</head>
<body>
<div id="app">
<form id="urlParameterForm">
<input type="date" name="startDate" id="startDate" />
<input type="date" name="endDate" id="endDate" />
<input
type="number"
name="pageNumber"
id="pageNumber"
value="1"
v-on:input="changePage"
/>
<input
type="button"
value="Filter"
id="Filter"
v-on:click="changeFilter"
/>
<p>Page : {{ pageActive }}</p>
</form>
<h3>{{title}}</h3>
<div v-for="dta in dataTable.sqlData">
Height: {{dta.height}}, Type: {{dta.type}}
<ul v-for="dta in dataTable.sqlData.graphData">
<li>{{dta.categorie}} - {{dta.serie}}</li>
</ul>
</div>
<textarea>
{{dataTable}}
</textarea>
</div>
<script src="getData.js"></script>
</body>
</html>
getData.js
const app = new Vue({
el: "#app",
devtools: true,
data: {
dataTable: [],
pageNumber: 1,
pageActive :0,
title:'Graph-1'
},
computed: {
url() {
return './dataSql.asp?pg=' + this.pageNumber
}
},
methods: {
changePage: function (event) {
console.log('Change Page',this.pageNumber);
this.pageNumber = event.target.value;
this.init();
},
changeFilter: function (event) {
console.log('Change Filter');
this.init();
},
init() {
let that = this;
console.log('init call');
$.ajax({
type: "POST",
url: that.url,
data:{
startDate:$('#startDate').val(),
endDate:$('#endDate').val(),
pageNumber:$('#pageNumber').val()
},
success: function (data) {
console.log('data remote call');
console.log(data.sqlData);
that.dataTable = data.sqlData;
}
});
}
},
mounted() {
this.init()
}
})
dataSql.asp response json
[
{
"height": 350,
"type": "bar",
"graphData": [
{
"categorie": "Bursa",
"serie": 4
},
{
"categorie": "Tekirdağ",
"serie": 3
}
]
}
]
When I run the page, the screen calls the data like this and I see the data coming as json.
Under the graph-1 text, the does not show anything as if I have never written this. But I can print json text in the text field as it appears in the upper right corner.
<div v-for="dta in dataTable.sqlData">
Height: {{dta.height}}, Type: {{dta.type}}
<ul v-for="dta in dataTable.sqlData.graphData">
<li>{{dta.categorie}} - {{dta.serie}}</li>
</ul>
</div>
<textarea>
{{dataTable}}
</textarea>
I actually want to assign this data, which I could not show on the page, to x and y variables here.
I need something like the following.
categories: app.dataTable.graphData.categorie;
series: app.dataTable.graphData.serie;
var barBasicChart = {
chart: {
height: 350,
type: 'bar',
},
plotOptions: {
bar: {
horizontal: true,
}
},
dataLabels: {
enabled: false
},
series: [{
data: [4,3] /* vue - json - graphData.serie */
}],
xaxis: {
categories: ['Bursa','Tekirdağ'], /* vue - json - graphData.categories */
},
fill: {
colors: $themeColor
}
}
// Initializing Bar Basic Chart
var bar_basic_chart = new ApexCharts(
document.querySelector("#denemeGrafik"),
barBasicChart
);
bar_basic_chart.render();
Vue seems to have not been developed for a long time. I'm new to vuede too. My goal is to automatically generate html content from json. To change the variables of the scripts I have used (such as apexcharts, xGrid etc.).
Can you suggest if there is another javascript library that I can do these things with?
Except for React and Angular because these two are hard to understand and write.
Your AJAX callback assigns dataTable to data.sqlData:
$.ajax({
//...
success: function (data) {
that.dataTable = data.sqlData;
}
})
Then, your component tries to render dataTable.sqlData, but sqlData was already extracted in the AJAX callback (dataTable is an Array):
<div v-for="dta in dataTable.sqlData">
^^^^^^^ ❌
Solution: You can either update the AJAX callback to return the full response (including sqlData):
$.ajax({
//...
success: function (data) {
that.dataTable = data;
}
})
...or update the template to not dereference sqlData, using dataTable directly:
<div v-for="dta in dataTable">

a form inside another and ajax

hello I have the following code that tries to show the field "name" in the div "target2", but for this I use a form within another form I think is the problem. But I don't see a way to fix it.
index.php
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<form method="post" id="fuera">
<div id="target1">
</div>
<button type='button' id="botonFuera">EnviarElDeFuera</button>
</form>
<div id="target2">
</div>
</body>
</html>
otro.php
<form method="post" id="dentro">
<input type='hidden' id='nombre' name='nombre' value='hola'>
<button type='button' id="botonDentro">EnviarElDeDentro</button>
</form>
otroMas.php
<?php
echo($_POST["nombre"]);
?>
ajax.js
(document).on('ready',function(){
$('#botonFuera').click(function(){
var url = "otro.php";
$.ajax({
type: "POST",
url: url,
data: $('#fuera').serialize(),
success: function(data)
{
$('#target1').html(data);
}
});
});
$(document).on('click',':button', function (evt) {
if(this.id=='botonDentro')
{
var url = "otroMas.php";
$.ajax({
type: "POST",
url: url,
data: $('#dentro').serialize(),
success: function(data)
{
$('#target2').html(data);
}
});
}
});
});

Why input value is NULL when using Ajax?(ASP.NET CORE)

I do not have access to input values when using Ajax in View(MVC) but I have access to input values when not use Ajax. actually values is empty when use Ajax
When I use Ajax:
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<input type="reset" value="send" id="ajax-button" class="btn btn-success btn-sm waves-effect waves-light submit-btn" />
</form>
Script:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
var data = $('#Form1').serialize();
$('#ajax-button').click(function () {
debugger
$.ajax({
type: "POST",
data: data,
url: url,
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
I added tag helpers
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, SmsWebClient
#using Microsoft.AspNetCore.Razor.TagHelpers;
Value is null before enter to ajax ,image:
Please Move the
var data = $('#Form1').serialize();
to below
$('#ajax-button').click(function () {
In fact, your code should be:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
$('#ajax-button').click(function () {
var data = $('#Form1').serialize();
debugger
$.ajax({
type: "POST",
data: data,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
In your code data set when docuement loaded and for this reason the value
is null
You must write like this
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<div class="form-group">
<button id="ajax-button">Submit</button>
</div>
</form>
And This ViewModel
public class RegisterVm
{
public string Name { get; set; }
public string Number { get; set; }
}
And finally this is the Ajax code
#section Scripts{
<script>
$(document).ready(function () {
var url = $('#Form1').attr("action");
var model = $('#Form1').serialize();
var token = $('input[name=__RequestVerificationToken]').val();
model.__RequestVerificationToken = token;
$('#ajax-button').click(function () {
$.ajax({
type: $('#Form1').attr("method"),
data: model,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
}
Your data are set when docuement loaded, it will not pass the value which you enter.
For a working demo, try code below:
<script>
$(document).ready(function () {
$('#ajax-button').click(function () {
var url = '#Url.Action("Register", "Home")';
var data = new FormData();
data.append('Name', $('#Name').val());
data.append('Number', $('#Number').val());
$.ajax({
type: "POST",
data: data,
url: url,
processData: false,
contentType: false,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>

How to fix ReferenceError: X is not defined

I am getting an error that shows my function "loaddata" is not defined. However, I have placed the script at the top of the page with no success. Any ideas why this is happening?
Thank you!
<script type="text/javascript">
function loaddata(){
var sid = document.getElementById("student_id");
if(sid) {
$.ajax({
type: 'post',
url: 'search.php',
data: {
student_id:sid,
},
success: function (response) {
// We get the element having id of display_info and put the response inside it
$( '#display_info' ).html(response);
}
});
}
else
{
$( '#display_info' ).html("Please Enter Some Words");
}
}
</script>
</head>
<body>
<div class="content">
<H2>Lookup Member</H2>
<input type="text" name="student_id" id="student_id" onkeyup="loaddata();">
</div>
</body>
Work for me in a single html file.
I comment your jquery code just for test.
<head>
<script type="text/javascript">
function loaddata() {
var sid = document.getElementById("student_id");
if (sid) {
// $.ajax({
// type: 'post',
// url: 'search.php',
// data: {
// student_id: sid,
// },
// success: function(response) {
// // We get the element having id of display_info and put the response inside it
// $('#display_info').html(response);
// }
// });
} else {
$('#display_info').html("Please Enter Some Words");
}
}
</script>
</head>
<body>
<div class="content">
<H2>Lookup Member</H2>
<input type="text" name="student_id" id="student_id" onkeyup="loaddata();">
</div>
</body>

JQuery Autocomplete Never Fires

I have an html page where I am trying to link an input box to an ajax autocomplete function. The problem is the function is not being called, for either success or failure.
If I change 'autocomplete' to 'keypress' it gets called, but it's not what I'm looking for.
Here is the page:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<link rel="stylesheet" href="~/Scripts/jquery-ui.css">
<script>
$(document).ready(function () {
$("#search-box").autocomplete(function () {
$.ajax({
type: "POST",
url: "http://localhost:52139/odata/WEB_V_CIVIC_ADDRESS?",
data: { enteredText: +$(this).val() },
dataType: 'json',
ContentType: "application/json, charset=UTF-8",
success: function (data) {
$("#suggesstion-box").show();
$("#suggesstion-box").html(data);
$("#search-box").css("background", "#FFF");
},
error: function (data, xml, errorThrown)
{
alert("here: " + errorThrown);
}
});
});
});
//To select country name
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmSearch">
<input type="text" id="search-box" placeholder="Country Name"
autocomplete="on"/>
<div id="suggesstion-box"></div>
</div>
</body>
</html>
So like I said, the ajax function never fires. If I use 'keypress' it does, but I need it to fire for autocomplete.
Any ideas?
Thanks.
Looks like jquery-ui wasn't being loaded properly. Thanks j08691 for the tip.