jQuery doesnt work at all in IE8 - php

I have read lots of past postings on this subject...
I have tried every "solution", change to type="text/javascript", upgrade it to the latest version, including this header <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> but nothing seems to work.
The site is testing.quierodecomer.com
NOTE: I wrote <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" /> in the head for testing issues.
<?php
session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
<title>Quiero de comer!</title>
<link href="favicon.png" type="image/png" rel="icon">
<style>
.ui-autocomplete-loading { background: white url('jquery-ui-1.8.21.custom/css/ui-lightness/images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<link rel="stylesheet" type="text/css" href="jquery-ui-1.8.21.custom/css/ui-lightness/jquery-ui-1.8.21.custom.css" />
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<link rel="stylesheet" type="text/css" href="css/fonts.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.imageZoom.css" />
<style type="text/css">
body {
padding: 0px;
vertical-align:bottom;
}
#container {
position: absolute;
margin: 0px;
padding: 0px;
width: 100%;
height: 360px;
overflow: hidden;
text-align:center;
}
.box {
position: absolute;
width: 400px;
height: 200px;
line-height: 40px;
font-size: 30px;
font-weight:bold;
color:black;
text-align: center;
border: 3px solid grey;
left: 50%;
top: 100px;
-webkit-border-radius:60px;
-moz-border-radius:60px;
border-radius:60px;
margin-top:-70px;
margin-left: -200px;
}
#box1 {
background-color:#FFF;
}
#box2 {
background-color:#FFF;
left: 150%;
}
#box3 {
background-color:#FFF;
left: 150%;
}
.btn1, .coloniaButton{
background:#ff5d35;
border:none;
-webkit-border-radius:10px;
-moz-border-radius:10px;
border-radius:10px;
vertical-align:middle;
cursor:pointer;
color:#fff;
font-weight:bold;
font-size:20px;
padding:5px 10px;
margin-right:-225px;
border: 1px solid #000;
}
.btn1:hover, .coloniaButton:hover{
background:#3f3f3f;
}
#tags, #tipoDeComida, #tags2, #city {
padding:.8em;
-moz-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
border-radius: 10px 10px 10px 10px;
border:none;
width:350px;
margin-bottom:5px;
border: 2px solid grey;
}
.titulo{
margin-top: 23px;
}
.caja{
margin-top: 20px;
}
.servicios{
font-size:15px;
font-weight:bold;
}
#ciudadBreadcrumb, #coloniaBreadcrumb{
font-size: 15px;
}
#footer{
text-align: center;
background-color: black;
width: 99.2%;
padding: 5px;
color: white;
position: absolute;
bottom: 0px;
}
</style>
<link rel="stylesheet" href="css/supersized.css" type="text/css" media="screen" />
<link rel="stylesheet" href="theme/supersized.shutter.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/flexslider.css" type="text/css">
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery.paginatetable.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/md5.js"></script>
<script type="text/javascript" src="js/jquery.flexslider.js"></script>
<script type="text/javascript" src="js/jquery.easing.min.js"></script>
<script type="text/javascript" src="js/supersized.3.2.6.min.js"></script>
<script type="text/javascript" src="theme/supersized.shutter.min.js"></script>
<script type="text/javascript" src="js/jquery.imageZoom.js"></script>
<?php
include("conecta.php");
$result = mysql_query("SELECT * FROM fondo WHERE id = 1");
while($row = #mysql_fetch_array($result)){
$fondo = $row['imgFondo'];
}
?>
<script type="text/javascript">
jQuery(function($){
$.supersized({
// Functionality
slide_interval : 3000, // Length between transitions
transition : 1, // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 700, // Speed of transition
// Components
slide_links : 'blank', // Individual links for each slide (Options: false, 'num', 'name', 'blank')
slides : [ // Slideshow Images
{image : 'admin/uploads/fondos/<?php echo $fondo; ?>', title : '', thumb : '', url : ''}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#colonia").hide();
$('.btn1').click(function() {
$('.box').each( function() {
if ($(this).offset().left < 0) {
$(this).css("left", "150%");
}
});
$(this.parentNode).animate({
left: '-50%'
}, 500);
if ($(this.parentNode).next().size() > 0) {
$(this.parentNode).next().animate({
left: '50%'
}, 500);
} else {
$(this.parentNode).prevAll().last().animate({
left: '50%'
}, 500);
}
});
$('#domicilio').click(function() {
$('.box').each( function() {
if ($(this).offset().left < 0) {
$(this).css("left", "150%");
}
});
$(this.parentNode.parentNode).animate({
left: '-50%'
}, 500);
if ($(this.parentNode.parentNode).next().size() > 0) {
$(this.parentNode.parentNode).next().animate({
left: '50%'
}, 500);
} else {
$(this.parentNode.parentNode).prevAll().last().animate({
left: '50%'
}, 500);
}
});
$('#colonia').click(function() {
setCookie("domicilio", "tipoDeServicio");
});
$('#ciudad').click(function() {
var e = document.getElementById("city");
var city = e.options[e.selectedIndex].value;
setCookie(city, "puraCiudad");
});
jQuery(document.body).imageZoom();
$('#pager').hide();
clienteBar();
$("#crossCiudad").hide();
$("#crossColonia").hide();
loadBreadcrumbs();
getTipoDeComida();
getCiudades();
$("#enviarSignUp").button();
$( "#logInContainer" ).dialog({
autoOpen: false,
height: 420,
width: 750,
modal: true,
buttons: {
"Regresar": function() {
$( this ).dialog( "close" );
}
},
});
$("#afiliarte").dialog({
autoOpen: false,
height: 350,
width: 450,
modal: true,
buttons: {
"Enviar": function() {
//function
},
"Regresar": function() {
$( this ).dialog( "close" );
}
},
});
$("#contactanos").dialog({
autoOpen: false,
height: 350,
width: 450,
modal: true,
buttons: {
"Enviar": function() {
//function
},
"Regresar": function() {
$( this ).dialog( "close" );
}
},
});
$( "#sugerirRestaurantes" ).dialog({
autoOpen: false,
height: 350,
width: 450,
modal: true,
buttons: {
"Enviar": function() {
//function
},
"Regresar": function() {
$( this ).dialog( "close" );
}
},
});
$( "#terminosCondiciones" ).dialog({
autoOpen: false,
height: 350,
width: 450,
modal: true,
});
$( "#signUpContainer" ).dialog({
autoOpen: false,
height: 320,
width: 480,
modal: true,
buttons: {
"Enviar": function() {
signUp();
},
"Regresar": function() {
document.getElementById("notificationCC").value = "";
$( this ).dialog( "close" );
}
},
})
});
function logInDialog(){
$( "#logInContainer" ).dialog( "open" );
}
function sugerirRestaurantesDialog(){
$( "#sugerirRestaurantes" ).dialog( "open" );
}
function terminosCondicionesDialog(){
$( "#terminosCondiciones" ).dialog( "open" );
}
function afiliarteDialog(){
$( "#afiliarte" ).dialog( "open" );
}
function contactanosDialog(){
$( "#contactanos" ).dialog( "open" );
}
function signUpDialog(){
$( "#signUpContainer" ).dialog( "open" );
}
function send(str, flag){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//callback
//xmlhttp.responseText
switch(flag){
case "setCookie": setCookieCallback(xmlhttp.responseText);break;
case "deleteCookie": deleteCookieCallback(xmlhttp.responseText); break;
case "loadBreadcrumbs": loadBreadcrumbsCallback(xmlhttp.responseText);break;
case "getRestaurantes": getRestaurantesCallback(xmlhttp.responseText);break;
case "logIn": logInCallback(xmlhttp.responseText);break;
case "signUp": signUpCallback(xmlhttp.responseText);break;
case "logOut": logOutCallback(xmlhttp.responseText);break;
}
}
}
xmlhttp.open("GET",str,true);
xmlhttp.send();
}
function loadBreadcrumbs(){
//Checkboxes
if(document.getElementById('domicilioBreadcrumb').value == "set"){
document.getElementById('domicilio').checked = true;
}
if(document.getElementById('recogerBreadcrumb').value == "set"){
document.getElementById('recoger').checked = true;
}
if(document.getElementById('reservacionBreadcrumb').value == "set"){
document.getElementById('reservacion').checked = true;
}
var str = "printCookie.php";
send(str, "loadBreadcrumbs");
}
function loadBreadcrumbsCallback(response){
var arr = response.split("/");
//alert(response);
var colonia = arr[0].split("=");
var ciudad = arr[1].split("=");
var estado = arr[2].split("=");
var tipoDeComida = arr[3].split("=");
if(colonia[1] != ""){
document.getElementById("coloniaBreadcrumb").innerHTML = colonia[1]+"<br />";
$("#colonia").show();
}
if(ciudad[1] != ""){
document.getElementById("ciudadBreadcrumb").innerHTML = ciudad[1] + ", " + estado[1]+"<br />";
}
//document.getElementById("tipoDeComidaBreadcrumb").innerHTML = tipoDeComida[1];
if(document.getElementById('ciudadBreadcrumb').innerHTML == ""){
$("#crossCiudad").hide();
} else {
$("#city").hide();
$("#crossCiudad").show();
}
if(document.getElementById('coloniaBreadcrumb').innerHTML == ""){
$("#crossColonia").hide();
} else {
$("#tags2").hide();
$("#crossColonia").show();
}
//alert(colonia[1]+", "+ciudad[1]+", "+tipoDeComida[1]);
//getRestaurantes(colonia[1], ciudad[1], tipoDeComida[1]);
}
function handleSearch(event, ui){
term = document.getElementById("tags").value;
$.ajax({
url: 'loadCiudades.php?term='+term,
success: function(data) {
if(data == '[]'){
restaurantes = document.getElementById("content-background");
imagen = document.getElementById("proximamente");
restaurantes.style.display = "none";
imagen.style.display = "block";
}else{
restaurantes = document.getElementById("content-background");
imagen = document.getElementById("proximamente");
restaurantes.style.display = "block";
imagen.style.display = "none";
}
}
});
}
function getCiudades(){
ciudad = "<?php echo $_COOKIE['ciudad']; ?>";
$( "#tags2" ).autocomplete({
source: "loadCiudades.php?ciudad="+ciudad,
select: function(event, ui) {
setCookie(ui.item.value, "ciudad");
},
search: function(event, ui){ handleSearch(event,ui); }
});
}
function getTipoDeComida(){
$("#tipoDeComida").autocomplete({
source: "loadTipoDeComida.php",
select: function(event, ui) {
setCookie(ui.item.value, "tipoDeComida");
}
});
}
function setCookie(cookieValue, cookieType){
var str = "setCookie.php?cookieValue=" + cookieValue + "&cookieType=" + cookieType;
send(str, "setCookie");
}
function setCookieCallback(response){
switch(response){
case "puraCiudad": document.getElementById("tags").value = "";
$("#crossCiudad").show();
$("#city").hide();
break;
case "tipoDeComida": document.getElementById("tipoDeComida").value = "";
$("#crossComida").show();
$("#tipoDeComida").hide();
break;
case "ciudad": document.getElementById("tags2").value = "";
$("#crossColonia").show();
$("#tags2").hide();
$("#colonia").hide();
break;
case "tipoDeServicio": parent.location='index2.php';
break;
}
loadBreadcrumbs();
}
function getRestaurantes(colonia2, ciudad2, tipo2){
var direccion = document.getElementById('tags').value;
//var colonia = direccion.split(',')[0];
//var ciudad = direccion.split(',')[1];
var colonia = trim(colonia2);
var ciudad = trim(ciudad2);
var tipoComida = trim(tipo2);
var str = "getRestaurantes.php?colonia=" + colonia + "&ciudad=" + ciudad + "&tipoComida=" + tipoComida;
send(str, "getRestaurantes");
}
function getRestaurantesCallback(response){
if(response == "empty"){
document.getElementById('paging').innerHTML = "";
$('#pager').hide();
} else {
var arr = response.split("|");
var restaurantes = arr[0];
var promociones = arr[1];
var numPag = arr[2]/4;
document.getElementById("promocionesContainer").innerHTML = promociones;
$('#pager').show();
document.getElementById('paging').innerHTML = restaurantes;
$('#myTable').paginateTable({ rowsPerPage: numPag });
if(document.getElementById('totalPages').innerHTML == ""){
document.getElementById('pager').style.display = "none";
} else {
document.getElementById('pager').style.display = "block";
}
}
}
function stripVowelAccent(str)
{
var rExps=[
{re:/[\xC0-\xC6]/g, ch:'A'},
{re:/[\xE0-\xE6]/g, ch:'a'},
{re:/[\xC8-\xCB]/g, ch:'E'},
{re:/[\xE8-\xEB]/g, ch:'e'},
{re:/[\xCC-\xCF]/g, ch:'I'},
{re:/[\xEC-\xEF]/g, ch:'i'},
{re:/[\xD2-\xD6]/g, ch:'O'},
{re:/[\xF2-\xF6]/g, ch:'o'},
{re:/[\xD9-\xDC]/g, ch:'U'},
{re:/[\xF9-\xFC]/g, ch:'u'},
{re:/[\xD1]/g, ch:'N'},
{re:/[\xF1]/g, ch:'n'} ];
for(var i=0, len=rExps.length; i<len; i++)
str=str.replace(rExps[i].re, rExps[i].ch);
return str;
}
function deleteCookie(cookieType){
var str = "deleteCookie.php?cookieType=" + cookieType;
send(str, "deleteCookie");
}
function deleteCookieCallback(response){
//Borra el breadcrumb
switch(response){
case "puraCiudad": document.getElementById("ciudadBreadcrumb").innerHTML = "";
$("#crossCiudad").hide();
$("#city").show();
break;
case "tipoDeComida": document.getElementById("tipoDeComidaBreadcrumb").innerHTML = "";
$("#crossComida").hide();
$("#tipoDeComida").show();
break;
case "ciudad": document.getElementById("coloniaBreadcrumb").innerHTML = "";
$("#crossColonia").hide();
$("#tags2").show();
$("#colonia").hide();
break;
}
getRestaurantes();
}
function setCookieCheck(check, cookieType){
if(check.checked){
setCookie(1, cookieType);
} else {
deleteCookie(cookieType);
}
}
function logIn(){
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if(email == "" || password == ""){
document.getElementById("notification").innerHTML = "Ingresa tu email y contraseña";
} else {
password = hex_md5(password);
var str = "logIn.php?password=" + password + "&email=" + email;
send(str, "logIn");
}
}
function logInCallback(response){
if(response == "not_logged/0"){
document.getElementById("notification").innerHTML = "Las credenciales no son válidas";
} else {
document.getElementById("notification").innerHTML = "";
$("#logInBar").hide();
$("#logInBarMenu").hide();
$("#signUpBar").hide();
$("#clienteBar").show();
arr = response.split("/");
document.getElementById("usuarioIDnombre").innerHTML = arr[1];
$("#logInContainer").dialog("close");
loadColonia();
}
}
function loadColonia(){
var str = "getColonia.php";
send(str, "colonia");
}
function loadColoniaCallback(response){
}
function clienteBar(){
if(document.getElementById('usuarioID').value == 0){
$("#clienteBar").hide();
} else {
$("#logInBar").hide();
$("#signUpBar").hide();
}
}
function signUp(){
var valido = validateSignUp();
if(valido == true){
var nombre = document.getElementById("nombreCC").value;
var direccion = document.getElementById("direccionCC").value;
var email = document.getElementById("emailCC").value;
var password1 = document.getElementById("password1").value;
var nacimiento = document.getElementById("dia").value + "/" + document.getElementById("mes").value + "/" + document.getElementById("anio").value;
var sexo = document.getElementById("sexo").value;
var telefono = document.getElementById("telefono").value;
var str = "signUp.php?nombre=" + nombre + "&direccion=" + direccion + "&email=" + email + "&password=" + password1 + "&nacimiento=" + nacimiento + "&sexo=" + sexo + "&telefono=" + telefono;
send(str, "signUp");
}
}
function signUpCallback(response){
if(response == "existingEmail"){
document.getElementById("notificationCC").innerHTML = "Esa dirección de correo ya ha sido utilizada";
} else {
document.getElementById("notificationCC").innerHTML = "Ingresa a tu email para dar de alta tu cuenta";
document.getElementById("nombreCC").value = "";
document.getElementById("emailCC").value = "";
password1 = document.getElementById("password1").value = "";
password1 = document.getElementById("password2").value = "";
}
}
function validateSignUp(){
var nombre = document.getElementById("nombreCC").value;
var direccion = document.getElementById("direccionCC").value;
var email = document.getElementById("emailCC").value;
var password1 = document.getElementById("password1").value;
var password2 = document.getElementById("password2").value;
var dia = document.getElementById("dia").value;
var mes = document.getElementById("mes").value;
var anio = document.getElementById("anio").value;
var sexo = document.getElementById("sexo").value;
var telefono = document.getElementById("telefono").value;
var mydate=new Date()
var year=mydate.getYear();
if (year < 1000){
year+=1900
}
var month = mydate.getMonth();
month = month + 1;
var day = mydate.getDate();
if(day > 31 || mes > 12 || anio >= year){
document.getElementById("notificationCC").innerHTML = "La fecha de nacimiento no es válida";
return false;
} else{
//Valida que todos los campos esten llenos
if(nombre == "" || email == "" || password1 == "" || password2 == "" || telefono == "" || direccion == ""){
document.getElementById("notificationCC").innerHTML = "Por favor llena todos los campos";
return false;
} else {
//Passwords iguales
if(password1 != password2){
document.getElementById("notificationCC").innerHTML = "Las contraseñas no coinciden";
return false;
} else {
//Longitud del password
if(password1.length < 6){
document.getElementById("notificationCC").innerHTML = "La contraseña debe ser de al menos 6 caracteres de largo";
return false;
} else {
if(comparaFecha(dia, mes, anio, day, month, year) == false){
document.getElementById("notificationCC").innerHTML = "La fecha no es correcta";
return false;
}
else{
if(telefono.length < 10){
document.getElementById("notificationCC").innerHTML = "El telefono no es correcto";
return false;
} else {
return true;
}
}
}
}
}
}
}
function trim(value) {
var temp = value;
var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
if (obj.test(temp)) { temp = temp.replace(obj, '$2');}
var obj = / /g;
while (temp.match(obj)) { temp = temp.replace(obj, " ");}
return temp;
}
function comparaFecha(dia, mes, anio, day, month, year){
if(anio > (year-18)){
return false;
}
else
{
if(anio == (year-18))
{
if(mes > month){
return false;
}
else
{
if(mes == month)
{
if(dia > day){
return false;
}
else
{
return true;
}
}
}
}
else
{
return true;
}
}
}
function logOut(){
var str = "logOut.php";
send(str, "logOut");
}
function logOutCallback(response){
if(response == "success"){
$("#clienteBar").hide();
$("#logInBar").show();
$("#logInBarMenu").show();
$("#signUpBar").show();
document.getElementById("usuarioID").value = 0;
}
}
function setServicio(tipo){
setCookie("check", tipo);
}
function redirect(element){
window.location = element.title;
}
</script>
</head>
<?php
include("indexBackend.php");
?>
<body>
<?php
//Carga la session
if(isset($_SESSION['usuarioID'])){
echo ("<input type='hidden' id='usuarioID' value='".$_SESSION['usuarioID']."' />");
$nombre = $_SESSION['nombre'];
} else {
echo ("<input type='hidden' id='usuarioID' value='0' />");
$nombre = "";
}
?>
<?php
include("getPublicidad.php");
?>
<?php
//Domicilio
if($_COOKIE['domicilio'] == 1){
echo("<input type='hidden' id='domicilioBreadcrumb' value='set'/>");
} else {
echo("<input type='hidden' id='domicilioBreadcrumb' value='not_set'/>");
}
//Recoger
if($_COOKIE['recoger'] == 1){
echo("<input type='hidden' id='recogerBreadcrumb' value='set'/>");
} else {
echo("<input type='hidden' id='recogerBreadcrumb' value='not_set'/>");
}
//Reservacion
if($_COOKIE['reservacion'] == 1){
echo("<input type='hidden' id='reservacionBreadcrumb' value='set'/>");
} else {
echo("<input type='hidden' id='reservacionBreadcrumb' value='not_set'/>");
}
?>
<div style="width:100%; text-align:center;"><img src="images/logoadmin.png" alt="" align="middle" /></div>
<div id="container">
<div id="box1" class="box">
<div class="titulo">Selecciona tu Ciudad:</div>
<div class="caja">
<select id="city">
<option value="San Pedro Garza García, Nuevo Leon">San Pedro Garza García</option>
<option value="Monterrey, Nuevo Leon">Monterrey</option>
</select><input id="tags" style="display:none" />
</div>
<img id="crossCiudad" src="images/cross2.gif" style="cursor:pointer" onclick="deleteCookie('puraCiudad')"/> <span id="ciudadBreadcrumb"></span>
<span class="btn1" id="ciudad">Continuar</span>
</div>
<div id="box2" class="box">
<div class="titulo">Selecciona el Tipo de Servicio:</div>
<div class="caja">
<input type="radio" id="domicilio" name="tipo" value="domicilio" class="selec"/><span class="servicios">A Domicilio</span>
<input type="radio" name="tipo" value="recoger" class="selec" onClick="setCookie('recoger', 'tipoDeServicio')"/><span class="servicios">Pasar a Recoger</span>
<input type="radio" name="tipo" value="reservar" class="selec" onClick="setCookie('reservar', 'tipoDeServicio')"/><span class="servicios">Reservar</span>
</div>
</div>
<div id="box3" class="box">
<div class="titulo">Selecciona tu Colonia:</div>
<div class="caja"><input id="tags2" value="Escribe tu colonia: Ej. Del Valle" onblur="if(this.value=='') this.value='Escribe tu colonia: Ej. Del Valle'" onfocus="if(this.value =='Escribe tu colonia: Ej. Del Valle' ) this.value=''" /></div>
<img id="crossColonia" src="images/cross2.gif" style="cursor:pointer" onclick="deleteCookie('ciudad')"/> <span id="coloniaBreadcrumb"></span>
<span class="coloniaButton" id="colonia">Continuar</span>
</div>
</div>
<div id="footer">
<span style="float: left;">Derechos Reservados Quierodecomer.com</span>
<span onclick="terminosCondicionesDialog()" style="cursor:pointer; text-decoration: underline;">El uso de este sitio web implica la aceptación de los términos y condiciones de quierodecomer.com</span>
<span style="float: right;">Login Restaurantes</span>
</div>
<div id="terminosCondiciones" title="Términos y Condiciones">
<?php echo $terminos; ?>
</div>
<script type="text/javascript">
/* Bookmark */
jQuery(document).ready(function(){
// add a "rel" attrib if Opera 7+
if(window.opera) {
if (jQuery("A.linkBookmark").attr("rel") != ""){ // don't overwrite the rel attrib if already set
jQuery("A.linkBookmark").attr("rel","sidebar");
}
}
jQuery("A.linkBookmark").click(function(event){
event.preventDefault(); // prevent the anchor tag from sending the user off to the link
var url = this.href;
var title = this.title;
if (window.sidebar) { // Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
} else if( window.external ) { // IE Favorite
window.external.AddFavorite( url, title);
} else if(window.opera) { // Opera 7+
return false; // do nothing - the rel="sidebar" should do the trick
} else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
alert('Desafortunadamente, este navegador no soporta la petición ' + ' por favor, agrega esta página manualmente.');
}
});
$('.flexslider').flexslider();
});
</script>
</body>
</html>

