FadeIn DIV after AJAX pull - javascript

i have this bit of nasty code :P that updates a div using AJAX, but i would love to see a fadein effect on it. The thing is, i have an image that loads and appears during the interval where the div is not showing any content yet. Analyse the bottom of it. What can i do to make it fadein?
function testing(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("myDiv").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
$('#myDiv').html('<div style="text-align:center; padding-top:195px;"><img src="../images/loaderajax.gif" width="220" height="19" /></div>');
xmlhttp.open("GET","getuser.php?q="+str,true);
$('#myDiv').hide();
xmlhttp.send();
$('#myDiv').fadeIn();
}

If you are okay with wrapping the returned content, I would do something like this in the ajax response:
$("<div/>").html(xmlhttp.responseText).appendTo("#myDiv").hide().fadeIn();
This will allow your image to show and only fade in the new content.

Your code is all wacky and out of order with your ajax call. You're using JQuery, so take advantage of it! :)
$.ajax({
url: 'getuser.php',
data: str,
beforeSend(jqXHR, settings) {
$('#myDiv').html('<div style="text-align:center; padding-top:195px;"><img src="../images/loaderajax.gif" width="220" height="19" /></div>');
},
error:function(jqXHR, textStatus, errorThrown) {
$('#myDiv').html(textStatus + ' -- ' + errorThrown);
},
success:function(data){
$('#myDiv').hide().html(data).fadeIn();
}
});

Put the fadein() call in the code that handles the response.
Any reason why you're using jQuery for the selectors and effects and not for the AJAX?

Related

Shortening Ajax Code

I am creating fully Ajax based website so all actions calls a different JS function therefore I am using this Ajax Code in each of my function which makes my functions a big code.
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var getData=xmlhttp.responseText;
if(getData=="something") {
/*
code goes here
*/
}
else {
/*
code goes here
*/
}
}
}
xmlhttp.open("GET","mypage.php",true);
xmlhttp.send();
So I wanted to ask should I use a different function that contains only above Ajax Code and declare my variable getData globally so whenever I need it I should call it.
Here is how I wanted to use
var getData=""; /*declaring var Globally (I read it like this dont know right)*/
function oneAjax(checkPage) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
getData=xmlhttp.responseText;
/*now check further in the function which called it*/
}
}
xmlhttp.open("GET",checkPage+".php",true);
xmlhttp.send();
}
Will it create any conflict with other running actions?
or provide me any right solution for my problem.
If you're not going to use an off-the-shelf library, you should pass a "callback" to oneAjax:
function oneAjax(checkPage, done, fail) {
...
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
done(xmlhttp.responseText, xmlhttp.status);
} else {
fail(xmlhttp.status);
}
}
};
}
Adjust the parameters passed to the callbacks to suit your requirements.
To use:
oneAjax('mypage', function(text, status) {
// success
console.log(status);
}, function(status) {
// failure
console.log(status);
});
why don't you use Jquery or something like this? Such library will much shorten your statements and this will be much easier to write.
But still if you want to do it by your own you should read about javascript promises. On msdn there is a nice tutorial how to solve your problem: Asynchronous Programming in JavaScript with “Promises”
I think using the jQuery library would be better and provide a better low level abstraction
<!-- add a protocol if on local ex: http: -->
<script src="//code.jquery.com/jquery-1.10.0.min.js"></script>
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
It also offers features like JSONP to get around cross domain issues

How Can 2 onload() JavaScript Scripts be Loaded?

With this function:
function start() {
MONDUX();
Biggie();
}
function MONDUX executes, and the AJAX call returns good data and is displayed correctly.
However, Biggie() is a.w.a.l.
The result of this :
function start() {
Biggie();
MONDUX();
}
is the opposite. Biggie() works as expected, MONUX() fails.
This doesn't do any good, down in the body:
<script type="text/JavaScript">
window.onload= start();
</script>
and, this dodge is not helpful:
<body onload="start()">
and that was tried like so also
Detest cargo~cult programming and running out of ideas here. Suggestions?
These resources were all related // near hits // no cigar.
Loading javascript in body onload with 2 functions
JS and Body(Window) Onload event
JavaScript: How is "function onload() {}" different from "onload = function() {}"? That one
was fascinating but way deep waters for me...
How to onload two javascript files? meh... good, but...
?? :/~
<script type="text/javascript" >
function MONDUX(){
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("WhatThexBobby").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","000 8 KISS 22solo PHP.php?figure1=5&figure2=33", true);
xmlhttp.send();
alert(WhatThexBobby);
}
</script>
<script type="text/javascript" >
function Biggie(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("FreakinEh").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","000 8 KISS solo PHP.php?figure1=5&figure2=10", true);
xmlhttp.send();
alert(FreakinEh);
}
</script>
You're assigning the request to the global variable xmlhttp, and then reassigning that variable to another request before the first one has returned. I don't know if that is causing your problem, but it's definitely going to cause a problem. It's also very bad JavaScript practice.
Simple fix is to put the line 'var xmlhttp;' at the beginning of both functions.
Edit: Just in case you didn't know this: xmlhttprequest is asynchronous. You call 'send', and your remaining statements in the script and document continue to run while the request is being sent to the server. Only after the server returns do the various callback methods (onreadystatechange, and the like) get called, and this is long after your alerts were shown.
Considering one of them is throwing some error, would it not be good idea to put them in Try Catch ? Something like,
function start() {
try
{
MONDUX();
}
catch(err)
{
// handle error
}
try
{
Biggie();
}
catch(err)
{
//Handle error
}
finally
{
// cleanup
}
}
This will ensure both runs even if one of them mis-fires.

