How to use script to get searched value in php - javascript

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

Related

laravel - datatables implement ajax on enter key pressed

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"/>

how to use a onkeyup function in javaScript to get the value using ajax with spring

How to use the on key up event with timeout option. The values typed should return the data that matched in the data base
here my Jquery code is
function searchUserId() {
var userId = $('#userId').val();
//var moduleID = $('#moduleIdList').val();
$.ajax({
url: "controlpanel/SearchUserData",
type: "POST",
data: "userId=" + userId,
//+ "&roleName=" + roleName,
//For Progress Bar
success: function(response) {
alert(userId);
$('#page-wrapper').html(response);
}
});
}
<input type="text" tabindex="1" class="form-control" name="userId" id="userId" maxlength="20"
onkeyup="searchUserId();"data-validation-engine="validate[required]"/>
By 'timeout option' I assume that you mean to use this to only trigger the function when the user has finished typing.
First you should remove the onkeyup attribute from the HTML.
Then add the following to your JS:
var timer;
$('#userId').on('keyup', function() {
if (timer) clearTimeout(timer);
timer = setTimeout(searchUserId,300);
});
This will reset the timer if another keyup event is triggered within 300ms, so the function will not get triggered when the user is still typing. Of course you can set this to any value you like.
You can do like this
HTML
<input type="text" tabindex="1" class="form-control" name="userId" id="userId" maxlength="20"
"data-validation-engine="validate[required]"/>
Jauery
$('#userId').on('keyup',function () {
var userId = $(thi).val();
//var moduleID = $('#moduleIdList').val();
$.ajax({
url: "controlpanel/SearchUserData",
type: "POST",
data: "userId=" + userId,
//+ "&roleName=" + roleName,
//For Progress Bar
success: function(response) {
alert(userId);
$('#page-wrapper').html(response);
}
});
});

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.

Repeat the function for every 1 min?

i am calling a function with parameters from onclick method what i want to do is i want this function to repeat every 1 min here is html code:
I am calling a function on everyclick with some parameter as id
The id fetches the the lat longs,and it is plotted in map ,i have done everything working except that i get the data keep recieving from the back end so what i want to do is , as i have clicked the href i want that particular id to be sent and keep recieve the data of that particular id only and when i click the second the first should be stopped and start the another .
<html>
</head>
<body>
</body>
</html>
javascript:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
Try this...
Use setInterval to call function every 1 minute and "trigger" function to click automatically when call function "test"
<html>
</head>
<body>
sdsd
sdsd
</body>
</html>
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
function test() {
$(".todo").trigger("click");
}
var refreshId = setInterval(test, 60000);
You can simply call a setInterval inside your todo function and it will fire with different calls, change your function like this:
function todo(id) {
setInterval(function() {
/*$.ajax({
type: "GET",
url: "example?value=" + id,
dataType: "text",
success: function(data) {
//parsing;
});*/
console.log(id);
}, 1000);
}
link1
link2
I used only 1000 milliseconds for test here, you only have to change it to 60000 to fit your needs, you can see the results in the console..
Note:
Keep in mind that for each click you will fire a new setInterval() so you have to disable click events after the first setInterval() to avoid this problem.
It is not clear as to what constraints you may require from your question and comments, but perhaps something like this?
Repeat will be stopped if there is an ajax error.
Clicking a button will cancel the current repeat and immediately start the new repeat (1-4). Requests in progress are not cancelled and there is no checking included to ignore processing them upon complete.
A stop button is included, this will stop the repeat but not the request in progress.
The requests are async and no effort has been made to make sure that they are processed in order of request.
This is a very basic example that starts you moving in the right direction.
var pre = document.getElementById('out'),
interval = 5,
running = false,
fetching = false,
timerId;
function stop() {
clearInterval(timerId);
running = false;
}
function todo(id) {
fetching = true;
$.ajax({
type: 'GET',
url: 'http://jsonplaceholder.typicode.com/albums?id=' + id,
dataType: 'jsonp',
error: function (qXHR, textStatus, errorThrown) {
pre.textContent += id + ': ' + textStatus + '\n';
stop();
},
success: function (data) {
pre.textContent += id + ': ' + data[0].title + '\n';
},
complete: function () {
fetching = false;
}
});
}
function start(id) {
if (running) {
stop();
}
running = true;
if (!fetching) {
todo(id);
}
timerId = setInterval(function () {
if (!fetching) {
todo(id);
}
}, interval * 1000);
}
document.body.addEventListener('click', function (evt) {
var target = evt.target;
if (target.classList.contains('album')) {
start(target.value);
}
}, false);
document.getElementById('stop').addEventListener('click', function () {
stop();
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="album" value="1">1</button>
<button class="album" value="2">2</button>
<button class="album" value="3">3</button>
<button class="album" value="4">4</button>
<button id="stop">stop</button>
<pre id="out"></pre>
You can use setTimeout of javascript.
It will repeat given function in specified time interval.
Javascript setTimeout function repeat
OR
setInterval( function(){ todo(id);}, 60000);
Make use of setTimeout to call the function again:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
setTimeout(function(){todo(id)}, 60000);
}
And if you also want to clear timeout on some condition:
var timer;
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
timer = setTimeout(function(){todo(id)}, 60000);
if(//Your condition){
window.clearTimeout(timer);
}
}

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