I checked your JS console in IE7 mode and I got the following error :
SCRIPT1028: Expected identifier, string or number
testing.quierodecomer.com, line 215 character 2
So, try just to remove the last comma of your function :
$( "#terminosCondiciones" ).dialog({
autoOpen: false,
height: 350,
width: 450,
modal: true,
});

Related

AJAX : Pass an image and data through Single AJAX [duplicate]

This question already has answers here:
How to send image to PHP file using Ajax?
(5 answers)
jQuery AJAX file upload PHP
(5 answers)
jQuery / ajax upload image and save to folder
(3 answers)
Upload image using jQuery, AJAX and PHP
(2 answers)
Closed 4 years ago.
I want to pass some text data and file through one ajax code
Here is my code's index.php :-
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Karthikeyan K">
<title>POST</title>
<!-- Bootstrap CSS file -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<style type="text/css">
body {
padding: 45px;
}
footer {
margin: 10px 0;
}
.photo {
margin-bottom: 10px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mentionsInput.css">
<style type="text/css">
#status-overlay {
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.50);
position: fixed;
top: 0;
left: 0;
z-index: 99999;
overflow: hidden;
}
#highlight-textarea {
background: #fff;
}
.form-control:focus {
box-shadow: 0 0 0 2px #3399ff;
outline: 0;
}
h2 {
font-size: 20px;
}
</style>
<style>
#upload_button {
display: none;
border: 0px;
background: linear-gradient(180deg, #f44, #811);
border-radius: 5px;
color: #fff;
padding: 5px;
}
</style>
</head>
<body>
<div id="status-overlay" style="display: none"></div>
<form method="POST" class="form" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" id="title" class="form-control" placeholder="Post title..."><br>
<div id="highlight-textarea">
<textarea onclick="highlight();" name="postText" class="form-control postText mention" cols="10" rows="8" placeholder="What's going on?" dir="auto"></textarea>
</div><br>
<select class="form-control" name="type" id="type" required>
<option value="">Choose Post Type</option>
<option value="Closet">Closet</option>
<option value="Follower">Follower</option>
<option value="Group">Group</option>
</select><br>
<p><button id="upload_button">Click here to select file</button></p>
<p><input id="upload_input" name="upfile" type="file"/></p>
</div>
<input type="button" value="Post" class="btn btn-primary pull-right postMention">
</form>
<!-- Bootstrap Script file -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src='https://cdn.rawgit.com/jashkenas/underscore/1.8.3/underscore-min.js' type='text/javascript'></script>
<script src='js/lib/jquery.elastic.js' type='text/javascript'></script>
<script type="text/javascript" src="js/jquery.mentionsInput.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('textarea').on('click', function(e) {
e.stopPropagation();
});
$(document).on('click', function (e) {
$("#status-overlay").hide();
$("#highlight-textarea").css('z-index','1');
$("#highlight-textarea").css('position', '');
});
});
function highlight()
{
$("#status-overlay").show();
$("#highlight-textarea").css('z-index','9999999');
$("#highlight-textarea").css('position', 'relative');
}
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
//post text in jquery ajax
var post_data = "text="+encodeURIComponent(post_text);
var val1 = $('#title').val();
var val2 = $('#type').val();
//var val3 = $('#upload_input');
//var post_title = $('#title').val();
var form = new FormData(document.getElementById('.postMention'));
//append files
var file = document.getElementById('upload_input').files[0];
if (file) {
form.append('upload_input', file);
}
$.ajax({
type: "POST",
data: post_data+'&title='+val1+'&type='+val2+'&upload_input='+form,
url: 'ajax/post.php',
success: function(msg) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
}
});
} else {
alert("Post cannot be empty!");
}
});
});
//used for get users from database while typing #..
$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('ajax/get_users_json.php', function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
});
</script>
</body>
</html>
<?php } ?>
here's a code of my php file to insert data into database ajax/post.php
. . . .
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
if(isset($_POST) && !empty($_POST['text']) && $_POST['text'] != '')
{
include '../config/config.php';
$user = $uid; //w3lessons demo user
$postid=mt_rand();
$text = strip_tags($_POST['text']); //clean the text
$title= $_POST['title'];
$type= $_POST['type'];
define('FIRST_MATCH_GROUP', 1);
preg_match_all("/#\[(.+)\]/U", $text, $tags); // Value under #[]
$tags = implode(',', $tags[FIRST_MATCH_GROUP]);
$upfile_name = $_FILES['upload_input']['name'];
$upfile_size =$_FILES['upload_input']['size'];
$upfile_tmp =$_FILES['upload_input']['tmp_name'];
$upfile_type=$_FILES['upload_input']['type'];
$upfile_t = explode(".", $_FILES["upload_input"]["name"]);
$upfile_name = mt_rand() . '.' . end($upfile_t);
if($upfile_type == "image/jpg" && $upfile_type == "image/png" && $upfile_type == "image/jpeg" && $upfile_type == "video/mp4"){
echo "<script>window.alert('extension not allowed, please choose a JPG or PNG or MP4 file.');</script>";
}
else {
if($upfile_size > 10485760){
echo "<script>window.alert('File size must be Less 10 MB');</script>";
}
else {
move_uploaded_file($upfile_tmp,"../../uploads/".$upfile_name);
$DB->query("INSERT INTO posts(post_id,title,content,user_id,type,tags,image) VALUES(?,?,?,?,?,?,?)", array($postid,$title,$text,$user,$type,$tags,$upload_input));
?>
<div class="media">
<div class="media-left">
<img src="https://cdn.w3lessons.info/logo.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">w3lessons</h4>
<p><?php echo getMentions($text); ?></p>
</div>
</div>
<hr>
<?php
} } } else {
echo "1"; //Post Cannot be empty!
}
function getMentions($content)
{
global $DB;
$mention_regex = '/#\[([0-9]+)\]/i'; //mention regrex to get all #texts
if (preg_match_all($mention_regex, $content, $matches))
{
foreach ($matches[1] as $match)
{
$match_user =$DB->row("SELECT * FROM register WHERE id=?",array($match));
$match_search = '#[' . $match . ']';
$match_replace = '<a target="_blank" href="' . $match_user['profile_img'] . '">#' . $match_user['first_name'] . '</a>';
if (isset($match_user['id']))
{
$content = str_replace($match_search, $match_replace, $content);
}
}
}
return $content;
}
}?>
When i submit form data was passing at my php page but images index is goes undefined...
change the way you pass data in request
try this
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
var formData = new FormData($('.form')[0]);
formData.append('text',encodeURIComponent(post_text));
$.ajax({
url: 'ajax/post.php',
type: 'POST',
data: formData,
success: function (data) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
},
cache: false,
contentType: false,
processData: false
});
} else {
alert("Post cannot be empty!");
}
});
});
and input name
<input id="upload_input" name="upload_input" type="file"/>

