Browser compatibility with AJAX function - javascript

I have the following AJAX function that calls a PHP file to determine if an email is present in a db.
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(Email){
var url="index.php?EmailCheck=Yes&Email=" + Email;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
if(ajaxRequest.responseText == 0) {
alert("Sorry that email is not registered.");
} else {
alert("Login successful.");
window.opener.location.reload();
window.close();
}
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
Are there going to be any browsers this won't work for? I have had some complaints from users, but I can't replicate the errors in IE, FF, or Chrome.

It won't work in Lynx, and it probably won't work in some specialized screen-reader browsers. If you seriously expect to have users for which it won't work, for God's sake fix the error message. Better yet, use something like jQuery. Realize that it's possible to fall back to an alternative approach of using a hidden <iframe> or something instead of XMLHTTPRequest.

Related

jquery tooltip not displaying from ajax function

So I have a list of movies and their info displayed from mysql in a table on a JSP. Each movie's table entry looks like <a id="135006" onmouseover=ajaxFunction(this); href=SearchSingleMovieServlet?txt_movie_id=135006>The Life Aquatic</a>.
My ajax function looks like:
<script language="javascript" type="text/javascript">
function ajaxFunction(obj){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$( '#'+ obj.id ).tooltip({
content: "<strong>Hi!</strong>",
track:true
});
document.getElementById('popup').innerHTML = '#' + obj.id+ ajaxRequest.responseText;
}
}
var parameter = "movie_id=" + obj.id;
ajaxRequest.open("POST","MoviePopUpWindowServlet", true);
ajaxRequest.setRequestHeader("Content-type"
, "application/x-www-form-urlencoded")
ajaxRequest.send(parameter);
}
</script>
The line document.getElementById('popup').innerHTML = '#' + obj.id+ ajaxRequest.responseText; is just a debugging line so I can see if the code enters the AJAX function and to make sure responseText displays correctly (which it does). But when I try mousing over the link of the movie, its tooltip doesn't show. Any reason why?

Ajax call does not refreshesh the calling page javascript

I have a JSP page that refreshes every 5 seconds Using ajax.
The page i am calling having javascript that is not getting refreshed .
Please tell me how to achieve that.
Below is the code i am using to refresh that page .
refresh is the name of the div where i am displaying the data.
<script type="text/javascript">
function AutoRefresh(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("No AJAX");
return false;
}
}
}
xmlHttp.onreadystatechange=function(){
//alert("hi");
if(xmlHttp.readyState==4){
document.getElementById('TotalRoutes').innerHTML=xmlHttp.responseText;
setTimeout('AutoRefresh()',10*1000); // JavaScript function calls AutoRefresh() every 3 seconds
}
}
xmlHttp.open("GET","QAGENIE.jsp",true);
xmlHttp.send(null);
}
</script>
Here js files in the QAGENIE.jsp page is not getting refreshed on the ajax call
try to wrap that code inside $(document).ready();
like
$(document).ready(function(){
$.ajax({
url: 'http://localhost:8088/Login.do',
success: function(data) {
alert(data);
$("#refresh").html(data);
alert(data);
},
complete: function() {
alert("refresh");
setTimeout(function(){ worker(); },5000);
//$('#refresh').load("http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
}
});
});
you should import the jquery file first
like
<script src="<%=request.getContextPath()%>/view/js/jquery1.7.2.js"></script>
and debug is,if is nothing in you console,it will be success

Trying to add delay to jQuery AJAX request

I am trying to delay an AJAX request so that it is sent out 2-3 seconds after the LAST keyup of an input cell.
So far I have managed to delay the requests, but after 2-3 seconds I get one request sent for every keyup in the field...
How can I make jQuery cancel the first ones and just send the last keyup?
Here's the code so far:
$('#lastname').focus(function(){
$('.terms :input').val(""); //clears other search fields
}).keyup(function(){
caps(this); //another function that capitalizes the field
$type = $(this).attr("id"); // just passing the type of desired search to the php file
setTimeout(function(){ // setting the delay for each keypress
ajaxSearchRequest($type); //runs the ajax request
}, 1000);
});
This code above, waits 1 sec then sends 4-5 AJAX requests depending on keypresses.
I just want one sent after the last keyup
I have found some similar solutions in StackOverflow that use Javascript, but I have not been able to implement them to my project due to my small knowledge of programming.
[SOLVED]
Final working code, thanks to #Dr.Molle:
$('#lastname').focus(function(){
$('.terms :input').val("");
}).keyup(function(){
caps(this);
$type = $(this).attr("id");
window.timer=setTimeout(function(){ // setting the delay for each keypress
ajaxSearchRequest($type); //runs the ajax request
}, 3000);
}).keydown(function(){clearTimeout(window.timer);});
Here's the ajaxSearchRequest code:
function ajaxSearchRequest($type){
var ajaxRequest2; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest2 = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest2 = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest2 = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Browser error!");
return false;
}
}
}
ajaxRequest2.onreadystatechange = function(){
if(ajaxRequest2.readyState == 4){
$result = ajaxRequest2.responseText;
$('#resultcontainer').html($result);
}}
var searchterm = document.getElementById($type).value;
var queryString ="?searchterm=" + searchterm +"&type=" +$type;
if(searchterm !== ""){
ajaxRequest2.open("GET", "searchrequest.php" +
queryString, true);
ajaxRequest2.send(null);
}
}
store the timeout in a variable, so you will be able to clear recent timeouts:
clearTimeout(window.timer);
window.timer=setTimeout(function(){ // setting the delay for each keypress
ajaxSearchRequest($type); //runs the ajax request
}, 3000);
What you are trying to do is called debouncing.
Here's a jquery plugin by Ben Alman that does the job.
And underscore.js includes this functionality as well.
There's really no need to hack the ajax request system. Just make sure it's called at the right moment.
I like the Molle's answer But I would to further improve the performance
var ajaxRequest2; // The variable that makes Ajax possible!
function getAjaxObject()
{
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest2 = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest2 = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest2 = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Browser error!");
// return false;
}
}
}
return ajaxRequest2;
}
getAjaxObject();
function ajaxSearchRequest($type){
if(typeof ajaxRequest2 =="undefined" || ajaxRequest2 == false)
{
return;
}
ajaxRequest2.abort();
ajaxRequest2.onreadystatechange = function(){
if(ajaxRequest2.readyState == 4){
$result = ajaxRequest2.responseText;
$('#resultcontainer').html($result);
}}
var searchterm = document.getElementById($type).value;
var queryString ="?searchterm=" + searchterm +"&type=" +$type;
if(searchterm !== ""){
ajaxRequest2.open("GET", "searchrequest.php" +
queryString, true);
ajaxRequest2.send(null);
}
}
This change will abort an on going ajax request and send a fresh request. It is helpful when you
Typed-> waited 4 sec ->request sent ->typed again (response not received) ->waited 4 second->another request fires