Calling a function cancels out the previous action

I have a simple script that i am testing with, but its acting very odd. I call a script which loads and i have it to a particular td id, I then call a second script and add that to different td id but for some reason it wipes out the first div's content even though they are seperate.
This is what i have:
function call_back(result,div_id,func){
document.getElementById(div_id).innerHTML = result;
if(typeof(func) != 'undefined'){func();}
}
function caller(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function call_file(url,div_id,func){
caller(url,function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
call_back(xmlhttp.responseText,div_id,func);
}
});
}
I then have this on my onload:
window.onload = function(){
stage = 6;
call_file('test.html','menu_left');
switch(parseInt(stage)){
case 6: call_file('test2.html','main'); break;
}
};
The problem arises with the case statement. If i remove the case statement the contents added with test.html loads fine, but if i add the case statement, content from test.html disappears and then only test2.html displays.
The html for the id's are:
<table class="body_wrapper">
<tr>
<td class="menu_left" id="menu_left"></td>
<td class="main" id="main"></td>
</tr>
</table>
Why might this be happening?
The problem has nothing to do with the switch statement. As you are calling the ajax request for some local files and it is already cached, the call_back function is called twice before document.getElementById(div_id).innerHTML = result; executes and hence replaced by the variable values from the last call. If you just put an alert into the call_back function like below
function call_back(result, div_id, func) {
alert(result);
document.getElementById(div_id).innerHTML = result;
if (typeof (func) != 'undefined') { func(); }
}
you will find it is working. But as it is not a solution, alternatively if you modify this
xmlhttp.open("GET", url, true);
to
xmlhttp.open("GET", url, false);
it will work but you will loose the asynchronous feature of AJAX.

ajax internet explorer onchange

My ajax script for loading the second select box, works in firefox and chrome, but internt explorers cant handle it. I call the onChange function from my select box and give the value from the select box to the function.
Code:
function getXMLHTTP()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function getType(categoryName)
{
var strURL="includes/get.php?c="+categoryName+"&sid="+Math.random();
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200)
{document.getElementById('type').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
My second question is, is it possible to send the text between the options tag instead of the value in the options tag?
For your 1st question, I assume your if (req) returns false. Which IE version are you using? Try to add debug codes in getXMLHTTP() function to start diagnosing the codes. Try this solution provided by Microsoft: http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx
I try not to repeat other's answer. Here is the answer for obtaining text in selected option tag : Getting the text from a drop-down box

AJAX: How to use TWO xmlHttpRequest in parallel in ONE function?

How should I do this?
function(id,id2){
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
First Request:
xmlhttp.open("GET", "http://example.com/ajax.php?id="+id, true);
xmlhttp.send();
Second Request:
xmlhttp.open("GET", "http://example.com/ajax2.php?id2="+id2, true);
xmlhttp.send();
}
Because in this way doesn't works.
I want to make it in plain javascript, so please do not post answers with jQuery or any library etc.
Thanks
It should work if you create a new xmlhttp object. Currently you are attempting to reuse the same object, which is already performing a query so it will not work.
if you are looking for classic javascript style you can use as the following. But use jQuery as it's simple and comprehensive. The one thing to be noted is that the "xmlhr" should be in method (callAjax) scope.
function callAjax(url) {
var xmlhr;
if (window.XMLHttpRequest) {
xmlhr = new XMLHttpRequest();
} else {
xmlhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhr.onreadystatechange = function () {
if (xmlhr.readyState == 4 && xmlhr.status == 200) {
alert(xmlhr.responseText);
}
}
xmlhr.open("GET", url, true);
xmlhr.send();
}
function myFunction(id1, id2) {
callAjax("http://example.com/ajax2.php?id2=" + id1);
callAjax("http://example.com/ajax2.php?id2=" + id2);
}

Categories