amCharts js doesnt work with ajax call? - php

I am trying create map with amCharts using jquery ajax but it doesnt work with ajax.
here my ajax code:
$('button#btn').click(function(){
$('div#ozellikli').html('<center><img src="assets/img/loading.gif" width="200" height="200"/></center>')
$.ajax({
type:'post',
url:'ozellikliAjax.php',
data:$('form#oz').serialize(),
success:function(msg){
$('div#ozellikli').html(msg);
}
});
});
Here my ajax php code:
<?php
include 'config.php';
$html="";
$yil=$_POST['yil'];
$tur=$_POST['tur'];
///HARITAYI CIZ
$sql="SELECT id,il,COUNT(kurum) AS kurum_Say FROM ozellikli GROUP BY id,il ORDER BY kurum_Say";
$result=$baglanti->query($sql);
$mapChart="";
while ($query=$result->fetch(PDO::FETCH_ASSOC)) {
$mapChart.=' { title: "'.$query['il'].':'.$query['kurum_Say'].'", id: "TR'.$query['id'].'",value:'.$query['kurum_Say'].', selectable: true },';
}
$html.='<script type="text/javascript">
AmCharts.ready(function() {
var map;
// *** CREATE MAP ***********************************************************
function createMap(){
map = new AmCharts.AmMap();
map.pathToImages = "http://www.ammap.com/lib/images/";
//map.panEventsEnabled = true; // this line enables pinch-zooming and dragging on touch devices
var dataProvider = {
mapVar: AmCharts.maps.turkeyLow
};
map.areasSettings = {
unlistedAreasColor: "#43B1A9",
rollOverOutlineColor: "#FFFFFF"
};
map.colorSteps=5;
map.valueLegend={
left: 10,
bottom:0,
minValue: "En Az",
maxValue: "En Çok"
};
dataProvider.areas = ['.$mapChart.'];
map.dataProvider = dataProvider;
map.addListener(\'clickMapObject\', function (event) {
// deselect the area by assigning all of the dataProvider as selected object
map.selectedObject = map.dataProvider;
// toggle showAsSelected
event.mapObject.showAsSelected = !event.mapObject.showAsSelected;
// bring it to an appropriate color
map.returnInitialColor(event.mapObject);
var states = [];
for (var i in map.dataProvider.areas) {
var area = map.dataProvider.areas[i];
if (area.showAsSelected) {
states.push(area.title);
}
}
});
map.write("mapdiv");
}
createMap();
});
</script>';
echo $html;
?>
when run the ajax code , script loading with ajax correctly but its not charting to map.
How can I solve this issue?
thanks

If you inject the resources the same way, you need to set manually it's ready state otherwise it won't work. AmCharts listens to the dom loaded event to set following property:
AmCharts.isReady = true;

Related

Too many connections to db error, after adding an ajax auto save