Chained drop down box value not showing in IE 7,8,9 or lower browser

Here is my javascript code::---
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(str){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
var url="../frontend/views/home/category.php" + "?value="+str;
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//document.myForm.time.value = ajaxRequest.responseText;
document.getElementById("class").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
</script>

how can i do jquery's $.get in pure javascript? (without wanting to return anything)

I want the mobile version of my site to be as snappy as possible, however i still want some basic analytics.
I want to ping a php file (hit counter) after the mobile page has loaded to count the amount of hits from javascript enabled browsers.
Jquery's a bit overkill for 1 ajax function so i'm keen to learn how to do the following in pure javascript:
<script type="text/javascript">
Window.onload(function(){
$.get('mvc/assets/ajax/analytics/event_increment.php?id='+id');
})
</script>
Create a utility function that will return to you a browser-specific Ajax object:
function ajax(url, method, callback, params = null) {
var obj;
try {
obj = new XMLHttpRequest();
} catch(e){
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function() {
if(obj.readyState == 4) {
callback(obj);
}
}
obj.open(method, url, true);
obj.send(params);
return obj;
}
You could then call that function like this:
var ajax = ajax('someurl', 'get', function(obj) { alert(obj.responseText); })
Just specify your file as the src attribute for the script tag.
Something simplistic:
<div id="hidden"></div>
<script type="text/javascript">
window.onload = function(){
var div = document.getElementById("hidden");
div.innerHTML = "<img src='tracking.php' />";
};
</script>
#Mike is suggesting a great method. If you would like to get into AJAX, though, it's not that difficult.
Code c/o bobince
var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();
// FOR <IE8 Compatibility do this first:
if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
window.XMLHttpRequest= function() {
return new ActiveXObject('MSXML2.XMLHttp');
};
}
replace x.html with your php file
While it is possible to create an image tag with that url as the src if you want to do it via AJAX as jQuery does there you could do this:
<script type="text/javascript">
function report(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",'mvc/assets/ajax/analytics/event_increment.php?id='+id',true);
}
window.onload = report;
</script>
You can use an img tag and put that in the src, and have your script return a transparent image.
Or as someone else pointed out, have it be the src of a script tag.
EDIT
If you don't want it to load if a bot accesses the page, you could use an img tag still
<img src="transparent.gif" width="1" height="1" />
Then, use javascript to change the src of the image to your php script. Most bots won't execute the javascript and therefor will never access your php script.
You may want to obfuscate the javascript a little though, so they don't see a url in it and try and access it.
<script type="text/javascript">
Window.onload(function(){
var id = "", xmlhttp = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.open("GET","mvc/assets/ajax/analytics/event_increment.php?id=" + id,true);
xmlhttp.send();
}
})
</script>
there existed image preloaders in the early days of webpages, when internet connections were still slow, which created image objects to be used for rollover effects. this should still work and load the image:
<script type="text/javascript">
var img = new Image('http://url.to/your/image/or/script');
</script>
As 2019 you can use ES6 fetch a modern replacement for XMLHttpRequest.
const options = {
method: "POST",
data: {
title: "foo",
body: "bar",
userId: 1
},
credentials: "include",
headers: {}
};
fetch("https://jsonplaceholder.typicode.com/posts", options)
.then(response => {
return response.json();
})
.then(jsonObject => {
console.log(jsonObject);
document.write(`ID ${jsonObject.id} was created!`);
})
.catch(error => {
document.write(error);
});

Categories

Resources