Why The Program Writes To Socket Empty?

I am making a program which records video, and sends its blobs to a socket every 5 secs.It seems working properly but when i look at the files received by the server, i see all the programs written by socket client are empty= 0kb.Can you help me please? My HTML/JS and PHP codes are below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>WebRTC Video Recording using MediaStreamRecorder</title>
<script src="https://cdn.WebRTC-Experiment.com/MediaStreamRecorder.js"></script>
<!-- for Edige/FF/Chrome/Opera/etc. getUserMedia support -->
<script src="https://cdn.WebRTC-Experiment.com/gumadapter.js"></script>
<link rel="stylesheet" href="https://cdn.webrtc-experiment.com/style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="author" type="text/html" href="https://plus.google.com/+MuazKhan">
<meta name="author" content="Muaz Khan">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<style>
input {
border: 1px solid rgb(46, 189, 235);
border-radius: 3px;
font-size: 1em;
outline: none;
padding: .2em .4em;
width: 60px;
text-align: center;
}
select {
vertical-align: middle;
line-height: 1;
padding: 2px 5px;
height: auto;
font-size: inherit;
margin: 0;
}
</style>
</head>
<body>
<article>
<header style="text-align: center;">
<h1>
WebRTC Video Recording using MediaStreamRecorder
</h1>
<p>
HOME
<span> © </span>
WebRTC Experiment .
</p>
</header>
<section class="experiment" style="padding: 5px;">
<label for="time-interval">Time Interval (milliseconds):</label>
<input type="text" id="time-interval" value="5000">
<br>
<br> recorderType:
<select id="video-recorderType" style="font-size:22px;vertical-align: middle;margin-right: 5px;">
<option value="[Best Available Recorder]">[Best Available Recorder]</option>
<option value="MediaRecorder API">MediaRecorder API</option>
<option value="WebP encoding into WebM">WebP encoding into WebM</option>
</select>
<br>
<br>
<button id="start-recording">Start</button>
<button id="stop-recording" disabled>Stop</button>
<button id="pause-recording" disabled>Pause</button>
<button id="resume-recording" disabled>Resume</button>
<button id="save-recording" disabled>Save</button>
<br>
<br>
<label for="video-width">Video Width:</label>
<input type="text" id="video-width" value="320">
<label for="video-height">Video Height:</label>
<input type="text" id="video-height" value="240">
</section>
<section class="experiment">
<div id="videos-container">
</div>
</section>
<script>
function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
}
var mediaConstraints = {
audio: !IsOpera && !IsEdge, // record both audio/video in Firefox/Chrome
video: true
};
document.querySelector('#start-recording').onclick = function() {
this.disabled = true;
captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
};
document.querySelector('#stop-recording').onclick = function() {
this.disabled = true;
mediaRecorder.stop();
mediaRecorder.stream.stop();
document.querySelector('#pause-recording').disabled = true;
document.querySelector('#start-recording').disabled = false;
};
document.querySelector('#pause-recording').onclick = function() {
this.disabled = true;
mediaRecorder.pause();
document.querySelector('#resume-recording').disabled = false;
};
document.querySelector('#resume-recording').onclick = function() {
this.disabled = true;
mediaRecorder.resume();
document.querySelector('#pause-recording').disabled = false;
};
document.querySelector('#save-recording').onclick = function() {
this.disabled = true;
mediaRecorder.save();
// alert('Drop WebM file on Chrome or Firefox. Both can play entire file. VLC player or other players may not work.');
};
var mediaRecorder;
function onMediaSuccess(stream) {
var video = document.createElement('video');
var videoWidth = document.getElementById('video-width').value || 320;
var videoHeight = document.getElementById('video-height').value || 240;
video = mergeProps(video, {
controls: true,
muted: true,
width: videoWidth,
height: videoHeight,
src: URL.createObjectURL(stream)
});
video.play();
videosContainer.appendChild(video);
videosContainer.appendChild(document.createElement('hr'));
mediaRecorder = new MediaStreamRecorder(stream);
mediaRecorder.stream = stream;
var recorderType = document.getElementById('video-recorderType').value;
if (recorderType === 'MediaRecorder API') {
mediaRecorder.recorderType = MediaRecorderWrapper;
}
if (recorderType === 'WebP encoding into WebM') {
mediaRecorder.recorderType = WhammyRecorder;
}
// don't force any mimeType; use above "recorderType" instead.
// mediaRecorder.mimeType = 'video/webm'; // video/webm or video/mp4
mediaRecorder.videoWidth = videoWidth;
mediaRecorder.videoHeight = videoHeight;
mediaRecorder.ondataavailable = function(blob) {
var a = document.createElement('a');
a.target = '_blank';
a.innerHTML = 'Open Recorded Video No. ' + (index++) + ' (Size: ' + bytesToSize(blob.size) + ') Time Length: ' + getTimeLength(timeInterval);
a.href = URL.createObjectURL(blob);
videosContainer.appendChild(a);
videosContainer.appendChild(document.createElement('hr'));
// EKLENEN
var myRequest = new XMLHttpRequest();
myRequest.open('POST', 'save.php' , true);
myRequest.send(blob);
};
var timeInterval = document.querySelector('#time-interval').value;
if (timeInterval) timeInterval = parseInt(timeInterval);
else timeInterval = 5 * 1000;
// get blob after specific time interval
mediaRecorder.start(timeInterval);
document.querySelector('#stop-recording').disabled = false;
document.querySelector('#pause-recording').disabled = false;
document.querySelector('#save-recording').disabled = false;
}
function onMediaError(e) {
console.error('media error', e);
}
var videosContainer = document.getElementById('videos-container');
var index = 1;
function bytesToSize(bytes) {
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function getTimeLength(milliseconds) {
var data = new Date(milliseconds);
return data.getUTCHours() + " hours, " + data.getUTCMinutes() + " minutes and " + data.getUTCSeconds() + " second(s)";
}
window.onbeforeunload = function() {
document.querySelector('#start-recording').disabled = false;
};
</script>
<pre style="border-left: 2px solid red; margin-left:2em; padding-left: 1em;">
// cdn.webrtc-experiment.com/MediaStreamRecorder.js
var mediaConstraints = {
audio: true,
video: true // if firefox or chrome
};
navigator.getUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
function onMediaSuccess(stream) {
var mediaRecorder = new MediaStreamRecorder(stream);
mediaRecorder.mimeType = 'video/webm';
mediaRecorder.ondataavailable = function (blob) {
// POST/PUT "Blob" using FormData/XHR2
var blobURL = URL.createObjectURL(blob);
document.write('' + blobURL + '');
};
mediaRecorder.start(3000);
}
function onMediaError(e) {
console.error('media error', e);
}
</pre>
MediaStreamRecorder Demos
<script>
window.useThisGithubPath = 'streamproc/MediaStreamRecorder';
</script>
<script src="https://cdn.webrtc-experiment.com/commits.js" async></script>
</article>
<footer>
MIT License
<table>
<tr> <td>
</td>
</tr>
</p>
</footer>
</body>
</html>
And PHP Socket Client below :
<?php
$portnum = 'portnum';
$ipnum = 'Ipnum';
// No Timeout
set_time_limit(0);
if ( ($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == FALSE ) {
$message = "Socket not created";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$context = stream_context_create($opts);
if ( ($file = file_get_contents($_FILES['blob'], false, $context ) ) == FALSE ) {
$message = "File_get_contents not working.";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$ss = fopen ( file, "r");
$streamvid = fread ( $ss );
if ( ( $tt = fsockopen($ipnum, $portnum, $errno, $errstr, 30)) == FALSE ) {
$message = "fsockopen not working";
echo "<script type='text/javascript'>alert('$message');</script>";
}
if ( (fwrite ( $tt , $streamvid ) ) == FALSE ) { // DIŞARI ALINDI
$message = "fwrite failed";
echo "<script type='text/javascript'>alert('$message');</script>";
}
fclose( $tt );
?>
mediaRecorder.ondataavailable = function(blob) {
// upload blob to PHP server
uploadToPHPServer(blob);
};
function uploadToPHPServer(blob) {
var file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
type: 'video/webm'
});
// create FormData
var formData = new FormData();
formData.append('video-filename', file.name);
formData.append('video-blob', file);
makeXMLHttpRequest('https://path-to-your-server/save.php', formData, function() {
var downloadURL = 'https://path-to-your-server/uploads/' + file.name;
console.log('File uploaded to this path:', downloadURL);
});
}
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback();
}
};
request.open('POST', url);
request.send(data);
}
Here is save.php:
<?php
// via: https://github.com/muaz-khan/RecordRTC/blob/master/RecordRTC-to-PHP/save.php
header("Access-Control-Allow-Origin: *");
function selfInvoker()
{
if (!isset($_POST['audio-filename']) && !isset($_POST['video-filename'])) {
echo 'PermissionDeniedError';
return;
}
$fileName = '';
$tempName = '';
if (isset($_POST['audio-filename'])) {
$fileName = $_POST['audio-filename'];
$tempName = $_FILES['audio-blob']['tmp_name'];
} else {
$fileName = $_POST['video-filename'];
$tempName = $_FILES['video-blob']['tmp_name'];
}
if (empty($fileName) || empty($tempName)) {
echo 'PermissionDeniedError';
return;
}
$filePath = 'uploads/' . $fileName;
// make sure that one can upload only allowed audio/video files
$allowed = array(
'webm',
'wav',
'mp4',
'mp3',
'ogg'
);
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
echo 'PermissionDeniedError';
continue;
}
if (!move_uploaded_file($tempName, $filePath)) {
echo ('Problem saving file.');
return;
}
echo ($filePath);
}
selfInvoker();
?>
Regarding PHP upload issues,
https://github.com/muaz-khan/RecordRTC/wiki/PHP-Upload-Issues
PS. Don't forget to create uploads directory here:
https://path-to-your-server/uploads/ ----- inside same directory as "save.php"

