laravel - datatables implement ajax on enter key pressed - javascript

As Im using datatables and have one cluomn countains input text, so I want to get some data on this input field using ajax and only on Enter key pressed,
I tried many sloutions but not working with me, if I used on blur or focusout working fine but need this to be only on enter
datatable:
{data: 'vendor_name', name: 'vendors.vendor_name',mRender: function (data, type, row) {
return '<input type="text" id="vendor_name"
class="vendor_name" data-id="'+row.id+'" onkeydown="myFunction(event)"
onClick="this.select();" value="'+data+'">';}},
javascript
<script type="text/javascript">
function myFunction(event) {
var x = event.keyCode;
var id = $(this).data("id");
var $row = $(this).closest('tr');
if (x == 13)
{
$.ajax({
type: 'POST',
url: 'Vendor_Save',
data: {
'_token': $('input[name=_token]').val(),
'currentid': id,
'current_vendor_name':$(this).val(),
},
success: function(data) {
$row.closest('tr').find('.category_name').val(data.categoryname);
$row.closest('tr').find('.vendor_no').val(data.vendorid);
}
});
}
};
</script>

I would recommend using axios, or even vue js instead of pure ajax!
What you can do is set a event listener on input of your field and use keyup to fire the request.
var input = document.getElementById("idofyourinput");
input.addEventListener("keyup", function(){
alert("KeyUp"); // Take out after testing
$.ajax({
type: 'POST',
url: 'Vendor_Save',
data: {
'_token': $('input[name=_token]').val(),
'currentid': id,
'current_vendor_name':$(this).val(),
},
success: function(data) {
var row = $(input).closest('tr');
$row.closest('tr').find('.category_name').val(data.categoryname);
$row.closest('tr').find('.vendor_no').val(data.vendorid);
}
});
});
<input type="text" id="idofyourinput"/>

Related

jQuery ajax input field event, options list and setting a value

I am trying to create an AJAX function to autocomplete the input field.
The user starts typing in location/city name, and it should trigger an AJAX call for lookup, presenting suggestions of matching city names list to the input field. Then the user selects one value and that is set to that input field. The below code doesn't even trigger events, I do not see request activity on the network. How to accomplish this?
$(function() {
$('#locationName').keyup(function() { //tried keyup, input
alert('Ok'); // to test event
$.ajax({
type: 'POST',
url: '/locationsearch',
data: {
'search_text': $('#locationName').val()
},
success: searchSuccess,
dataType: 'text'
});
});
});
function searchSuccess(data) {
locationName.val = 'data';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="locationName" id="locationName">
Your example does not seem complete. It's not clear where locationName is defined. Consider the following snippet.
$(function() {
function searchLoc(txt) {
var result = "";
$.post("/locationsarch", {
"search_text": txt
}, function(data) {
result = data;
});
return result;
}
$('#locationName').keyup(function() {
var q = $(this).val();
if (q.length >= 3) {
$(this).val(searchLoc(q));
}
});
});
It's not clear what the resulting data will be, I am assuming text or HTML.

How to use script to get searched value in php

I am trying to make search button:
<input type="text" name="searchme" id="searchme" onkeydown="searchme()" />
<input type="button" value="SearchMe" />
I want to get all data from table if textbox is empty else myFunction() will be execute and search.
<script>
function searchme() {
var searchvalue;
searchvalue = document.getElementById('search_id').value;
alert(searchvalue);
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: value }
})
}
</script>
is there any problem with script? What should I add?
Your code is looks fine to me. You just need to add success for fetching results.
HTML
<input type="text" name="searchme" id="searchme" onkeyup="searchme()" />
Change onkeydown to onkeyup. because on key the you are not able to get the value.
include jQuery in <head> of your html
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
now JS
function searchme() {
var searchvalue;
searchvalue = $('#searchme').val();
alert(searchvalue);
var table = "table_name";
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: searchvalue, revanue: table},
success: function (result)
{
$(".resultDiv").html(result);
}
})
}
Where .resultDiv is the div where you want to show the result. and remove ' from searchvalue and revanue.
I would do it like this. Since you're using jquery. Might as well use it everywhere.
<input type="text" name="searchme" id="searchme" />
Then your JS
$('#searchme').keyup(function(){
var search = $(this).val();
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: search},
success: function (data)
{
$(".results").html(data);
}
})
});
But also...you probably dont want your script firing on every keystroke. Instead you should wait a fraction of a second between strokes, to only fire the request when the user is actually done typing.
So like this...
// The delay function
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#searchme').keyup(function() {
var search = $(this).val();
delay(function(){
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: search},
success: function (data)
{
$(".results").html(data);
}
})
}, 800 );
});
EXAMPLE HERE

Check the value of a text input field with ajax

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.

Jquery insert error message returned by PHP via Json

