codeigniter load googlemaps on ajax gives empty map_canvas - ajax

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

Related

AJAX works in IE but not in Firefox or Chrome

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.

fitBounds() is not working with geocoder function

I have just updated my code from v2 to v3. Every thing is working but the function map.fitBounds();
Here is my sample code
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'your address'}, >function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var newPoint = new google.maps.LatLng(results[0].geometry.location.lat(), >results[0].geometry.location.lng());
markerBounds.extend(newPoint);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
map.fitBounds(markerBounds);
}
I have found that this code looks fine but here fitBounds() will not work. The required change is mention in the answer below.
In this case we have to write code like this
markerBounds.extend(newPoint);
map.fitBounds(markerBounds); // here in function rather in the end
This worked for me hopefully will work for you as well.

XMLHttpRequest inside `onbeforeunload` handler not working in Opera

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.

Preload ajax loaded content

On my site I use one core/frame PHP file. If user hit one of my link (like contact, our about..etc..) the content loaded via ajax. I use the following snippet to achieve this:
var AjaxContent = function(){
var container_div = '';
var content_div = '';
return {
getContent : function(url){
$(container_div).animate({opacity:0},
function(){ // the callback, loads the content with ajax
$(container_div).load(url, //only loads the selected portion
function(){
$(container_div).animate({opacity:1});
}
);
});
},
ajaxify_links: function(elements){
$(elements).click(function(){
AjaxContent.getContent(this.href);
return false;
});
},
init: function(params){
container_div = params.containerDiv;
content_div = params.contentDiv;
return this;
}
}
}();
I need help how to integrate a preloading, so if visitors hit one of my link (for example the gallery menu) will see a little loading image, because now they see the big white nothing for long - long seconds.
Add loading image beforing ajax call and after you get response from server simply replace that image with data like the one below
function(){ // the callback, loads the content with ajax
$(container_div).html("<img src='loading.gif' />");//add image before ajax call
$(container_div).load(url, //only loads the selected portion
function(){
$(container_div).html(data);//replace image with server response data
$(container_div).animate({opacity:1});
}
Try this
var AjaxContent = function(){
var container_div = '';
var content_div = '';
return {
getContent : function(url){
$(container_div).html('Loading...'); //replace with your loading img html code
$(container_div).load(url, //only loads the selected portion
function(){
$(container_div).css({opacity:0});
$(container_div).animate({opacity:1});
});
},
ajaxify_links: function(elements){
$(elements).click(function(){
AjaxContent.getContent(this.href);
return false;
});
},
init: function(params){
container_div = params.containerDiv;
content_div = params.contentDiv;
return this;
}
}
}();

AJAX Ready State stuck on 1

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");
}
}

Resources