Passing JavaScript Variables from JavaScript to PHP using AJAX

I am having some problems with my PHP file. So basically I am working on a project that takes two addresses from the user, then it uses javascript to show their route and once they click submit, I want to pass these two variables to PHP file. I researched a lot and found that I would need AJAX call. The problem I am running into is that AJAX call works perfectly, but when I go to PHP file it throws me an error that variables are not defined. Someone, please explain to me what I am doing wrong here.
JavaScript code:
/* ============================================================================================
Reference: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-directions
==============================================================================================
*/
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 41.881832, lng: -87.623177},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var submit_button = document.getElementById('button-to-submit');
/*var modeSelector = document.getElementById('mode-selector');*/
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
/*this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');*/
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(submit_button);
/*this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);*/
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
/* AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
}; */
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
origin_addr = document.getElementById('origin-input').value;
//console.log(origin_addr);
destination_addr = document.getElementById('destination-input').value;
//console.log(destination_addr);
//var place_id = document.getElementById('origin-input');
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
$("#button-to-submit").click(function() {
$.ajax({
url: "Database/save-points.php",
type: "POST", //send it through get method
data: {
origin_address: origin_addr,
destination_address: destination_addr
},
success: function(response) {
//Do Something
console.log("Succeed");
location.href="Database/save-points.php";
},
error: function(xhr) {
//Do Something to handle error
}
});
});
PHP code:
<?php
$origin_address = $_POST['origin_address'];
$destination_address = $_POST['destination_address'];
echo $origin_address;
echo $destination_address;
?>
/* maps.php */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr" dir="ltr">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js" type="text/javascript"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#origin-input,
#destination-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 200px;
}
#origin-input:focus,
#destination-input:focus {
border-color: #4d90fe;
}
#mode-selector {
color: #fff;
background-color: #4d90fe;
margin-left: 12px;
padding: 5px 11px 0px 11px;
}
#mode-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
</head>
<body>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination location">
<div id="mode-selector" class="controls">
<input type="radio" name="type" id="changemode-walking" checked="checked">
<label for="changemode-walking">Walking</label>
<input type="radio" name="type" id="changemode-transit">
<label for="changemode-transit">Transit</label>
<input type="radio" name="type" id="changemode-driving">
<label for="changemode-driving">Driving</label>
<input type="submit" id="button-to-submit" value="SAVE !" />
</div>
<div id="map"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOU_KEY&libraries=places"></script>
<script type="text/javascript">
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var modeSelector = document.getElementById('mode-selector');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
/************************************/
$(document).ready( function() {
$("#button-to-submit").click(function() {
origin_addr = $("#origin-input").val();
destination_addr = $("#destination-input").val();
$.ajax({
type: "POST",
url: "maps.exe.php",
data: {
origin_address: origin_addr,
destination_address: destination_addr
},
success: function(response){
alert(response);
window.location.href = 'test-resp.php?'+response;
}
});
return false;
});
});
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMap" async defer></script>
</body>
</html>
/* maps.exe.php */
<?php
$origin_address = $_POST['origin_address'];
$destination_address = $_POST['destination_address'];
echo"origin=$origin_address&destination=$destination_address";
?>
/* test-resp.php */
<?php
$origin_address = $_GET['origin'];
$destination_address = $_GET['destination'];
echo"[ origin : $origin_address / destination = $destination_address ]";
?>
I have an example of me passing JS variable to PHP.
JS (url and content are JS variables) :
var data_to_send = {
filepath: ""+url,
filecontent: ""+content
};
jQuery.ajax({
url:"php/dynamic.php",
data: data_to_send,
cache: false,
async: true,
type:'post',
timeout:3000//purely optionnal, check jQuery's Doc to learn more about ajax optionnal parameters/settings
});
In dynamic.php :
<?php
$vars = serialize($_POST); /*easier access*/
$file_path = "../".$vars["filepath"];
$file_content = $var["filecontent"]; /*example of assigning a JS var's value to a PHP var*/
$fh = fopen($file_path, 'w+') or die("could not open file");
fwrite($fh, $file_content."\n");
fclose($fh);
?>
PS: I use jQuery for POST, I dunno the pure javascript way to do the same :/