I'm trying to submit a form via AJAX.I send my form to PHP which return error messages if there are via Json.
If there are no error, the code work well. But if not... I cannot insert error message. I don't understand why.
Here is what I would like to do :
function addWishlist(){
var formdata = $("#addwishlist").serializeArray();
$.ajax({
url: "/Shawili/<?= $profile['username'] ?>/addwishlist/",
data: formdata,
type: 'POST',
dataType: 'json',
success: function(json){
if(json.valid == 'ok') {
$('#addwishlist').each(function(){
this.reset();
});
} else {
$.each( json, function( key, value ) {
$('#'+key).before('<div class="row"><div class="col-sm-offset-2 col-sm-5"><span class="label label-danger">' + value + '</span></div></div>');
});
}
}
});
}
This code is working :
function addWishlist(){
var formdata = $("#addwishlist").serializeArray();
$.ajax({
url: "/Shawili/<?= $profile['username'] ?>/addwishlist/",
data: formdata,
type: 'POST',
dataType: 'json',
success: function(json){
if(json.valid == 'ok') {
$('#addwishlist').each(function(){
this.reset();
});
} else {
$.each( json, function( key, value ) {
alert(key +':'+ value);
});
}
}
});
}
This code is'nt :
function addWishlist(){
var formdata = $("#addwishlist").serializeArray();
$.ajax({
url: "/Shawili/<?= $profile['username'] ?>/addwishlist/",
data: formdata,
type: 'POST',
dataType: 'json',
success: function(json){
if(json.valid == 'ok') {
$('#addwishlist').each(function(){
this.reset();
});
} else {
$('#title').html('<p>test</p>')
}
}
});
}
The html form is shown via AJAX because I'm using a tabs system. (Each tab is loaded via AJAX when user click on it) The JS script is located at the end of the layout.
Here is a part of the form :
<div id="title" class="form-group"><label class="col-sm-2 control-label" for="title">Title</label>
<div class="col-sm-4">
<input type="text" placeholder="" name="title" class="form-control"></div></div>
However, when I use Firebug I can see the changes in the html structure but nothing appends in the page.
Here is my tab loading function :
$('#myTabs a').click(function (e) {
e.preventDefault();
var url = $(this).attr("data-url");
var href = this.hash;
var pane = $(this);
// ajax load from data-url
$(href).load(url,function(result){
pane.tab('show');
});
});
And here is Firebug screenshot :
Try to bind first in another not DOM element, something like this:
$('#otherDivContent').find('#title').html('<p>test</p>');
Where #otherDivContent is a div(or other element) that you have initially on your page.

On change event inside hidden input field

I have two AJAX functions. First function takes the result of the first input field and concatenates a string and then changes the value of the second input field. The second input field is (type=”hidden”). Second function checks if there was a change triggered in the second input field and then display the value on the third input field. Nothing is being triggered by the change of value made in input field # 2. Example
<script>
$(document).ready(function () {
var timer = null;
var $result=$("#result");
$result.data('url',$result.val());
function submitForm( input ) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
var url=$result.data('url'),
newUrl= url+input+'/';
$result.val(newUrl);
}
});
return false
}
$("#input").on("keyup", function() {
var input = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){
submitForm(input) ;
}, 40);
})
});
$(document).ready(function () {
var timer = null;
var $result=$("#result").val();
function submitForm( input ) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
$result.val();
}
});
return false
}
$("#result").on("change", function() {
var input = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){
submitForm(input) ;
}, 40);
})
});
</script>
</head>
<body>
<h1>Enter a word:</h1>
<form action="index.php" method="post">
Input: <input type="text" id="input" name="input"></br>
Concatenated Result1(hidden): <input type="hidden" style="width:200px;" id="result" name="result" value="http//www.example.com/"></br>
Concatenated Result2: <input type="text" id="result2" name="result2" value=""></br>
</form>
This answer is really a revamp of your code, but maybe it will do what you need and simplify things.
If you simply throw out the second input box, and show #result (make it not hidden), i think this code might work to get what you need accomplished, and simplify things a bit.
What this should do is submit a request to the server no more frequently than every 40ms and on success of that request, we update the display value of #result.
I'm now noticing that if this does actually solve the issue, then you've gotten away from the onChange issue completely, because the real trigger now is the keyup event.
$(document).ready(function() {
/** get the inputs we might need */
var $result = $('#result');
var $input = $('#input');
$result.data('url', $result.val());
var timer;
/** function to submit data to the server and
update the result input on success */
function submitForm( input, newValue) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
$result.val(newValue);
}
});
};
/** on key up, fill #result with the url + input */
$input.bind('keyup', function() {
var $this = $(this);
var inp = $this.val();
var url = $result.data('url');
var newValue = url + inp + '/';
if(timer) { clearTimeout(timer); }
timer = setTimeout(function(){
submitForm(inp, newValue) ;
}, 40);
return false;
});
});
The OnChange event is not fired when the contents of the field is changed programmatically. The OnChange event is only raised when a user enters data into the field.
That's just the way this works.

Categories

Resources