use multiple $(function() with ajax live search - javascript

I created a live search. When i open up the page i want to run $(function() {. This run the ajax once and all the output shown up. But i want that it is also updating the page when i type in the searchbox(thats why i used this $('#search').keyup(function(){). AND i want that it update the page also when i press one of the checkboxes which add some other values to the livesearch($('.btn').click(function(){)
$(document).ready(function(){
$(function() {
$('#search').keyup(function(){
var search = $(this).val();
console.log("Input: " + search);
$('.btn').click(function(){
let val1 = getval1();
let val2 = getval2();
let val3 = getval3();
let val4 = getval4();
console.log(val1 + val2 + val3 + val4)
$.ajax({
url:"search.php",
method:"post",
data:{
search:search,
val1:val1,
val2:val2,
val3:val3,
val4:val4,
},
success:function(data){
$('#output').html(data);
}
});
});
});
});

$(document).ready(function(){
//page completed loading
$('#search').keyup(function(){
//user typed something
var search = $(this).val();
let val1 = getval1();
let val2 = getval2();
let val3 = getval3();
let val4 = getval4();
//let's retrieve values
$.ajax({
url:"search.php",
method:"post",
data:{
query:query,
search:search,
val1:val1,
val2:val2,
val3:val3,
val4:val4
},
success:function(data){
$('#output').html(data);
}
});
});
That is enough. You don't even need to use click event since it will fire on each type. Otherwise you can use the click instead of the keyup and it will fire on button click.
Each time you will type something into #search, you will check the value of the other fields too. I'm curious to see what is inside each getval fucntion beacuse probably they can be replaced by something simpler (btw no need for four different functions imho)
Note: $(document).ready(){}; is used to tell the browser to wait the full page to be loaded before executing the code. You will have one of these only in your page with all the js inside. The functions you define (like when you do
function getval1(){
//your function here
}
don't need to be inside the document ready statement

<script type="text/javascript">
search_data()
$(document).ready(function(){
$('#search').keyup(function(){
search_data()
});
$('.btn').click(function(){
search_data()
});
});
function search_data(query){
var search = $('#search').val();
let val1 = getval1();
let val2 = getval2();
let val3 = getval3();
let val4 = getval4();
$.ajax({
url:"search.php",
method:"post",
data:{
query:query,
search:search,
val1:val1,
val2:val2,
val3:val3,
val4:val4,
},
success:function(data){
$('#output').html(data);
}
});
}
</script>

Related

Ajax update post request on click jQuery

I would like to click on a previous or next button and update the ajax post request. The parameter I want to change is the variable called "page". The URL of the request takes this variable to show the right page. When I click on a previous or next button I want to change the "page" variable value. Thanks.
$(document).ready(()=>{
var pageSize = "pageSize=10";
//want to change the page number on click
var page = "page=1"
var requestIndex = $.ajax({
type: 'POST',
url: `url`,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
}
});
// console.log(request)
requestIndex.done((data)=>{
var done = JSON.parse(data)
// console.log(done)
done.forEach((result, index)=>{
// res.push(result)
var firstName = result.FirstName;
var lastName = result.LastName;
var modelYear = result.ModelYear;
var make = result.Make;
var model = result.Model;
var dealership = result.Dealership;
$('#test>tbody').append(`
<tr>
<td>${firstName} ${lastName}</td>
<td>${modelYear}</td>
<td>${make}</td>
<td>${model}</td>
<td>${dealership}</td>
</tr>
`)
})
var tr = $('table').find("tr");
var resultQuant =[]
resultQuant.push(tr)
var pages = []
//loop over each result and create pagination
resultQuant.forEach(function(res, index){
console.log(res.length);
if(res.length > 9){
$('#prev_page').append(`
Prev Page
`)
$('#next_page').append(`
Next Page
`)
}
})
});
requestIndex.fail(function(jqXHR, textStatus) {
console.log('failed')
});
})
Here is a working snippet for what I think you're looking for. I had to make some changes, some for aesthetics, and some for functionality. Here's the functional changes/updates:
Your whole ajax/refresh table script needed to be outsourced to a function so it could be called multiple times.
The page and pageSize variables are better left as numbers rather than queryString strings
I created a delegated event listener on your buttons. It's one listener that will handle either button. The listener callback finds out if its the next or previous button that was clicked, then calls the goToPage() function with the incremented onPage variable
The table is now cleared before each new data batch is written to it, as you'd expect a paginated result to be
The buttons should disable/enable according to the pagination, so I put in a script to test if we're at the first page or the last page to disable/enable them
I changed all your vars to lets because that's the way we initialize block variables nowadays
let onPage, pageSize = 10;
$(document).ready(() => {
goToPage(1)
$('body').on('click', '#next_page, #prev_page', function() {
inc = 1;
if ($(this).attr('id') === 'prev_page') inc = -1;
goToPage(onPage + inc);
})
})
function goToPage(page) {
let requestIndex = $.ajax({
type: 'POST',
url: `url`,
beforeSend: function() {
$("#loading").show();
},
complete: function() {
$("#loading").hide();
}
});
requestIndex.done((data) => {
onPage = page;
$('#test>tbody').html('');
JSON.parse(data).forEach((result, index) => {
$('#test>tbody').append(`
<tr>
<td>${result.FirstName} ${result.LastName}</td>
<td>${result.ModelYear}</td>
<td>${result.Make}</td>
<td>${result.Model}</td>
<td>${result.Dealership}</td>
</tr>
`)
})
if (onPage > 1) $('#prev_page').removeAttr('disabled');
else $('#prev_page').attr('disabled', true)
if (JSON.parse(data).length === pageSize) $('#next_page').removeAttr('disabled');
else $('#next_page').attr('disabled', true)
});
requestIndex.fail(function(jqXHR, textStatus) {
console.log('failed')
});
}
#loading {
display: none'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='loading'>Loading...</div>
<table id='test'>
<tbody></tbody>
</table>
<button id='prev_page'>Prev Page</button>
<button id='next_page'>Next Page</button>

Set AJAX response as javascript variable for reuse [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
EDIT : found the solution, i edited the code so if anyone came to the same problem in a near future can copy my code.
I need to set AJAX response as variable so i can use it on next js script. how can i set AJAX response to variable?
i don't really good at javascript so it might be just typo or something.
this is my code
<script type="text/javascript">
var delivery; // declare of variable to make it "global"
$(document).ready(function() {
$("#jumlah").bind("input change paste keyup", function() {
var qty = $(this).val();
$.ajax({
type: 'POST',
url: '../component/quantity.php',
data: {
jumlah: qty,
id:<?php echo $hasil['id']; ?>
},
success: function (response) {
// We get the element having id of display_info and put the response inside it
delivery = parseFloat(response); // remove the "var" here so you take the cur variable and don't set a new one in the scope of this function.
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("select").change(function() {
var total = delivery;
$('select option:selected').each(function() {
total += parseFloat($(this).data('price'));
});
var updatePrice = document.getElementById('jumlah').value;
var grandTotal = total * updatePrice;
$(".total").val(grandTotal);
$(".total").html(grandTotal.toLocaleString());
});
$("#jumlah").bind("input change paste keyup", function() {
var total = delivery;
$('select option:selected').each(function() {
total += parseFloat($(this).data('price'));
});
var updatePrice = $(this).val();
var grandTotal = total * updatePrice;
$(".total").val(grandTotal);
$(".total").html(grandTotal.toLocaleString());
});
});
</script>
What you are looking for are scopes. Depending on how and where you set a variable the scope changes.
In your case you want one that is accessable globally so you should place it at the top. You just need to declare it, you don't need to assign any value.
<script type="text/javascript">
var delivery; // declare of variable to make it "global"
$(document).ready(function() {
$("#jumlah").bind("input change paste keyup", function() {
var qty = $(this).val();
$.ajax({
type: 'POST',
url: '../component/quantity.php',
data: {
jumlah: qty,
id:1
},
success: function (response) {
// We get the element having id of display_info and put the response inside it
delivery = parseFloat(response); // remove the "var" here so you take the cur variable and don't set a new one in the scope of this function.
}
});
});
});
</script>
2nd part
<script type="text/javascript">
$(document).ready(function() {
$("select").change(function() {
var total = delivery;
$('select option:selected').each(function() {
total += parseFloat($(this).data('price'));
});
var updatePrice = document.getElementById('jumlah').value;
var grandTotal = total * updatePrice;
$(".total").val(grandTotal);
$(".total").html(grandTotal.toLocaleString());
});
$("#jumlah").bind("input change paste keyup", function() {
var total = delivery;
$('select option:selected').each(function() {
total += parseFloat($(this).data('price'));
});
var updatePrice = $(this).val();
var grandTotal = total * updatePrice;
$(".total").val(grandTotal);
$(".total").html(grandTotal.toLocaleString());
});
});
</script>
Edit: Fixed the code. The variable has to be outside of a function.
The window object represents an open window in a browser.
window is a object and you can add any property to window.
success: function (response) {
window.deliveryResponse = response;
}
So you can use this response in any other js file.
other.js
(window.deliveryResponse) && console.log(window.deliveryResponse)
As ajax calls are async, you cannot be sure that the delivery variable will be undefined or not.
In your case, this cannot work also because the variable is defined in the callback scope. To ensure that the delivery response is defined, create a function like this:
function onDelivery(delivery) {
....(rest of second script)
}
Pass this function to the success and use delivery as it is.
Try this:-
<script type="text/javascript">
var delivery; // make your variable delivery as global so you can use it where you want.
$(document).ready(function() {
//you can use it here or anywhere in script you want to re-use it.
//put your code as per your functionality.
});
</script>

how to count length of list created dynamically

I am creating a chat box in which chat messages are fetched in the form of list. My problem is whenever i am clicking on start chat button i have to open chat box and then count the no of list. my chat box is opening but length of list are always zero. how to solve this.
$(document).on('click', '.start_chat', function(){
var to_user_id = $(this).data('touser_id');
var to_user_name = $(this).data('tousername');
//console.log(to_user_id);
var getdata;
$.ajax({
url:"chat_id_table.php",
method:"POST",
data:{to_user_id:to_user_id},
async:false,
dataType:'json',
success:function(data)
{
//console.log(data);
getdata = JSON.parse(data);
//console.log(getdata);
}
})
if($('#user_dialog'+to_user_id).length == 0){
make_chat_box(to_user_id, to_user_name, getdata);
}
var chat_length = $('.msg_list').find("li").length;
});
Getting the chat data is an async call. so what happens is that the list is counted before the data comes in.
To solve this wrap the list counter in a function and call it after data is in.
fixed code here
$(document).on('click', '.start_chat', function(){
var to_user_id = $(this).data('touser_id');
var to_user_name = $(this).data('tousername');
//console.log(to_user_id);
var getdata;
$.ajax({
url:"chat_id_table.php",
method:"POST",
data:{to_user_id:to_user_id},
async:false,
dataType:'json',
success:function(data)
{
//console.log(data);
getdata = JSON.parse(data);
//console.log(getdata);
var chat_len = counter();
}
})
});
function counter(){
if($('#user_dialog'+to_user_id).length == 0){
make_chat_box(to_user_id, to_user_name, getdata);
}
var chat_length = $('.msg_list').find("li").length;
return chat_length;
}

select not getting updated on ajax call

I have an ajax call to dynamically create select elements. the amount of selects is dependent on another select. This works fine. for my test 3 select menus should be created dynamically which works fine. the dynamically created selects will make ajax calls on their own to create some options dynamically, this is where I have the issue. Everything seems to be working except the options for a second select is not getting populated. Please see code below.
Thank you
$('#union').on('change',function(){
var union_id = $(this).val();
if(union_id){
$.ajax({
type:'POST',
url:'fetch_referee.php',
data:'union_id='+union_id,
dataType: 'json',
success:function(data){
$('#dynamic_selects').html(data.html);
var total = data.total;
for(i=1; i<=total; i++){
$('#allreferee'+i).on('change', function(){
var all_games = $(this).val();
//alert(all_games);// this is good output is valid
if(all_games){
$.ajax({
type:'POST',
url:'fetch_places.php',
data:'all_games='+all_games,
dataType: 'json',
success:function(html){
alert(html);/// this is good.. returns option values
$('#refposition'.i).html(html);//the select menu does not get updataded
}
});
}else{
$('#refposition'+i).html('<option value=""></option>');
}
});
}
}
});
}else{
}
});
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). Check this for more details
Your code should now look like this
$(document.body).on('change','#union',function(){
var union_id = $(this).val();
if(union_id){
$.ajax({
type:'POST',
url:'fetch_referee.php',
data:'union_id='+union_id,
dataType: 'json',
success:function(data){
$('#dynamic_selects').html(data.html);
var total = data.total;
for(i=1; i<=total; i++){
$(document.body).on('change','#allreferee'+i, function(){
var all_games = $(this).val();
//alert(all_games);// this is good output is valid
if(all_games){
$.ajax({
type:'POST',
url:'fetch_places.php',
data:'all_games='+all_games,
dataType: 'json',
success:function(data){
alert(html);/// this is good.. returns option values
$('#refposition'+i).html(data.html);//the select menu does not get updataded
}
});
}else{
$('#refposition'+i).html('<option value=""></option>');
}
});
}
}
});
}else{
}
});
I'm sure that your methodology is flawed, but if you must:
$('#union').change(function(){
var union_id = $(this).val();
if(union_id !== ''){
$.post('fetch_referee.php', 'union_id='+union_id, function(data){
$('#dynamic_selects').html(data.html);
$('[id^=allreferee').change(function(){ // I would give the Elements an HTML class instead - but
var t = $(this), all_games = t.val();
// console.log(all_games); // this is good output is valid ??
if(all_games === ''){
t.html("<option value=''></option>");
}
else{
$.post('fetch_places.php', 'all_games='+all_games, function(html){
// console.log(html); // this is good.. returns option values ??
t.html(html); // the select menu does get updataded ??
}, 'json');
}
});
}, 'json');
}
});

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