Rendering Flot barchart with dropdowns

I am plotting flot bar graph in my website.My requirement is like I have a zone dropdown and another dependent country dropdown on zone .On the selection of zone and country for that particular country the bar graphs needs to be plotted.Individually every page is rendering as expected.But when I am including those pages in single php page I am getting an error as"No method plot".where I am wrong.
My code for Integrated page is:
<script type="text/javascript" src="../assets/plugins/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../assets/plugins/flot/jquery.flot.js"></script>
<script type="text/javascript" src="../assets/plugins/flot/jquery.flot.time.min.js"></script>
<script type="text/javascript" language="javascript" src="../assets/plugins/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" language="javascript" src="../assets/plugins/flot/jquery.flot.orderBars.js"></script>
<script type="text/javascript" language="javascript" src="../assets/plugins/flot/jquery.flot.tickrotatotor.min.js"></script>
<script type="text/javascript" language="javascript" src="../assets/plugins/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" language="javascript" src="../assets/plugins/flot/jquery.flot.labelangle.min.js"></script>
<script>
function graph()
{
alert("In graph function");
var yourSelect = document.getElementById('zoneddl');
if(yourSelect.options[yourSelect.selectedIndex].value =='overall')
{
alert("overall");
maindashoverall();
}
else if(yourSelect.options[yourSelect.selectedIndex].value =='overall1')
{
alert("overall1");
document.getElementById('overall1').style.display ="block";
document.getElementById('overall').style.display ="none";
maindashoverall1();
}
}
</script>
<select id="zoneddl" onChange="graph()">
<option value="0">select</option>
<option value="overall">OVERALL</option>
<option value="overall1">OVERALL1</option>
</select>
<div id="overall">
<?php include "graphs/maindashoverall.php"; ?>
</div>
<div id="overall1" style="display:none">
<?php include "graphs/maindashoverall1.php"; ?>
</div>
The code for Individual pages is below.
maindashoverall.php:
<?php require_once('dbfile');
mysql_select_db($database_finalkms, $finalkms);
$query_getmaindata = "select `EquipmentMainCatagory`,count(`EquipmentMainCatagory`) from asset a join assetinfo ai on a.assetid=ai.assetid and upper(ai.EquipmentStatus) like upper('%Active%') group by `EquipmentMainCatagory`";
$getmaindata = mysql_query($query_getmaindata, $finalkms) or die(mysql_error());
$row_getmaindata = mysql_fetch_assoc($getmaindata);
$totalRows_getmaindata = mysql_num_rows($getmaindata);
$rows = array();
while($row_getmaindata = mysql_fetch_assoc($getmaindata))
{
$rows[] = array( $row_getmaindata['EquipmentMainCatagory'],(int)$row_getmaindata['count(`EquipmentMainCatagory`)']);
}
// convert data into JSON format
$jsonTable = json_encode($rows);
?>
<div id="placeholder1" style="width:900px;height:750px;"></div>
<script>
$(function maindashoverall() {
var data =<?php echo $jsonTable;?>;
var ticks = [];
for (var i = 0; i < data.length; i++) {
ticks.push([i,data[i][0]]);
data[i][0] = i;
}
var dataset = [{ data: data, color: "#5482FF" }];
var options = {
series: {
lineWidth: 5,
bars: {
show: true,
barWidth: 0.5,
align:"center"
}
},
xaxis: {
axisLabel: "EquipmentMainCatagory",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
ticks: ticks,
//rotateTicks:90
labelAngle: 90
},
yaxis: {
axisLabel: "# Assets",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3
},
grid: {
hoverable: true,
borderWidth: 0,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] },
}
};
var previousPoint = null, previousLabel = null;
$.fn.UseTooltip = function () {
$(this).bind("plothover", function (event, pos, item) {
if (item) {
if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
previousPoint = item.dataIndex;
previousLabel = item.series.label;
$("#tooltip").remove();
var x = item.datapoint[0];
var y = item.datapoint[1];
var color = item.series.color;
//console.log(item.series.xaxis.ticks[x].label);
showTooltip(item.pageX,
item.pageY,
color,
item.series.xaxis.ticks[x].label + " : <strong>" + y + "</strong>");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
};
function showTooltip(x, y, color, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y ,
left: x,
border: '2px solid ' + color,
padding: '3px',
'font-size': '9px',
'border-radius': '5px',
'background-color': '#fff',
'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
opacity: 0.9
}).appendTo("body").fadeIn(200);
}
$.plot($("#placeholder1"), dataset, options);
$("#placeholder1").UseTooltip();
});
</script>
<?php
mysql_free_result($getmaindata);
?>
maindashoverall1.php:
<script type="text/javascript" src="../../assets/plugins/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../../assets/plugins/flot/jquery.flot.js"></script>
<script type="text/javascript" src="../../assets/plugins/flot/jquery.flot.time.min.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.orderBars.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.tickrotatotor.min.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" language="javascript" src="../../assets/plugins/flot/jquery.flot.labelangle.min.js"></script>
<?php //require_once('dbfile.php');
mysql_select_db($database_finalkms, $finalkms);
$query_getmaindata = "select `EquipmentMainCatagory`,count(`EquipmentMainCatagory`) from asset a join assetinfo ai on a.assetid=ai.assetid and upper(ai.EquipmentStatus) like upper('%Active%') group by `EquipmentMainCatagory` order by count(`EquipmentMainCatagory`) desc";
$getmaindata = mysql_query($query_getmaindata, $finalkms) or die(mysql_error());
$row_getmaindata = mysql_fetch_assoc($getmaindata);
$totalRows_getmaindata = mysql_num_rows($getmaindata);
$rows = array();
while($row_getmaindata = mysql_fetch_assoc($getmaindata))
{
$rows[] = array( $row_getmaindata['EquipmentMainCatagory'],(int)$row_getmaindata['count(`EquipmentMainCatagory`)']);
}
// convert data into JSON format
$jsonTable = json_encode($rows);
?>
<div id="placeholder2" style="width:900px;height:750px;"></div>
<script>
$(function maindashoverall1() {
var data =<?php echo $jsonTable;?>;
var ticks = [];
for (var i = 0; i < data.length; i++) {
ticks.push([i,data[i][0]]);
data[i][0] = i;
}
var dataset = [{ data: data, color: "#5482FF" }];
var options = {
series: {
lineWidth: 5,
bars: {
show: true,
barWidth: 0.5,
align:"center"
}
},
xaxis: {
axisLabel: "EquipmentMainCatagory",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
ticks: ticks,
labelAngle: 90
},
yaxis: {
axisLabel: "# Assets",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3
},
grid: {
hoverable: true,
borderWidth: 0,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] },
}
};
var previousPoint = null, previousLabel = null;
$.fn.UseTooltip = function () {
$(this).bind("plothover", function (event, pos, item) {
if (item) {
if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
previousPoint = item.dataIndex;
previousLabel = item.series.label;
$("#tooltip").remove();
var x = item.datapoint[0];
var y = item.datapoint[1];
var color = item.series.color;
//console.log(item.series.xaxis.ticks[x].label);
showTooltip(item.pageX,
item.pageY,
color,
// "<strong>" + y + "</strong>");
item.series.xaxis.ticks[x].label + " : <strong>" + y + "</strong>");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
};
function showTooltip(x, y, color, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y ,
left: x,
border: '2px solid ' + color,
padding: '3px',
'font-size': '9px',
'border-radius': '5px',
'background-color': '#fff',
'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
opacity: 0.9
}).appendTo("body").fadeIn(200);
}
var $overall1 = $.plot($("#placeholder2"), dataset, options);
$("#placeholder2").UseTooltip();
});
</script>
<?php
mysql_free_result($getmaindata);
?>
In your integrated page, you load all javascript files once at the beginning of the integrated page and once again at the beginning of maindashoverall1.php. Remove the block in the maindashoverall1.php file.
You also have two lines (per block) where you load jquery.flot.axislabels.js. Remove one of those too.

