Html (if there are not results - example):
<div id="fixedsearch"></div>
Html (with results - example):
<div id="fixedsearch">
<div>
<h3>Title</h3>
<img src="/imagesource.jpg">
</div>
</div>
jquery:
$('#searchinput').on('keyup', function(){
$value=$(this).val();
$.ajax({
type: 'get',
url: '{{URL::to('ajaxsearch')}}',
data: {'states':decodeURIComponent($value)},
success:function(data){
$('#fixedsearch').html(data);
if(data == ''){
$('#fixedsearch').slideUp();
}else{
$('#fixedsearch').slideDown();
}
}
});
});
What I need is:
1) If data is not null (and there are existed div inside #fixedsearch) do a smooth animation like slidedown() to show the results inside the #fixedsearch,
2) If data is null do a smooth animation like slideup() to hide smoothly the div.
That is the general idea but I can't accomplished with this jquery code.
Your if condition is wrong. Instead of testing for data == '', you should instead test for data.length > 0 if you want to test for the presence of data to output.
success:function(data){
$('#fixedsearch').html(data);
if(data.length > 0){
$('#fixedsearch').slideUp();
}else{
$('#fixedsearch').slideDown();
}
}
Try adding some timeout delay along with stop() with true to clear the pending animation queues that got triggered when multiple keyup events got triggered.
jQuery(document).ready(function() {
$('#searchinput').on('keyup', function() {
//when no data from server
data = $(this).val();
if (data.length) {
$('#fixedsearch').stop(true, true).slideUp(1000, function(){
//you can do some process
});
} else {
$('#fixedsearch').stop(true, true).slideDown(1000, function(){
// you can do some process
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchinput" />
<div id="fixedsearch">
<div>
<h3>Title</h3>
<img src="/imagesource.jpg">
</div>
</div>
You should check for length of data:
find the tag and check if it returns length zero. If it does, there is no data returned.
$('#searchinput').on('keyup', function(){
$value=$(this).val();
$.ajax({
type: 'get',
url: '{{URL::to('ajaxsearch')}}',
data: {'states':decodeURIComponent($value)},
success:function(data){
var dataHtml = $('#fixedsearch',data).find('div').length;
$('#fixedsearch').html($('#fixedsearch',data).html());
if(dataHtml == 0){
$('#fixedsearch').slideUp();
}else{
$('#fixedsearch').slideDown();
}
}
});
});
using .html().length
After appending the data into your div you can check the content length. You can check that by using .html().length on your div. Use this code in your success callback
success:function(data){
var $fixedSearch = $('#fixedsearch'); // hold the object in a variable since you are using it multiple times, Just a performance concern
$fixedSearch.html(data);
if($fixedSearch.html().length == 0){ // check if the contents exist or not
$fixedSearch.slideUp();
}else{
$fixedSearch.slideDown();
}
}
Ok here is problem in your code ...
I think you are missing really important property about slideDown() function as I know-
slideDown() works on elements hidden with jQuery methods and
display:none in CSS (but not visibility:hidden); if your div has no css like display:none then slideDown() has no effect.
and slideUp() will work in displayed element but you have to callback function in that. I think you should have code like below-
$('#searchinput').on('keyup', function(){
$value=$(this).val();
$.ajax({
type: 'get',
url: '{{URL::to('ajaxsearch')}}',
data: {'states':decodeURIComponent($value)},
success:function(data){
// $('#fixedsearch').html(data);- this will set html to recent and if data is empty then you div with id fixedsearch automatically hidden
$('#fixedsearch').html(data);
if(data == ''){
$('#fixedsearch').slideUp("slow",function(){
$('#fixedsearch').html(data);
});
}else{
// this will hide your div abrupty
$('#fixedsearch').css('display':'none');
// now set div with you new html; hope you are getting response in html
$('#fixedsearch').html(data);
$('#fixedsearch').slideDown();
}
}
});
});
After many attempts I saw the height was the problem.
$('#searchinput').on('keyup', function(){
$value=$(this).val();
$.ajax({
type: 'get',
url: '{{URL::to('ajaxsearch')}}',
data: {'states':decodeURIComponent($value)},
success:function(data){
$('#fixedsearch').html(data);
$('#fixedsearch').css({"height": "296px"});
if(data != ""){
$('#fixedsearch').slideDown();
}else{
$('#fixedsearch').slideUp();
}
}
});
});
Now what I need is to get the height dynamically when the div is not empty. Everything else is perfect now. Thank you for your support.
Related
I have a chat application that works similar to hangouts. When you click on a user the chat div is generated. A simple feature I have is to allow them to press enter in a textarea to send the text, which works fine but if I have multiple dynamically generated jQuery functions only the LAST function will still work. I assume its stopping the previous instances from running. How do I fix this?
Again when the user starts a chat it loads the scripts for that chat session because I assume I need a unique ID rather than a class name so I could pass the ID to the database - probably not the most efficient way to do things I know:
echo "$('#im-textbox".$receiver_id."').on('keyup', function(event){
if (event.keyCode == 13) {
//$(this.form).submit()
var dataset = $('#im-form".$receiver_id."').serialize();
$.ajax({
url: 'data/add-chat.php',
data: dataset,
method: 'post',
success: function(data) {
console.log(data);
}
});
$('#im-textbox".$receiver_id."').val('')
return false;
}
});
";
Thank you for your help!
I fixed it with this...
$(document).on('keyup', '#im-textbox".$receiver_id."', function(event){
if (event.keyCode == 13) {
//$(this.form).submit()
var dataset = $('#im-form".$receiver_id."').serialize();
$.ajax({
url: 'https://easyrepair.us/manage/data/add-chat.php',
data: dataset,
method: 'post',
success: function(data) {
console.log(data);
}
});
$('#im-textbox".$receiver_id."').val('')
return false;
}
});
I am trying to make search function based on Ajax/Jquery.
My web app shows the data of service requests from the database. I want to make searchbar for my app as follows:
show all service request on the table initially.
If something is typed on the searchbar, it searches data and load those data to the table.
Finally if user deletes anyword from searchbar it will show all data as stated on No.1
I managed doing second and third function but I am having issues with the first one.
$(document).ready(function(){
$('#search_text').keyup(function(){
var txt = $(this).val();
if(txt != '') {
$.ajax({
url:"ajax/fetchRequests.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data) {
$('#result').html(data);
}
});
}
else if(txt == '') {
$.get("ajax/readRequests.php", {}, function (data, status) {
$("#result").html(data);
});
}
});
});
Here is another script that i have worked on trying:
$(document).ready(function(){
var txt = $('#search_text').val();
if(txt != ''){
$.ajax({
url:"ajax/fetchRequests.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data) {
$('#result').html(data);
}
});
}
else if(txt == '') {
$.get("ajax/readRequests.php", {}, function (data, status) {
$("#result").html(data);
});
}
});
All my features are working except for the search functions. Any tips or critics are welcome, thank you very much in advance.
I suggest you do two things, 1) use the suggested .on() and 2) use only one ajax function to simplify things. The idea is to funnel your calls through one function so that you know if something fails, it's not because you messed up the ajax part of the script:
// Create a generic ajax function so you can easily re-use it
function fetchResults($,path,method,data,func)
{
$.ajax({
url: path,
type: method,
data: data,
success:function(response) {
func(response);
}
});
}
// Create a simple function to return your proper path
function getDefaultPath(type)
{
return 'ajax/'+type+'Requests.php';
}
$(document).ready(function(){
// When the document is ready, run the read ajax
fetchResults($, getDefaultPath('read'), 'post', false, function(response) {
$('#result').html(response);
});
// On keyup
$(this).on('keyup','#search_text',function(){
// Get the value either way
var getText = $(this).val();
// If empty, use "read" else use "fetch"
var setPath = (!getText)? 'read' : 'fetch';
// Choose method, though I think post would be better to use in both instances...
var type = (!getText)? 'post' : 'get';
// Run the keyup function, this time with dynamic arguments
fetchResults($, getDefaultPath(setPath), type, { search: getText },function(response) {
$('#result').html(response);
});
});
});
To get initial results hook onto jQuery's document ready event.
var xhr;
var searchTypingTimer;
$(document).ready(function(){
// initial load of results
fetchResults([put your own params here]);
// apply on change event
$('#search_text').on('input', function() {
clearTimeout(typingTimer);
searchTypingTimer = setTimeout(fetchResults, 300);
});
});
function fetchResults($,path,method,data,func)
{
if (xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: path,
type: method,
data: data,
success:function(response) {
func(response);
}
});
}
As Rasclatt mentions you should use jQuery's on method to catch any changes.
Secondly I'd recommend disposing of previous requests when you make new ones, since if you are sending a new one on each character change then for one word many requests will be made. They won't necessarily arrive back in the order you send them. So for example as you type 'search term', the result for 'search ter' may arrive after and replace 'search term'. (welcome to async).
Thirdly since you will send many requests in quick succession I'd only call your fetchResults function after a short time out, so for example if a user types a five character word it doesn't fire until 300ms after the last character is typed. This will prevent 4 unnecessary requests that would just be ignored but put strain on your backend.
In my project I have this code who takes results from mysql query and put it into comment DIV and a jquery code who takes me more results when I scroll down my page via a another page code
<body>
<div id="container">
<div class="comment">
<div id="comm">
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var offset = $('.comment:last').offset();
$(window).scroll(function(){
if((offset.top-$(window).height() <= $(window).scrollTop())
&& load==false && ($('.comment').size()>=5) &&
($('.comment').size()!=$('.nb_com').text())){
var theme = $('.comment').attr('idtheme');
$.ajax({
url: 'ajax_scroll.php',
type: 'get',
data: 'theme='+theme,
success: function(data) {
$('.comment:last').after(data);
offset = $('.comment:last').offset();
}
});
}
});
});
</script>
I would like to apply this javascript below for my comment DIV but it works only for the DIVS before I scroll down the page
$('#confirmdelete a').click(function(){
var id_comm=$(this).attr('id');
if(confirm("Delete?")) {
$.ajax({
url: 'commentsdelete.php',
type: 'post',
async: false,
data:{
'id_comm': id_comm
},
success:function(){
}
});
}
else
{
}
return false;
});
How I can apply this javascrip code for all the DIVs (before scrolling and after scrolling)
Thanks.
Solution 1:
Add your click function to the global scope, if the content is changed reassign:
var onclickfunc=function(){
alert("clicked");
}
$('#confirmdelete a').click(onclickfunc);
//later in your ajax
sucess:function(data){
//add the content
//reassign:
$('#confirmdelete a').click(onclickfunc);
}
Solution 2(even better):
Detect if a parent element was clicked, and than check if it was a confirmdelete element:
$(document).on("click","#confirmdelete a",function(){
//yourcode here
});
See: http://api.jquery.com/on/
I am learning jquery and i am stuck with a problem. Here is the code
$(function(){
var gotProducts=new Array();
var productsWithDelete=new Array();
$('.addProducts').on('keyup',function(event) {
var searchVal=$(this).val().trim();
if(searchVal.length > 0) {
$.ajax({
url: 'http://localhost/url',
data: { products: $(this).val(), },
type: 'POST',
dataType: 'html',
success: function(msg) {
$('#printTheProducts').html(msg);
}
});
}
});
$('.productsButton').click(function() {
alert('yes');
});
});
The response I am getting from the ajax call is a button having class productsButton.
Now when i try to click that button I got through ajax then it does not alert yes. I mean it does nothing.
Question:-
What might be the problem?
Try event delegation using .on() for generated button, As they are generated dynamically
$('#printTheProducts').on('click','.productsButton',function(){
alert('yes');
});
Where #printTheProducts is the closest parent element, you can use document or document.body also as a selector!
Syntax:
$(closestparentelement).on('event','targetselector',function(){
});
I have the following that fires off when a checkbox is changed.
$(document).ready(function() {
$("#reviewed").change(function(){
if ($('#reviewed:checked').val() !== null) {
$.ajax({
url: "cabinet_reviewed.php?reviewed=yes",
cache: false,
success: function(html){
$("#reviewDate").replaceWith(html);
}
});
} else {
$.ajax({
url: "cabinet_reviewed.php?reviewed=no",
cache: false,
success: function(html){
$("#reviewDate").replaceWith(html);
}
});
}
});
})
This only works once. I'm looking to see when the check box is changed and what the value of it is once changed.
UPDATE:
I've change the code around to the following (based on everyone's comments)
$(document).ready(function() {
$("#reviewed").click(
function() {
var rURL = 'cabinet_reviewed.php?reviewed=';
if ($("#reviewed").is(":checked"))
rURL = rURL + "yes";
else
rURL = rURL + "no";
alert (rURL);
$.ajax({
url: rURL,
cache: false,
success: function(html){
$("#reviewDate").replaceWith(html);
}
});
});
})
The file cabinet_reviewed.php simply echos the value of $_GET['reviewed']
With this updated code the alert shows the correct URL but the second click does not run the .ajax.
Do I need to do something so the .ajax is run again?
Try with != instead of !==
And also this as an alternative:
$('#reviewed').is(':checked')
The below code works consistently in FF 3.5 and IE8:
$("#reviewed").click(
function() {
if ($("#reviewed").is(":checked"))
alert('checked');
else
alert('not checked');
}
);
After your update:
This code...
success: function(html){
$("#reviewDate").replaceWith(html);
}
... is replacing the element with ID=reviewDate in the DOM with the HTML that is returned from the Ajax call, so it is no longer present the second time the Ajax call is made.
Will something simpler like this work for you?
success: function(html){
$("#reviewDate").html(html);
}
There are apparently some bugs with the change() event for checkboxes in IE. Try using the click() event instead and see if it works better.
You normally want to use click event to track changes in checkboxes/radiobuttons. The change event is only fired if the new value differs from the old value. In checkboxes/radiobuttons there's no means of an initial value, only the checked attribute which is often not predefinied, hence the need to click twice before the change event is fired.
In checkboxes/radiobuttons you also don't want to check the value by val(), it's always the same. You rather want to check the checked state using this.checked.
Thus, the following should work:
$(document).ready(function() {
$("#reviewed").click(function() {
if (this.checked) {
// ...
} else {
// ...
}
});
});