I have script like this:
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
alert("test" + this.chrono);
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + this.chrono, false); // async = false
blockingRequest.send();
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
PHP part (visitor_log/ajax_store_visit_duration.php file):
<?php
if(isset($_GET["visit_duration"]))
{
$text = $_GET["visit_duration"];
logtxt($text);
echo "OK";
}
else die("application error");
function logtxt($text)
{
$myFile = "test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
?>
It works in Chrome perfectly, but it doesn't work in Opera.
How to make it cross-browser?
It shouldn't work anywhere. getMilliseconds() returns the milliseconds portion of the date object, not some ultimate milliseconds value. The value is always under 1000. Not useful in comparisons of your magnitude. What you really want is universal time.
(new Date()).valueOf() should get you a value you can work with.
This may be a partial answer, since you didn't actually specify what's not working.
Related
i'm displaying a google maps in codeigniter and this works all fine.
But i'm using the same code in an ajax call, but than it outputs an empty map_canvas, so i don't see anything..
public function googlemapsAjax()
{
echo "
<script type='text/javascript'>
$.getScript('/assets/js/admin.js');
</script>
";
$this->load->library('googlemaps');
$config['center'] = '50.850340, 4.351710';
$config['zoom'] = '6';
$config['places'] = TRUE;
$config['placesAutocompleteInputID'] = 'location';
$config['placesAutocompleteBoundsMap'] = TRUE; // set results biased towards the maps viewport
$config['placesAutocompleteOnChange'] = '
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("location").value;
geocoder.geocode({ "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if(typeof marker != "undefined"){marker.setMap(null)};
$("#location").parent().removeClass("has-error");
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
$("#latitude").val(latitude);
$("#longitude").val(longitude);
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(latitude, longitude)
});
map.setCenter(new google.maps.LatLng(latitude, longitude), 16);
map.setZoom(16);
google.maps.event.addListener(marker, "dragend", function (event) {
latitude = this.getPosition().lat();
longitude = this.getPosition().lng();
$("#latitude").val(latitude);
$("#longitude").val(longitude);
});
} else {
alert("Request failed.")
$("#location").parent().addClass("has-error");
}
});
';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('admin/ajax/view_googlemaps_ajax', $data);
}
And in my view i have
echo $map['js'];
and
echo $map['html'];
Anyone knows why i have no output in map_canvas?
While it works perfectly if i don't do it over ajax..
#jen_vdp - Thanks for using my library. I've taken a look and believe the issue is to do with how the map is called/initialized.
If you revert back to the non-ajax version and view the page source, you will see that the map is initialized through the following code:
google.maps.event.addDomListener(window, "load", initialize_map);
Obviously, if you load the map via AJAX, the window is already loaded, and therefore, I don't 'think' this will get executed.
My suggestion would be to manually call the JS function initialize_map() on the success callback of your AJAX request.
That's the only thing I can think that it might be at this time. Do let me know if you continue to experience issues and I'll investigate further.
Thanks,
Steve
I'm new to using AJAX and my code works in Internet Explorer but not in Firefox or Chrome.
I do not know what it is exactly what should change in the code ...
// I think that error should be here :-)
function cerrar(div)
{
document.getElementById(div).style.display = 'none';
document.getElementById(div).innerHTML = '';
}
function get_ajax(url,capa,metodo){
var ajax=creaAjax();
var capaContenedora = document.getElementById(capa);
if (metodo.toUpperCase()=='GET'){
ajax.open ('GET', url, true);
ajax.onreadystatechange = function() {
if (ajax.readyState==1){
capaContenedora.innerHTML= "<center><img src=\"imagenes/down.gif\" /><br><font color='000000'><b>Cargando...</b></font></center>";
} else if (ajax.readyState==4){
if(ajax.status==200){
document.getElementById(capa).innerHTML=ajax.responseText;
}else if(ajax.status==404){
capaContenedora.innerHTML = "<CENTER><H2><B>ERROR 404</B></H2>EL ARTISTA NO ESTA</CENTER>";
} else {
capaContenedora.innerHTML = "Error: ".ajax.status;
}
} // ****
}
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send(null);
return
}
}
function creaAjax(){
var objetoAjax=false;
try{objetoAjax = new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){try {objetoAjax = new ActiveXObject("Microsoft.XMLHTTP");}
catch (E){objetoAjax = false;}}
if(!objetoAjax && typeof XMLHttpRequest!='undefined') {
objetoAjax = new XMLHttpRequest();} return objetoAjax;
}
//These functions are connected with a form
function resultado(contenido){
var url='ajax/buscar.php?'+ contenido +'';// Vota Resultado
var capa='resultado';
var metodo='get';
get_ajax(url,capa,metodo);
}
function paginas(contenido){
var url='ajax/paginar.php?'+ contenido +'';// Vota Paginas
var capa='paginas';
var metodo='get';
get_ajax(url,capa,metodo);
}
Strongly suggest that you use a lib like jQuery that encapsulates a lot of what you're doing above, masking cross-browser issues (current and future). Even if you don't want to use jQuery site-wide, you could still use it just for its AJAX functionality.
I'm going a little crazy trying to understand why this outputs the json data once and then not again as per timeout function. What am I doing wrong?
<script type="text/javascript">
var myTimer =0;
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("POST", "ballJson.php",true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var obj in data){
results.innerHTML += data[obj]+"<br />";
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
myTimer = setTimeout('ajax_get_json()',10000);
}
</script>
I think that you want to use the setInterval function as setTimeout only executes one time.
It is also much preferred to use setTimeout(function () { ajax_get_json(); }, 10000) or setTimeout(ajax_get_json, 10000) instead of using a string that is evaluated as the function callback.
Also note that the ajax requests may complete at any time, so it won't exactly be once every 10 seconds using setInterval. You could also call setTimout in the onreadystatechange callback to chain the calls.
Hi I can see this has been discussed but after perusing the issues/answers I still don't seem to be able to get even this simple AJAX call to bump out of ready state 1.
Here's the Javascript I have:
<script language="javascript" type="text/javascript">
var request;
function createRequest()
{
try
{
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
function loadClassesBySchool()
{
//get require web form pieces for this call
createRequest(); // function to get xmlhttp object
var schoolId = getDDLSelectionValue("ddlSchools");
var grade = getDDLSelectionValue("ddlGrades");
var url = "courses.php?grades=" + escape(grade) + "&schoolId=" + escape(schoolId);
//open server connection
request.open("GET", url, true);
//Setup callback function for server response
//+++read on overflow that some fixed the issue with an onload event this simply had
//+++the handle spitback 2 readystate = 1 alerts
request.onload = updateCourses();
request.onreadystatechanged = updateCourses();
//send the result
request.send();
}
function updateCourses()
{
alert('ready state changed' + request.readyState);
}
function getDDLSelectionValue(ddlID)
{
return document.getElementById(ddlID).options[document.getElementById(ddlID).selectedIndex].value;
}
</script>
The PHP is HERE just a simple print which if i navigate to in the browser (IE/Chrome) loads fine:
<?php
print "test";
?>
I'm quite new at this but seems like I can't get the most bare bones AJAX calls to work, any help as to how work past this would be greatly appreciated.
All I get out of my callback function 'updateCourses' is a 1...
Well after more digging I actually gave up and switched over to jQuery which should for all intents and purposes be doing the EXACT same thing except for the fact that jQuery works... I was just less comfortable with it but so be it.
Here's the jQuery to accomplish the same:
function loadCoursesBySchool(){
var grades = getDDLSelectionValue("ddlGrades");
var schoolId = getDDLSelectionValue("ddlSchools");
jQuery.ajax({
url: "courses.php?grades=" + grades + "&schoolId=" + schoolId,
success: function (data) {
courseDisplay(data);
}
});
}
function courseDisplay(response)
{
//check if anything was setn back!?
if(!response)
{
$("#ddlCourses").html("");
//do nothing?
}
else
{
//empty DLL
$("#ddlCourses").html("");
//add entries
$(response).appendTo("#ddlCourses");
}
}
I don't understand this. I have an innerHTML request.
<div id="targetDiv"></div>
One of the includes is:
<?php
echo ("Hello, world");
?>
and works fine, but if I do:
<?php
echo ("Hello, world");
?>
<!--
lots of code I'm trying to debug
-->
it doesn't work.
Why?
getData:
<script language = "javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
It looks mostly likely to be a bug in your PHP code rather than your javascript code. I recommend that you type in the PHP script's URL into your browser and check if it produces the expected output. Better still I recommend that you install firebug. That will allow you to check each and every ajax request as it happens. Better still it will allow you to debug your javascript and inspect variables.