In my project, I am trying to create a autocomplete effect using the following plugin:
Devbridge jQuery Autocomplete
This plugin is working fine until I don't add space into my textbox (after adding a word). and when I just delete the entered word using backspace then the autocomplete is showing the previous list which should have shown before.
PS: Every time I am passing the full text of the text field to server through ajax call which is necessary in my application.
Here is my code:
JS Fiddle (not working because of ajax url)
JS
$(function () {
var result = $('#result');
var contents = {
value: "",
data: ""
};
/* Ajax call */
result.keydown(function (event) {
if (!event.shiftKey) {
var sugData;
var text = result.val(); //.split(" ").pop();
//console.log(text);
/* Send the data using post and put the results in a div */
$.ajax({
url: "http://localhost:9999/projects/1/autocomplete/suggestions",
type: "POST",
data: "drqlFragment=" + text, // + " ",
//data: "drqlFragment=when node_database_property ",
async: false,
cache: false,
headers: {
accept: "application/json",
contentType: "application/x-www-form-urlencoded"
},
contentType: "application/x-www-form-urlencoded",
processData: true,
success: function (data, textStatus, jqXHR) {
var resData = data.suggestions;
//console.dir(resData);
for (var i = 0; i < resData.length; i++) {
resData[i].value = resData[i].keyword;
}
sugData = resData;
//console.dir(sugData);
},
error: function (response) {
//console.dir(response);
$("#result").val('there is error while submit');
}
});
console.dir(sugData);
$('#result').autocomplete({
lookup: sugData
});
}
});
});
HTML
<form id="foo">
<textarea id="result" rows="4" cols="50"></textarea>
<input type="submit" value="Send" />
</form>
Sorry, I can't provide you the json data because it is being modified by the server whenever I press a key. (So, actually it is an object variable returning by the server on ajax call).
Related
I have a text area with id "text" and I am toggling the text area to appear on the screen with a click event on some div and I have 30 such divs. Initially , I'm assigning the textarea.value with result of ajax call to my fetch api which fetches the data from the mongo on the server side based on an unique id.
Sometimes , when I'm making the ajax call to my update api in my backend , the textarea.value I'm sending as data to this ajax call is not the same as the updated text of the text area.
//client side
// called when any of the divs is clicked
$(".radius").on("click", function(event) {
//extracting the id from the class and using this id as the id of my data for my mongo
var st=event.target.classList[1].substring(0,7);
var num=parseInt(event.target.classList[1].substring(7));
var toadd="close-button"+num;
//console.log(num+"modal")
closeButton.classList.add(toadd);
$.ajax({type: "POST",
url: "/fetch",
async: true,
data: JSON.stringify({
id: num,
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
input.value=result.text;
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
});
// called when textarea is closed
function toggleModal1(event) {
var s1=closeButton.classList[closeButton.classList.length-1];
var st=s1.substring(12);
closeButton.classList.remove(s1);
var num=parseInt(st);
// event.preventDefault();
console.log(input.value)
$.ajax({type: "POST",
url: "/update",
data: JSON.stringify({
id:num,
text:input.value,
//input is my textarea
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
}
//server side
app.post("/fetch",function(req,res)
{
//console.log(req.body);
// var id1=req.body.id;
const findInDB= Fruit.findOne({id:req.body.id},function (err, docs) {
console.log(docs);
res.send({text:docs.text});
});
});
app.post("/update",function(req,res)
{
Fruit.updateOne({id:req.body.id},
{text:req.body.text}, function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Updated Docs : ", docs);
}
});
I tried debugging my code but couldn't reason out the contents of my console.
You are referencing input in your client side code, but I don't see it anywhere in the code. Can you check?
Update:
the textarea.value I'm sending as data to this ajax call is not the
same as the updated text of the text area.
I assume that you have an error in the code related to input. If you can add it to your answer, it will be easier to help you.
I need this ajax call to run my onpost handler PassPart. It successfully calls it, but my parameter "searchedpart" is always empty. I've also tried passing the parameter directly in my url, like: "?handler=passPart" + "&searchedpart=" + searchedpart , but it's still empty. Lastly, I've tried using "Request.Form[SearchedPart]" in my method to pull the value in, also empty. I've tested that this element is not empty by adding an alert message to my js to confirm, and I see the value being found.
ps. I'm using an EmptyResult because I don't need anything posted back. I simply need it to run through my handler using the parameter.
<form method="post">
<input class="form-control" name="searchedpart" asp-for="PostData.SearchedPart" value="#Model.PostData.SearchedPart" id="searchedpart" />
<button type="submit" id="searchpartbtn" class="btn btn-success btn-sm">Find</button>
</form>
document.getElementById('searchpartbtn').addEventListener('click', PassPart);
var searchedpart = document.getElementById('searchedpart').value;
function PassPart() {
$.ajax({
type: "POST",
url: "?handler=passPart",
dataType: "json",
data: JSON.stringify({ searchedpart: searchedpart }),
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
}
});
}
public ActionResult OnPostPassPart(string searchedpart = "")
{
if (searchedpart != "") {
// Do Things
}
return new EmptyResult();
}
Because searchedpart is already a string type, there is no need to JSON.stringify.And you should write your var searchedpart = document.getElementById('searchedpart').value;code inside your function.
Just change your code as below:
document.getElementById('searchpartbtn').addEventListener('click', PassPart);
function PassPart() {
var searchedpart = document.getElementById('searchedpart').value;
$.ajax({
type: "POST",
url: "?handler=PassPart",
dataType: "json",
data: { "searchedpart": searchedpart },
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
}
});
}
In your background:
public ActionResult OnPostPassPart(string searchedpart)
{
//...
}
Result:
I ended up using the following in my method to get this working:
string part = Request.Form["SearchedPart"];
remove dataType: "json"
Add header token
I have tried to ajax using post to jsp script my html table rows for weeks now with no success.Can anyone please guide me on this?Below is what I have done so far.
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
$('#notSoCoolGrid > tr').each(function(event) {
event.preventDefault();
var postData = {
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
};
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData.$('input, select').serialize() ,
success: function(msg){
alert("submitted");
}
});
});
});
If I correctly understand your need, you want to transmit the content of your rows, each in the form showed in your current postData.
So this can be made at once for all rows (instead of ajaxing successively each of them).
It might be something like this:
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
event.preventDefault();
var postData = [];
$('#notSoCoolGrid > tr').each(function(event) {
postData.push(
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
);
});
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData,
success: function(msg){
alert("submitted");
}
});
});
});
Note that I choosed (the simplest way, IMO) to make a simple array of rows, where each one is an object like you already structured them.
Last point: I notice you specified async: false.
I don't know why you did that, and so I kept it unchanged.
But note that it's not recommended, and is being on the road to become deprecated.
I finally was able to solve this issue,for that I want to post my answer it might be helpful for someone out there.My previous code was submitting a form before even ajax call being triggered and I have to use Classes instead of IDs to identify my rows.I had to change the code completely to be able to submit the form
$('#btn').click(function(e) {
e.preventDefault();
$('#notSoCoolGrid tr').each(function(i, tr) {
var postData = {
paymentId : $('.paymentId', tr).val(),
id : $('.deald', tr).val(),
pType:$('.pType', tr).val(),
pAmt:$('.pAmt',tr).val(),
currency:$('.currency',tr).val(),
pInvDate:$('.pInvDate',tr).val(),
pRecDate:$('.pRecDate',tr).val(),
comments:$('.comments',tr).val()
}
$.ajax({
async: false,
type: "post",
url: "/update_deal_pmt_script.jsp",
data: postData
})
.done(function(response) {
console.log(response);
})
.fail(function(x, status, error) {
alert("Error: " + error);
});
});
});
My requirement is to show few options when user input some characters (minimum 3) in one of input field which might be added dynamically too.
I can not load data at page loading at beginning because data is huge. There is an ajax call to get that filtered data.
The issue what I am getting is Expected identifier error on page loading at line# 2. So, could you please tell what is wrong with the below code?
$(document).on('keydown.autocomplete', 'input.searchInput', function() {
source: function (request, response) { // Line # 2
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getNames.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
How about using another approach: initialize the autocomplete when you create the input:
$(function() {
// settings for each autocomplete
var autocompleteOptions = {
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "getNames.html",
data: { name: request.term },
success: function(data) {
response(data);
}
});
}
};
// dynamically create an input and initialize autocomplete on it
function addInput() {
var $input = $("<input>", {
name: "search",
"class": "searchInput",
maxlength: "20"
});
$input
.appendTo("form#myForm")
.focus()
.autocomplete(autocompleteOptions);
};
// initialize autocomplete on first input
$("input.searchInput").autocomplete(autocompleteOptions);
$("input#addButton").click(addInput);
});
<form id="myForm" name="myForm" method="post">
<input id="addButton" type="button" value="Add an input" />
<input name="search" class="searchInput" maxlength="20" />
</form>
jsFiddle with AJAX
The method where I am adding new input field there writing below code.
function addInput(){
// Code to append new input filed next to existing one.
$("table").find('input[id=clientId]:last').autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
}
And some where in other js which will be used to all other (static) input fields below code is used.
jQuery("input.searchInput").autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
Note :- For any autocomplete requests in dynamically added input fields, AutoComplete code of addInput() function will be called.
Thanks to #Salman and this post Enabling jQuery Autocomplete on dynamically created input fields to give me an idea.
Try this.
$("#autocompleteElement").autocomplete({
source:function (data, response) {
$ajax({
url:'your/url?name='+data.term,
success:function(data){
response(data);
}
})
}
});
This code based on jquery UI autocomplete.
I've got the following problem. Here is the input I want to validate
<input type="text" name="vatid" data-parsley-remote data-parsley-remote-validator='vatid'/>
and this is the asyncValidator
$('[name="vatid"]').parsley()
.addAsyncValidator('vatid', function (xhr) {
return 404 === xhr.status;
}, confighandler.getConfig().apiUrl + '/checkvatids');
My problem is, that also if the user doesn't enter a value parsley sends an request (on form submit) to the api and then the errors-mesage are triggered. How can I avoid this and only validate if the user has entered something?
Update
big thanks to milz, I've got the following solution and it works like charm :)
define([
'jquery',
'confighandler',
'requirejs-i18n!nls/labels',
'parsleyjs'
], function($, confighandler, Labels) {
'use strict';
return {
initialize: function() {
// add custom validators
window.ParsleyValidator
.addValidator('vatid', function(val) {
var isvalid;
$.ajax({
url: confighandler.getConfig().apiUrl + '/checkvatids/' + val,
dataType: 'json',
type: 'get',
async: false,
success: function(response) {
isvalid = (response.result.data.isvalid === 'true') ? true : false;
},
error: function() {
isvalid = false;
}
});
return isvalid;
}, 32).addMessage('de', 'vatid', Labels.validation.vatid);
}
};
});
You can accomplish that, but you can't use ParsleyRemote. The problem with remote validators is that you cannot verify if the value is empty or not before the remote ajax call is made.
A possible solution to this issue is adding a custom validator with .addValidator and then place an ajax call.
In this case you don't even need to check if the input has any content because the validator is only executed when the input is not empty.
<input type="text" name="vatid" data-parsley-vatid />
<script>
$(document).ready(function() {
window.ParsleyValidator
.addValidator('vatid', function (value, requirement) {
var response = false;
$.ajax({
url: confighandler.getConfig().apiUrl + '/checkvatids',
data: {vatid: value},
dataType: 'json',
type: 'get',
async: false,
success: function(data) {
response = true;
},
error: function() {
response = false;
}
});
return response;
}, 32)
.addMessage('en', 'vatid', 'Vatid is invalid.');
});
</script>
You can also check the following question that can provide adicional information: Parsley.js Trigger Error on AJAX