I have PHP site with MySql data base
I just added automatic save for a text area
and one of the users received the following error:
Too many connections in ...Unable to connect to database
maybe I have to change my ajax auto save:
bkLib.onDomLoaded(function(){
var myEditor = new nicEditor({iconsPath : 'include/nicEdit/nicEditorIcons.gif'}).panelInstance('area1');
auto_save_func(myEditor);
});
function auto_save_func(myEditor)
{
draft_content=myEditor.instanceById('area1').getContent();
int_id='<?=$_GET[interview_id]?>';
$.post("ajax_for_auto_save_interview.php", { interview_id: int_id,content:draft_content},
function(data){ });
setTimeout( function() { auto_sav_func(myEditor); }, 100);
}
in the page "ajax_for_auto_save_interview.php" I`m including the connection to the DB.
First thing is you should close your mysql connection every time you open it after your usage.
You can have a javascript variable to check whether an AJAX call is already issued and is it finished or not. Only if it is finished, you can re-issue new call
Like this:
var isAjaxStarted = 0;
bkLib.onDomLoaded(function(){
var myEditor = new nicEditor({iconsPath : 'include/nicEdit/nicEditorIcons.gif'}).panelInstance('area1');
if(isAjaxStarted == 0)
auto_save_func(myEditor);
});
function auto_save_func(myEditor)
{
isAjaxStarted = 1;
draft_content=myEditor.instanceById('area1').getContent();
int_id='<?=$_GET[interview_id]?>';
$.post("ajax_for_auto_save_interview.php", { interview_id: int_id,content:draft_content},
function(data){ isAjaxStarted = 0; });
setTimeout( function() { auto_sav_func(myEditor); }, 100);
}
maybe I am writing late you help in place it? thank you very much
<script type="text/javascript">
bkLib.onDomLoaded(function() {
var myNicEditor = new nicEditor({buttonList : ['bold','italic','underline','strikethrough','left','center','right','justify',/*'ol','ul',*/'forecolor',/*'fontSize','fontFamily',*//*'fontFormat',*//*'indent','outdent',*/'image','upload','link','unlink'/*,'bgcolor'*/,'hr','removeformat', 'youTube'/*,'subscript','superscript'*/],/*fullPanel : true,*/
iconsPath : '<? echo "".$IndirizzoPagina."".$IndirizzoCartella."";?>default/image/EditorDiTesto/nicEditorIcons.gif'});
myNicEditor.setPanel('myNicPanel'); //PANNELLO DI CONTROLLO
myNicEditor.addInstance('titolo'); //TITOLO
myNicEditor.addInstance('contenuto'); //CONTENUTO
});
<textarea name='contenuto' id='contenuto' class='box2'>".$ContenutoNotizia."</textarea>"
i used this code http://nicedit.com/

multiple highcharts on one page

I'm wishing to render multiple charts using mysql data, there will be more or less charts depending on a particular search. I've successfully created a single chart, and my php file echoes the required json format nicely.
Now, what I would like is to be able to loop over an array and draw new charts based on the array vales being parsed to the php which in turn provides different json data to be rendered.
by the way, my javasript is very limited so here goes my code and thoughts:
<script type="text/javascript">
$(function () {
var chart;
var venue = <?php echo json_encode($venue_name); ?>; /* parsed to php file */
var distances = <?php echo json_encode($data); ?>; /* array to be looped over */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue='+venue+'&'+distances
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart = new Highcharts.Chart(options);
});
});
</script>
What I have learnt is that I cannot loop an include php file which has the completed php and jquery...
this will create other charts. every time u want create new chart , u must give new name chart like i do chart2
paste this bellow and it will give you other chart.
<script type="text/javascript">
$(function () {
var chart2;
var venue2 = <?php echo json_encode($venue_name); ?>; /* <---use other variable here of $venue_name */
var distances2 = <?php echo json_encode($data); ?>; /* <---use other variable of $data */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances2, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue2='+venue2+'&'+distances2
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart2 = new Highcharts.Chart(options);
});
});
</script>
Instead of using many variables, you can push your charts to array.
var charts = [];
charts.push(new Highcharts(options));
Then you can avoid of using index etc.

Retrieving data from server using jquery $.get function

I am creating a real-time graph with flot library and using jquery $.get function.
I want the graph to be updated every 5 seconds retrieving the recorded data.
The X axis is in time mode. I have been trying to retrieve the necessary data but i can't get it yet. The .php file is fine because it connects to the postgresql database and writes the data into the requested variable.
I think that my problem is in the $.get function.
Can you please help me to find if my Javascript code is fine?
Thanks in advance
<script type="text/javascript">
$(function () {
var data=[];
var data_inicial = [];
var data_actual = [];
var x;
var y;
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; });
data_inicial.push([x]);
return data_inicial;
}
function actualiza_data()
{
$.get("param_pozos_linea2.php", function(data2) { y= data2; });
data_actual.push(y);
return data_actual;
}
// control de velocidad
var updateInterval = 500;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
series: { shadowSize: 0 }, // drawing is faster without shadows
yaxis: { min: 0, max: 100 },
xaxis: { mode: "time",tickLength: 5, timeformat: "%d/%m - %h:%M %p"}
};
var plot = $.plot($("#placeholder"), data_init() , options);
function update() {
plot.setData([ actualiza_data() ]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
</script>
The retrieved data from "param_pozos_linea1.php" file loooks like this:
[1355767803000,0],[1355767502000,0],[1355767202000,0],[1355766902000,0],[1355766602000,0],[1355766302000,0],[1355766002000,0],[1355765702000,0],[1355765402000,0],[1355765103000,2570.17],[1355764803000,2569.63]
And the retrieved data from "param_pozos_linea2.php" looks like this:
[1355767803000,0]
The get request is asynchronous, it is impossible for it to work in a synchronous manner like you think it does.
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; }); <-- calls the server asynchronously
data_inicial.push([x]); <-- is called before code is set on server, so it is setting it with what ever the last value was
return data_inicial; <-- returns something you do not want
}
what you want to do is call the function that set the data
function data_init()
{
$.get("param_pozos_linea1.php",
function(data1) {
data_inicial.push([data1]);
callYourPlotFunction(data_inicial);
}
);
}

Ajax Instant Messenger Using PHP

Trying to create an AJAX IM for my site...
need to load the part of page when row is inserted into mysql DB ... can anybody help me with this.. thanks in advance
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
var waittime=2000;
var intUpdate = null;
function verifDB(){
$.ajax({
type: "POST",
url: "verifdb.php",
success: function(msg){
alert(msg),;
}
});
intUpdate = setTimeout("verifDB()", waittime);
}
verifDB();
</script>
verifdb.php file is queried every 2000 ms to check on the database
you can put your file in requette verifdb.php
and you will have the answer in the variable msg
Client Side
For assyncronous requests on the client side you can use JQuery or plain Javascript XMLHTTPRequest
Server Side
I know you've specified PHP but I would recommend you to check how google channels work and make a similar implementation in PHP.
Since checking having multiple users checking for updates on the database, I would recommend you to use memcache.
Something like:
$script_called_time = time();
while($memcache->get('last_message') < $script_called_time){
usleep(100);
}
$result = $database->query("SELECT * FROM `messages` WHERE `date` > " . $script_called_time . "'");
...
This way the connection will be established and the user will receive a response when there's any...
(function() {
var chat = {
messageToSend: "",
messageResponses: [
"I Love You",
"I Wants to Kiss You.",
'Hug Me!"',
"Lets Sleep Together",
"Lets go for a date",
"Will you be physical with me?"
],
init: function() {
this.cacheDOM();
this.bindEvents();
this.render();
},
cacheDOM: function() {
this.$chatHistory = $(".chat-history");
this.$button = $("button");
this.$textarea = $("#message-to-send");
this.$chatHistoryList = this.$chatHistory.find("ul");
},
bindEvents: function() {
this.$button.on("click", this.addMessage.bind(this));
this.$textarea.on("keyup", this.addMessageEnter.bind(this));
},
render: function() {
this.scrollToBottom();
if (this.messageToSend.trim() !== "") {
var template = Handlebars.compile($("#message-template").html());
var context = {
messageOutput: this.messageToSend,
time: this.getCurrentTime()
};
this.$chatHistoryList.append(template(context));
this.scrollToBottom();
this.$textarea.val("");
// responses
var templateResponse = Handlebars.compile(
$("#message-response-template").html()
);
var contextResponse = {
response: this.getRandomItem(this.messageResponses),
time: this.getCurrentTime()
};
setTimeout(
function() {
this.$chatHistoryList.append(templateResponse(contextResponse));
this.scrollToBottom();
}.bind(this),
1500
);
}
},
addMessage: function() {
this.messageToSend = this.$textarea.val();
this.render();
},
addMessageEnter: function(event) {
// enter was pressed
if (event.keyCode === 13) {
this.addMessage();
}
},
scrollToBottom: function() {
this.$chatHistory.scrollTop(this.$chatHistory[0].scrollHeight);
},
getCurrentTime: function() {
return new Date()
.toLocaleTimeString()
.replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3");
},
getRandomItem: function(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
};
chat.init();
var searchFilter = {
options: { valueNames: ["name"] },
init: function() {
var userList = new List("people-list", this.options);
var noItems = $('<li id="no-items-found">No items found</li>');
userList.on("updated", function(list) {
if (list.matchingItems.length === 0) {
$(list.list).append(noItems);
} else {
noItems.detach();
}
});
}
};
searchFilter.init();
})();
Messenger Using Jquery And PHP
If you needs any help regarding this answer feel free to contact me at pachauriashokkumar[at]gmail[dot]com if you need complete code with css JS and HTML Drop me an email i will email the code to you
External Files are needed
https://code.jquery.com/jquery-3.4.1.js
https://cdn.jsdelivr.net/npm/handlebars#latest/dist/handlebars.js
https://raw.githubusercontent.com/javve/list.js/v1.5.0/dist/list.min.js
Messenger Using JQuery And PHP Demo Is Here Also Author of This Post on PenCode is available for clarification over email pachauriashokkumar[at]gmail[dot]com

JavaScript DOM Error in Internet Explorer

I'm receiving the following error on this line of code
select.up().appendChild(sw);
With error "SCRIPT438: Object doesn't support property or method 'up' "
This only happens in Internet Explorer... Chrome, Safari, and Firefox all run the code fine. I'm unable to find anything via Google searching for "select.up()". This code isn't my own and I'm not very adept with using DOM in Javascript.
Here is rest of the code:
<?php
$swatches = $this->get_option_swatches();
?>
<script type="text/javascript">
document.observe('dom:loaded', function() {
try {
var swatches = <?php echo Mage::helper('core')->jsonEncode($swatches); ?>;
function find_swatch(key, value) {
for (var i in swatches) {
if (swatches[i].key == key && swatches[i].value == value)
return swatches[i];
}
return null;
}
function has_swatch_key(key) {
for (var i in swatches) {
if (swatches[i].key == key)
return true;
}
return false;
}
function create_swatches(label, select) {
// create swatches div, and append below the <select>
var sw = new Element('div', {'class': 'swatches-container'});
select.up().appendChild(sw);
// store these element to use later for recreate swatches
select.swatchLabel = label;
select.swatchElement = sw;
// hide select
select.setStyle({position: 'absolute', top: '-9999px'})
$A(select.options).each(function(opt, i) {
if (opt.getAttribute('value')) {
var elm;
var key = trim(opt.innerHTML);
// remove price
if (opt.getAttribute('price')) key = trim(key.replace(/\+([^+]+)$/, ''));
var item = find_swatch(label, key);
if (item)
elm = new Element('img', {
src: '<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>swatches/'+item.img,
alt: opt.innerHTML,
title: opt.innerHTML,
'class': 'swatch-img'});
else {
console.debug(label, key, swatches);
elm = new Element('a', {'class': 'swatch-span'});
elm.update(opt.innerHTML);
}
elm.observe('click', function(event) {
select.selectedIndex = i;
fireEvent(select, 'change');
var cur = sw.down('.current');
if (cur) cur.removeClassName('current');
elm.addClassName('current');
});
sw.appendChild(elm);
}
});
}
function recreate_swatches_recursive(select) {
// remove the old swatches
if (select.swatchElement) {
select.up().removeChild(select.swatchElement);
select.swatchElement = null;
}
// create again
if (!select.disabled)
create_swatches(select.swatchLabel, select);
// recursively recreate swatches for the next select
if (select.nextSetting)
recreate_swatches_recursive(select.nextSetting);
}
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
function trim(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
$$('#product-options-wrapper dt').each(function(dt) {
// get custom option's label
var label = '';
$A(dt.down('label').childNodes).each(function(node) {
if (node.nodeType == 3) label += node.nodeValue;
});
label = trim(label);
var dd = dt.next();
var select = dd.down('select');
if (select && has_swatch_key(label)) {
create_swatches(label, select);
// if configurable products, recreate swatches of the next select when the current select change
if (select.hasClassName('super-attribute-select')) {
select.observe('change', function() {
recreate_swatches_recursive(select.nextSetting);
});
}
}
});
}
catch(e) {
alert("Color Swatches javascript error. Please report this error to support#ikova.com. Error:" + e.message);
}
});
</script>
Appreciate any insight anyone could give me!
I'm pretty sure up() is a PrototypeJS method, so i'm pretty sure you would need it to work.
http://prototypejs.org/api/element/up
I m also facing this problem. so, i comment
var sw = new Element('div', {'class': 'swatches-container'});
$(select).up().appendChild(sw);
select.setStyle({position: 'absolute', top: '-9999px'})
lines from function create_swatches
and paste it in function trim(str).
After this i did not error again.

Categories