API google + php + MySql

I want to display the marker on the map but I can see only the first.
what is the problem?
while the marker did not show any
<?php
session_start();
//connessione al DB
include("dati_db.inc.php");
mysql_connect($host,$username,$password)or die("Connessione IMPOSSIBILE al DBMS. TIPO ERRORE:".mysql_error());
mysql_select_db($database)or die("IMPOSSIBILE selezionare il DataBase");
$idric=$_GET['id_ric']; //id richiesta
$sql = "SELECT * FROM richieste WHERE id=".$idric;
$dati=mysql_query($sql);
if (!$dati) {
echo "Query non eseguita correttamente sul DB(".$sql."): ".mysql_error();
exit;
}
$row=mysql_fetch_assoc($dati);
$luogo=$row['luogo'];
$indirizzo=$row['indirizzo'];
$descrizione=$row['descrizione'];
$oggetto=$row['oggetto'];
$indirizzogoogle=$luogo." , ".$indirizzo;
?>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalableo"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3: geocoding</title>
<style type="text/css">
html, body { margin:0; padding:0; width:100%; height:100%; }
body { background:#FFFFFF; color:#000000; font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:150%; text-align:center;}
#map { width:100%; height:95%; }
input { width:250px; }
#tooltip { padding:10px; text-align:left; }
#tooltip p { padding:0; margin:0 0 5px 0; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=it"></script>
<script type="text/javascript" src="inc/jquery-1.7.2.js"></script>
<script type="text/javascript" src="inc/myjs.js"></script>
<script type="text/javascript">
var createMap = function() {
//indirizzo ricavato in precedenza del luogo dell'intervento
var address = "<?php echo ($indirizzogoogle);?>";
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': address}, function(results,status) {
if (status == google.maps.GeocoderStatus.OK) {
var options = {
zoom: 12,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
var marker = new google.maps.Marker(
{
position: results[0].geometry.location,
map: map,
title: 'punto di intervento'
}
);
var tooltip = '<div id="tooltip">'+
'<p>Indirizzo punto di intervento<br>'+
results[0].formatted_address+'</p>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: tooltip
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
sedi = new Array();
dim=0;
//popoli vettore
<?php
//recupero info di tutte le sedi
$query="SELECT * FROM utenti WHERE tipo=3";
$query_sedi=mysql_query($query);
//per ogni record creiamo un MARKER
$contcs=mysql_num_rows($query_sedi);
if($contcs > 0){
//se ci sono records mostriamo tutte le sedi in un ciclo
while($line = mysql_fetch_array($dati, MYSQL_ASSOC)){
//recupero alcune informazioni
$sede = $line['sede'];
echo ("cod_indirizzi($sede);\n");
}
}
?>
} else {
alert("Problema nella ricerca dell'indirizzo: " + status);
}
});
};
function cod_indirizzi(indirizzo){
geocoder.geocode({'address':indirizzo}, function(result, status){
map.setCenter(result[0].geometry.location);
var marker= new google.maps.Marker
({map:map,
position:result[0].geometry.location,
title: indirizzo});
});
}
window.onload = createMap;
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
the map obtained there is only a marker, and you should see 3
what is the error?
Here is a similar script i have done may this help u
use jquery 1.2.6
(function() {
window.onload = function()
{
var ttl=["place1","place2","place3"];
var options = {
zoom: 13,
center: new google.maps.LatLng(28.550000, 77.22496000000001),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
// Creating an array that will contain the coordinates
var places = [];
places.push(new google.maps.LatLng(28.550392878584265, 77.25169658660889));
places.push(new google.maps.LatLng(28.546396951091907 , 77.19741940498352));
places.push(new google.maps.LatLng(28.528748, 77.219663));
// Looping through the places array
for (var i = 0; i < places.length; i++)
{
// Adding the marker as usual
var marker = new google.maps.Marker({
position: places[i],
map: map,
title: ttl[i]
});
// Wrapping the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(i, marker) {
// Creating the event listener. It now has access to the values of
// i and marker as they were during its creation
google.maps.event.addListener(marker, 'mouseover', function() {
var infowindow = new google.maps.InfoWindow({
content: '<div style="overflow:hidden;">'+ttl[i]+'</div>'
});
infowindow.open(map, marker);
setTimeout(function () { infowindow.close(); }, 5000);
});
})(i, marker);
}
}
})();
HTML
<div id="map"></div>
CSS
#map {
width: 400px;
height: 400px;
border: 4px solid #ccc;
}

Categories