On change event inside hidden input field - javascript

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.

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.

Preventing multiple requests from ajax

I have "load more" button, and if I click it fast enough it load the same content twice, and I want to prevent it.
This is how I call to the load more with ajax:
<script type="text/javascript">
function loadmore() {
var val = document.getElementById("result_no").value;
var userval = document.getElementById("user_id").value;
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
getresult: val,
getuserid: userval
},
context: this,
success: function(response) {
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML + response;
document.getElementById("result_no").value = Number(val) + 10;
}
});
}
</script>
<div id="content">
<div id="result_para">
</div>
</div>
<input type="hidden" id="user_id" value="<?php echo $userid;?>">
<input type="hidden" id="result_no" value="15">
<input type="button" id="load" onclick="loadmore()" value="Load More Results">
You could set a loading variable to true at the start of loadmore, and set it back to false in the ajax callback. loading should be declared outside of loadmore though (see what a closure is).
var loading = false;
function loadmore()
{
if (loading) {
return ;
}
loading = true;
var val = document.getElementById("result_no").value;
var userval = document.getElementById("user_id").value;
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
getresult:val,
getuserid:userval
},
context: this,
success: function (response) {
loading = false;
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML+response;
document.getElementById("result_no").value = Number(val)+10;
},
error: function () {
loading = false;
}
});
}
Instead of using that variable, you could also programmatically disable/enable the button, but that means that your button will flicker if the request is fast.
You can prevent from this by disable the button after first click, so change this lines:
success: function (response) {
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML+response;
document.getElementById("result_no").value = Number(val)+10;
}
With this lines:
success: function (response) {
document.getElementById("load").disabled = true;
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML+response;
document.getElementById("result_no").value = Number(val)+10;
document.getElementById("load").disabled = false;
}
you could disable the button when the "load more" button is clicked then then use the javascript function setTimeout to remove the disabled attribute from the button after a period of time. This would mean that the button would not be able to be clicked after the first click and even if the ajax request returned an error the button would still be able to be clicked.
$('#load').click(function {
// disable the button
$(this).prop('disabled', true);
// after three seconds enable the button again
var timeout = setTimeout(function() { $(this).prop('disabled', false); }, 3000);
});

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.

JS/AJAX Auto submit form: Disabling enter key to prevent page refresh

I am using a function that will submit with ajax and without the help of a button click. But I am currently undergoing two issues which with trial and error haven't found plausible solutions:
First is there any way I can disable the enter button click(this causes the whole page to refresh)?
JSFIDDLE basic example in how the JS function works
Second, It feels like I am going the roundabout way to display what has been posted. How can I change this part of the function $('#special').html('<p>' + $('#resultval', result).html() + '</p>'); to have it POST just inside a div called #special without the need of span or <p> #resultval?
Everytime i echo through php I have to do set it like this to display a result: <div id="special"><span id="resultval">This is the result.</span></div>
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});
</script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(event){// the function call on click or on submit onclick=submitForm(event);
event.preventDefault(); //to prevent enter key
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').text(result); //you can use text() or html() only
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});

Categories

Resources