Asynchronous searching with AJAX and Jquery - javascript

I have a page I'm building which is powered primarily with AJAX. I want the searching on the page to be asynchronous so that as the user types, the search results change on the fly. I was able to make this work somewhat by sending an AJAX call on keyup from the text box, and it works well in Chrome, FF, etc.
The only problem I'm having is in IE7. The page starts to get really slow as you type, so I'm assuming that perhaps the function to call the AJAX is being opened several times without being closed, causing the page to get slow. Is there an easy way to do this where I can basically end the current AJAX call if another key is pressed? Or is there maybe some other reason that IE could be slow?
The general code is:
$('.search_input').keyup(function(e) { make ajax call and populate results }
Thanks in advance for your help.

Hmm...I have something just like this and I tested it out in IE7 without receiving any slowdowns. Here's what my code looks like:
$("#key").keyup(function(event) {
if(event.which != '13') {
$.get("hash.php", {key: $("#key").val()}, function(hashes) {
$("#hashvalues").html(hashes);
});
}
});
"#key" is a text input field, "hash.php" is the current page, and "#hashvalues" is the main container div on the hash.php page.
Are you returning an insane amount of data for any reason? I've seen IE slow way down if there's a LOT of HTML returned.

Use jQuery.Load() to keep loading a seperate page into a placeholder element (div for example), and pass the value of 'search_input' as a querystring value each time.
This will give that new Google search feel, if thats something youre after

Related

JS: temporarily disable page rendering (possible?)

I'm tryin to sort a big html table using JS. It takes a lot of cpu% to rearrange all the rows of this table. I think the big part of this problem is: every time my script moves a pair of rows, the browser starts refreshing the table
So, I'm searching for any way to temporarily tell the browser something like "wait, I'm sorting this table, dont waste CPU for rendering until I'll finish, plz?"
Basically, I need something lke "Memo1.lines.beginupdate / Memo1.lines.endupdate" in delphi >.<
alert(string) stops rendering, and not asyncronous calls, but not loading. You may prompt "too many cells to load, please wait" you may got the desired behavior.
note that, in order to work, string should be a non empty string after trim so a white space is not valid.
You can disable most of the background rendering by disabling displaying of the parent element. Since the parent element is not displayed, client's renderer has nothing to render and also does not recompute sizes. Be aware that when you are updating the content, you will loose focus if it was present wihtin the parent Element.
To achieve something like Memo1.lines.beginupdate and Memo1.lines.endupdate use this:
originalStyleDisplay = myMemo1Div.style.display;
myMemo1Div.style.display = 'none';
try {
mySorting();
} catch() { }
myMemo1Div.style.display = originalStyleDisplay;

Updating multiple areas with ajax

I've started learning ajax and javascript recently, and still getting a handle on it. But I have a simple goal I'm trying to achieve, and I'm half way there.
For example. I am working on the ability to manage bookmarks saved by one user to be used by other members. I have the code built where I can add, edit, and delete the item live on the page. But how I learned how to do the edit part is a 'click the field area' to start the edit, then 'click out of the field area', to finish the update. I'd really like to change that to a way to click a button to submit the edit.
Also on the page it has a "View Bookmark" button right next to the delete option, but I am not sure how to update that link when I update the text area of it without refreshing the page.
So essentially I want to learn a more efficient way to do live updates via ajax, and then when the update is completed, update all the instances of that same item on the page (which is only two areas).
Any help would be greatly appreciated.
I can post my original code but I think I might be better to learn from someone who knows better. lol
This is a generic question so I will answer generic answer.
If you have, for example, 2 divs
<div id="area1"></div>
<div id="area2"></div>
And you want to call the server and get 2 data's for each div, So it will looks like this: (I'm using jQuery for the example..
$.ajax({
url:'server_url',
method: 'post',
success: function(data) {
$('#area1').html(data.objForArea1);
$('#area2').html(data.objForArea2);
}
});
The JSON that return from the server (for example)
{
objForArea1: '<div class="list-item">item 1</div>...'
objForArea2: '<div class="list-item">item 1</div>...'
}
So you read the response from the object that return from the ajax call, then you put the data wherever you want.

Can a URL activate several scripts?

Is it possible to alter the url of a webpage so that it will activate specific click-activated features on the webpage without the user having to do the clicking?
To better illustrate my question I made this fiddle.
The page loads with a red box with information in it. The user can click the box once to see new information. They can click it again to see a third piece of information.
I would like to have urls that load the page with specific information showing. For example, if the main url for my page is http://www.mypage.com, then I would like to have urls http://www.mypage.com/#info2 and http://www.mypage.com/#info3 so that when the user enters the info2 (respectively, info3) url, the page loads with the second (respectively, third) piece of information showing.
Remarks: I have searched some other questions about activating scripts with hashtags, but have not found something I can understand or implement into what I want to do. In particular, I need my hashtag urls to be able to implement a sequence of several actions (e.g. two clicks to get info3 in the above example).
Remark 2: I am open to other solutions too. I just need someone to explain how to accomplish what I am trying to do.
You could use this after you define your click handlers.
if (window.location.hash == '#1'){
$("#info1").click();
}
if (window.location.hash == '#2'){
$("#info1").click();
$("#info2").click();
}
Not sure if any of this works -- I didn't devote much time on it, given the state of the question, but consider:
var hash_page = (window.location.hash+'').replace(/^#/,''); // get hash and parse
var page_number = hash_page.match(/\w+?(\d+)/)[1] || 1; // get the number
var next_page = page_number + 1; // get next number
$('#info'+page_number).click(function(){
window.location.hash = 'info' + next_page;
});
Assuming that your red box is a div like this:
<div class="redbox">...</div>
and that you have three blocks within it (info 1, 2, and 3):
<div class="redbox">
<div class="info1">...</div>
<div class="info2">...</div>
<div class="info3">...</div>
</div>
With jQuery you could do something simple like this:
jQuery(".redbox").click(function()
{
if(jQuery(".redbox .info3").is(":visible"))
{
return; // all done already
}
if(jQuery(".redbox .info2").is(":visible"))
{
jQuery(".redbox .info3").show();
return;
}
jQuery(".redbox .info2").show();
});
I'm not too sure why you'd like that in the URI. The only reason for such would be in case the user comes back to that same place and you'd want them to see the page in the same state. If that is important, then yes, you should use the window.location.hash to change the URI. That way, if the user comes back you can test the hash and setup the status as required on load. However, note that the hash does not get sent to the server. It is only a client thing.
My solution supposes that info2 and info3 are already loaded. It is also possible to use the load() function to load them dynamically. It depends on their size and whether you do or do not want that information to be visible when the user does "Show Source".
There is the reason why some systems use the "hashbang" feature in their website:
https://developers.google.com/webmasters/ajax-crawling/
Google, at some point, said they would drop that functionality, but it looks like they have not done so and actually continue to encourage people to use that methodology. Twitter has been using it for a while, but from what I can see they don't use it anymore.

jQuery event triggering multiple times because of multiple javascript inclusions/requires

I have a problem here and it's making me mad. I maintain a legacy php system. It's badly organized, no frameworks are used and a lot of other problems, for example, at least 5 different query versions are used in different parts of the system.
So my problem right now is this, I have a search form, when a button is clicked it shows a list of items, lets call this a list of "A" objects. In each A item, there is an expand /toggle button to show the B items that belong to A (this is done using ajax, by setting a specific div's html to the ajax response). Then each B also has an expand/toggle button to show the C items that belong to B.
What is happening: I click to search, all A are shown. I click on the expand to show the B items of one A object, they are shown. I click B to hide it, it hides and then show again. If I click it one more time, it hides, shows and hide. So it is like every ajax request is including the javascript code and running it.
I think this is pretty much an organization problem, I am not knowing how to include/require and insert the js correctly. I've been trying to solve this issue since yesterday and I think I've seen the code so many times that I can't think out of the box.
So here's some of the organization (I changed the names because there are some business rules):
SearchResults.php -> Declares a class that has static methods to print out HTML of each item A, B and C and some other helper methods. To make stuff "work", it has a require "js.php"; otherwise the A expand button does not work because it does not exist at the time the js is executed and no function is bound.
search.php -> the HTML form with all the search options, nothing important.
js.php -> the javascript stuff, why is it in a ".php"? I can't even remember, but I think it is because with the php I can require/include:
<script type="text/javascript" src="../util/js/jquery/1.8.1/jquery.min.js"></script>
<script>
var jQ = jQuery.noConflict(true);
jQ(document).ready(function() {
jQ(".loadBfromA").click( function(e) {
if (div.style.display == 'none')
alert("was hidden, now is showing");
//call ajax_B.php
//response is put into the div using .html(data)
else
alert("was showing, now is hidden");
...
ajax_B.php -> the ajax that access the database and echoes html code that will be put into the A items div. Here I have to require SearchResults.php, because I call some methods of the class.
Why is it including the jQ(document).ready being executed multiple times? How can I fix it? Is there any way I can reorganize the code?
Is the ajax_B.php, when requiring SearchResults.php, including the js again because SearchResults.php requires js.php? Does this gets echoed and then put into the div?
I can't make a fiddle of this because there is ajax included.
Edit:
I have tried unbind("click").bind("click", ()) and it didn't work.
It looks like the event is being bound multiple times on jQ(".loadBfromA")
I know this is not the cleanest solution out there, but you could rewrite the actual binding:
jQ(".loadBfromA").bind('click.loadbfroma', function(e) {
// Do your code
$(this).unbind('click.loadbfroma');
});
That way you can at least be sure that only one event is bound at all times, no matter how many times the code snippet is being included. I know this doesn't really help you with the underlying issue but it's a start.

jQuery not replacing some text

I've been working on a project that involves ajax; it's a planner for school assignments. When a button is pressed, it's supposed to change the text inside of 31 <textarea>'s (and one <span>) based on data it gets from the server. The thing is, textareas that have been changed after the last time the window was refreshed don't change. I've looked over the JSON sent between the server and the webpage and vice-versa, and concluded that the bug is in the success function of the ajax call. Here's the code:
success: function(data) {
$("span#date").text(data['date']);
$("#assignments").find("textarea").each(function() {
$(this).text("");
$(this).html(data[$(this).attr("id")]);
});
console.log(data); // I was using this to see if the data received from the server was correct
}
Thanks very much in advance for any help.
you should use .val() for textarea as it's basically an input.
You can't really have html elements inside it.
Try $(textarea).val() instead of .html(). I noticed that html only works the first time the textarea is rendered.

Categories

Resources