I am using cakephp I have 2 links:
<a href="#" tabindex="1" onclick="base_load_demo1('http://www.boxyourtvtrial.com/widget/beer/main/');" >beer</a>
cocktail
With the following JavaScript:
var Url1 = "http://www.boxyourtvtrial.com/widget/cocktail/main/";
var Url2 = "http://www.boxyourtvtrial.com/widget/beer/main/";
var Url3 = "http://www.boxyourtvtrial.com/widget/beer/mini/";
function base_load_demo(Url) {
remoteCall(Url1,"","mainLeftContent");
//remoteCall("SCRIPT_PATH","QUERY_STRING","TARGET_FUNCTION");
}
function base_load_demo1(Url2) {
remoteCall(Url2,"","mainLeftContent");
//remoteCall("SCRIPT_PATH","QUERY_STRING","TARGET_FUNCTION");
}
When I click on the first link it's showing its content through ajax call but when I click on the second link its giving error as follows:
Missing Controller
Error: Http:Controller could not be found.
Error: Create the class Http:Controller below in file: app/controllers/http:controller.php
<?php
class Http:Controller extends AppController {
var $name = 'Http:';
}
?>
Notice: If you want to customize this error message, create app/views/errors/missing_controller.ctp
and in FireFox console tab
POST http://www.boxyourtvtrial.com/widget/beer/main/http://www.boxyourtvtrial.com/widget/cocktail/main/
How can we solve this dual URL calling at the same time?
var xmlHttp;
var uri = "";
var callingFunc = "";
var sResponse = new Array();
function remoteCall(sUrl, sQueryStr, sCalledBy)
{
alert(sUrl);
var resStr = "";
var str = " { ";
if(sQueryStr != "") {
var arr1 = new Array();
arr1 = sQueryStr.split("&");
if(arr1){
for(i=0;i<=arr1.length;i++)
{
if(arr1[i] && arr1[i] != "")
{
var arr2 = new Array();
arr2 = arr1[i].split("=");
str += arr2[0]+":'"+arr2[1]+"' ,";
}
}
}
}
str += " tp: 'tp' } ";
$.ajax({
type: "GET",
url: sUrl,
data: sQueryStr,
dataType: "html",
success: function(data) {
$("#"+sCalledBy).html(data);
//jih(sCalledBy,data);
}
});
/* $.get(sUrl,sQueryStr,function(data) {
jih(sCalledBy,data);
});*/
}
function jih(divid,data)
{
if(document.getElementById(divid))
document.getElementById(divid).innerHTML=data;
}
After your first call to either of those pages it loads:
<script type="text/javascript" src="http://www.boxyourtvtrial.com/widget/cocktail/main/js/common.js"></script>
in the header. Inside common.js is a function called remoteCall, which is overwriting your local remoteCall function.
The remoteCall function inside common.js adds
var url= WIDGET_WEG_PATH+scr_url;
where WIDGET_WEG_PATH = "http://www.boxyourtvtrial.com/widget/beer/main/"
and scr_url = "http://www.boxyourtvtrial.com/widget/beer/main/" (the first parameter of the new remoteCall function)
This is why you are getting the url 'doubled' in the post.
Solution:
Rename local remoteCall function to something that is distinct.
Related
I'm trying to use ajax to store the JavaScript variables which get their values from divs into MySql every 10 seconds. But for some reason the PHP doesn't recognize the variables I'm Posting to it. It displays Undefined Index for all the variables. I tried to use the if(isset($_POST['Joy'])) and the error disappeared but the sql query is never created.
Here is the HTML code (Note: The HTML is originally provided by Affectiva (https://www.affectiva.com) for the video stream facial emotion recognition system. The code lines followed with // are from the original HTML file. The rest are personal effort to store the values of emotions to the database),
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://download.affectiva.com/js/3.2/affdex.js"></script>
</head>
<body>
<div class="container-fluid"> //
<div class="row"> //
<div class="col-md-8" id="affdex_elements" //
style="width:680px;height:480px;"></div> //
<div class="col-md-4"> //
<div style="height:25em;"> //
<strong>EMOTION TRACKING RESULTS</strong><br> //
Joy <div id="Joy"></div> //
Sad <div id="Sadness"></div> //
Disgust <div id="Disgust"></div> //
Anger <div id="Anger"></div> //
Fear <div id="Fear"></div> //
</div> //
</div> //
</div> //
</div> //
<div> //
<button id="start" onclick="onStart()">Start</button> //
</div> //
Here is the JavaScript code,
var divRoot = $("#affdex_elements")[0]; //
var width = 640; //
var height = 480; //
var faceMode = affdex.FaceDetectorMode.LARGE_FACES; //
var detector = new affdex.CameraDetector(divRoot, width, height,
faceMode); //
detector.detectAllEmotions(); //
function onStart() { //
if (detector && !detector.isRunning) { //
detector.start(); //
} } //
function log(node_name, msg) { //
$(node_name).append( msg ) //
} //
setInterval(function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
} });
}
,10000);
detector.addEventListener("onImageResultsSuccess", function(faces, image,
timestamp) { //
$("#Joy").html("");$("#Sadness").html("");$("#Disgust").html(""); //
$("#Anger").html("");$("#Fear").html(""); //
var joy = JSON.stringify(faces[0].emotions.joy,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var sad = JSON.stringify(faces[0].emotions.sadness,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var disgust =
JSON.stringify(faces[0].emotions.disgust,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var anger = JSON.stringify(faces[0].emotions.anger,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var fear = JSON.stringify(faces[0].emotions.fear,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
log('#Joy', JSON.parse(joy) );
log('#Sadness', JSON.parse(sad));
log('#Disgust', JSON.parse(disgust));
log('#Anger', JSON.parse(anger));
log('#Fear', JSON.parse(fear));
});
I get the success alert but the database contain nothing. Here is my PHP code,
<?php
$conn = mysqli_connect('localhost', 'root', '', 'emotions');
if(isset($_POST['Joy'])){
$Joy = $_POST['Joy'];
$Sadness = $_POST['Sadness'];
$Disgust = $_POST['Disgust'];
$Anger = $_POST['Anger'];
$Fear = $_POST['Fear'];
$sql = "Insert into IPEMOTION (JOY, SADNESS, DISGUST, ANGER, FEAR) values
($Joy,$Sadness,$Disgust,$Anger,$Fear)";
mysqli_query($conn, $sql); }
?>
One test I have made is checking the contents of $_POST['Joy'] so I wrote the following code in my php
if (!isset($_POST['Joy'])){
echo "Joy is empty";}
after running the code the previous message "Joy is empty" appeared to me.
Your data shouldn't be like that!
From the Documentation, the data should be like this :
{variableName: value}
So, in your case, the data should be :
{Joy:Joy,Sadness:Sadness,Disgust:Disgust,Anger:Anger,Fear:Fear}
Without the quotes (')
And in HTMLNew.php you can do :
$joy = $_POST['Joy'];
I'm just gonna keep helping you through the answer section, as it is the most easy way for now. So you are saying that the ajax success alert is popping. Then i think that your Interval is not functioning well. Change this:
setInterval(function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
} });
},10000);
Into this:
function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
}
});
}
setInterval(function() {
getElement();
}, 10000);
Just a few question. To see if your values are right you can echo $Disgust in your PHP Script. Then change this:
success : function (){
alert("sucess");
}
Into this
success : function (data){
alert(data);
}
Then:
<?php
//$conn = mysqli_connect('localhost', 'root', '', 'emotions');
//if(isset($_POST['Joy'])){
$Joy = $_POST['Joy'];
$Sadness = $_POST['Sadness'];
$Disgust = $_POST['Disgust'];
$Anger = $_POST['Anger'];
$Fear = $_POST['Fear'];
echo $Joy;
echo $Sadness;
echo $Disgust;
echo $Anger;
echo $Fear;
//$sql = "Insert into IPEMOTION (JOY, SADNESS, DISGUST, ANGER, FEAR) values
//($Joy,$Sadness,$Disgust,$Anger,$Fear)";
//mysqli_query($conn, $sql);
//}
?>
Let me know. I'm deleting all my past answers until now.
I have this messaging system (aka wall). It works to add new messages and If I want to cancel the messages loaded from the database. But if I want to cancel the new messages which have just been appended (without reload the page) it doesn't.
$("#wallButton").on("click",function(){
var textdocument = document.getElementById('input_post_wall').value
var poster = '<?php echo escape($userLogged->data()->user_id);?>';
var date = '<?php echo $humanize->humanize()->naturalDay(time());?>';
var time = '<?php echo $humanize->humanize()->naturalTime(time());?>';
var timeNow = '<?php echo time();?>';
if(textdocument.length>0){
$.ajax({
url: '/post_process.php',
type: 'post',
dataType: 'json',
data: {'action': 'post', 'userid': userId, 'poster': poster, 'text':textdocument, 'time':timeNow},
success: function(data) {
var LastID = data["postID"];
var image = data["image"];
var sex = data["sex"];
var name = data["name"];
if(image){
image = "/userImages/"+poster+"/"+poster+".jpg";
}else{
if(sex == 'male'){
image = '/images/male_profile.png';
}if (sex == 'female'){
image = '/images/female_profile.png';
}
}
$('.postDiv').prepend('<div class="post" data-post-id= "'+LastID+'"><img src="'+image+'" class="postImg"><div class="formatted-text"><h4>'+name+'</h4><h5>'+textdocument+'</h5><h6>'+date+' - <span>'+time+'</span></h6><a style="font-size:10px;"class="cancelPost" data-cancel-id= "'+LastID+'">cancel</a></div></div>').hide().fadeIn('slow');
textdocument.val('');
},
}); // end ajax call
}else{
alert('no text');
}
});//end click function
//this cancel post from wall but it only works for the messages displayed when the page has been loaded. I will write the code to cancel the message from database when the jquery part works.
$('.cancelPost').each(function (e) {
var $this = $(this);
$this.on("click", function () {
value = $(this).data('cancel-id');
$('div[data-post-id="'+ value +'"]').fadeOut("slow", function(){ $(this).remove(); });
});
});
this is the php function that fetches all the message from the database when page is loaded.
public function presentPost($userId){
$query = $this->_db->prepare("SELECT * FROM wall WHERE user_ident = ? ORDER BY postId DESC");
if ($query->execute(array($userId))){
$result = $query->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $row) {
$user = New User($row->posterId);
if($user->data()->image == 0){
if($user->data()->sex == 'male'){
$image = '/images/male_profile.png';
}else{
$image = '/images/female_profile.png';
}
}else{
$image = "/userImages/$row->posterId/$row->posterId.jpg";
}
echo'<div class="post" data-post-id= "'.$row->postId.'"><img src="'.$image.'" class="postImg"> <div class="formatted-text"><h4>'.$user->data()->name.' '.$user->data()->lastName.'</h4><h5>'.$row->textPost.'</h5><h6>'.$this->_humanize->naturalDay($row->time).' - <span>'.$this->_humanize->naturalTime($row->time).'</span></h5><a style="font-size:10px;"class="cancelPost" data-cancel-id= "'.$row->postId.'">cancel</a></div></div>';
}
}
}
you should use delegates for that
$(document).on("click",".cancelPost", function () {
value = $(this).data('cancel-id');
$('div[data-post-id="'+value+'"]').fadeOut("slow");
$('div[data-post-id="'+value+'"]').remove();
});
Im using a MVC in PHP and I have this script created in my form page to validate three text boxes. When these three text boxes contain a value my php code in my controller asks Google Map Api for the closest directions based on the input of these three fields.
In my script I have the variable "direccion" which is what I need to pass to the controller using PHP but im not sure how to accomplish this.
Script Code (View):
jQuery(document).ready(function () {
var direccion="";
var flag = false;
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
alert("false");
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#ff_elem295").val();
var municipio = jQuery("#id_municipio option:selected").text();
var provincia = jQuery("#id_provincia option:selected").text();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
//alert(direccion);
}
});
jQuery.ajax({
url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias",
data : direccion,
dataType : 'html'
}).done(function(){
var data = data;
});
});
PHP Code (Controller):
function calcularDistancias(){
$valor = JRequest::getVar('direccion');
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='. $valor .'&sensor=false';
$data = file_get_contents($url);
$data_array = json_decode($data,true);
$lat = $data_array[results][0][geometry][location][lat];
$lng = $data_array[results][0][geometry][location][lng];
......
}
data property in the object passed to jQuery.ajax is an object.
data : { direccion: direccion }
Then you can access the value of direccion in your controller as a request parameter.
In the if condition put your ajax request like
if(flag == true) {
jQuery.ajax({
url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias",
data : {direction : direccion},
dataType : 'html'
}).done(function(){
var data = data;
});
}
In addition the retrieved data are missing in your code, don't forget to put data in done function :
.done(function(){
var data = data;
});
To
.done(function(data){
var data = data;
});
On my php site, I want to retrieve data every three seconds from a mysql database using javascript.
Problem: when I retrieve data using SELECT * from msgtable, then neither php nor javascript startTime seems to work.
JavaScript:
setInterval(function() {
var link = document.getElementById("chg");
link.href = "http://google.com.pk";
link.innerHTML = "<?php dynamic(); ?>";
}, 3000);
function startTime() {
var today = new Date();
var s = today.getSeconds();
s = checkTime(s);
if( s == s+3 ) { alert("faraz"); }
document.getElementById('time').innerHTML= s;
t = setTimeout( function() { startTime() }, 500 );
}
function changeURL() {
var link = document.getElementById("chg");
link.href = "http://google.com.pk";
link.innerHTML = "Google Pakistan";
}
function checkTime( i ) {
if ( i < 10 ) {
i = "0" + i;
}
return i;
}
php:
<?php
$connection = mysql_connect("localhost","root","");
$db_select = mysql_select_db("msgs",$connection);
$result = mysql_query("SELECT * FROM msgtable", $connection);
function dynamic() {
echo "faraz";
while ( $row = mysql_fetch_array( $result ) ) {
echo $row['msgBody'] ;
}
}
?>
HTML:
<body onLoad="startTime()">
<div id="chg1"> 3 Seconds to Google Pakistan </div>
Google Italia
<!-- Hafiz Faraz Mukhtar-->
<div id="time"> Time </div>
<div class="publicOut">Faraz</div>
</body>
You can't call a PHP function through JavaScript like this:
link.innerHTML = "<?php dynamic(); ?>";
You will need to make an AJAX call to run the PHP script and return the result. I would recommend using jQuery and $.ajax, which makes this very easy.
http://api.jquery.com/jQuery.ajax/
You need to use normal ajax or jquery ajax for this .Use javascript setInterval() function for setting an interval
Here is a sample jquery ajax method
function request()
{
$.ajax ({
url : "";
data : {},
dataType : "" ,
success : function(success) {} ,
error : function() {}
});
}
setInterval() Syntax
setInterval(request,3000); // in milliseconds
I have a database where i'm using php to randomize the information by ID and send it out via xml. My issue is that I only want to grab the xml once and store it for use in at least 2 functions... one function that runs onload to grab the first line of xml, another that will run every time a button is pressed to access the next line of xml until the end. My 2 functions are loadfirst() and loadnext(). loadfirst() works perfectly, but I'm not sure how to pass the xml data to loadnext(). Right now I'm just using loadfirst() on pageload and loadfirst() on button press, but i end up creating new xml from the database each time which causes randomization issues and is incredibly inefficient. Any help would be appreciated.
var places;
var i = 0;
function loadXML(){
downloadUrl("places.php", function(data){
places = data.responseXML;
getFeatured(i);
});
}
function getFeatured(index){
var id = places[index].getAttribute("id");
var name = places[index].getAttribute("name");
var location = places[index].getAttribute("location");
var imgpath = places[index].getAttribute("imgpath");
var tags = places[index].getAttribute("tags");
}
function getPrev() {
i--;
getFeatured(i);
}
function getNext() {
i++;
getFeatured(i);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
loadnext() will be very similar to loadfirst(), I'm just running into issues with passing the xml data so that i can use it without having to access the database again. Thanks.
Set your xml and i in public scope. Then all you have to do is increment/decrement i and re-read data from XML. Something like this:
var xml;
var xml_idx = 0; // replaces your i counter
function loadXML() {
downloadUrl ("places.php", function(data) {
xml = data.responseXML;
)};
}
function loadItem(index) {
var id = xml[index].getAttribute("id");
var name = xml[index].getAttribute("name");
var location = xml[index].getAttribute("location");
var imgpath = xml[index].getAttribute("imgpath");
var tags = xml[index].getAttribute("tags");
// do something with this data
}
function loadCurrentItem() {
loadItem(xml_idx);
}
function loadNextItem() {
xml_idx++;
loadItem(xml_idx);
}
function loadPreviousItem() {
xml_idx--;
loadItem(xml_idx);
}
// usage
loadXML(); // do this first to populate xml variable
loadItem(xml_idx); // loads first item (i=0)
loadCurrentItem(); // loads i=0
loadNextItem(); // loads i=1
loadNextItem(); // loads i=2
loadPreviousItem(); // loads i=1
If you really want to get fancy (and keep the global namespace cleaner), you could easily make this into a class.
Use global variables (items - items array, iterator - counter) to store data available for all functions.
Try something like this:
items = false;
iterator = 0;
function loadfirst(){
downloadUrl ("places.php", function(data) {
var i = 0;
var xml = data.responseXML;
var places = xml.documentElement.getElementsByTagName("place");
var id = places[i].getAttribute("id");
var name = places[i].getAttribute("name");
var location = places[i].getAttribute("location");
var imgpath = places[i].getAttribute("imgpath");
var tags = places[i].getAttribute("tags");
items = places;
iterator++;
)};
}
function loadnext(){
var i = iterator;
var id = items[i].getAttribute("id");
var name = items[i].getAttribute("name");
var location = items[i].getAttribute("location");
var imgpath = items[i].getAttribute("imgpath");
var tags = items[i].getAttribute("tags");
iterator++;
}
You should wrap all this into a single object to control scope and data state. (Untested code below, which should just illustrate a possible pattern and interface to use.)
function PlacesScroller(url, callback) {
this.url = url;
this.data = null;
this._index = null;
this.length = 0;
var self = this;
downloadURL(this.url, function(result, status) {
if (Math.floor(status/100)===2) {
self.setData(result);
}
if (callback) {
callback(self, result);
}
});
}
PlacesScroller.prototype.setData(xmldom) {
this._index = 0;
// this may require changing; it depends on your xml structure
this.data = [];
var places = xmldom.getElementsByTagName('place');
for (var i=0; i<places.length; i++) {
this.data.push({
id : places[i].getAttribute('id'),
name : places[i].getAttribute('name')
// etc
});
}
}
PlacesScroller.prototype.getPlaceByIndex = function(index) {
if (this.data) {
return this.data[index];
} else {
return null;
}
}
PlacesScroller.prototype.getCurrentFeature = function() {
return this.getPlaceByIndex(this._index);
}
PlacesScroller.prototype.addToIndex(i) {
// This sets the index forward or back
// being careful not to fall off the end of the data
// You can change this to (e.g.) cycle instead
if (this.data===null) {
return null;
}
var newi = i+this._index;
newi = Math.min(newi, this.data.length);
newi = Math.max(0, newi);
this._index = newi;
return this._index;
}
PlacesScroller.prototype.getNextFeature = function() {
this.addToIndex(1);
return this.getCurrentFeature();
}
PlacesScroller.prototype.getPreviousFeature = function() {
this.addToIndex(-1);
return this.getCurrentFeature();
}
Then initialize it and use it like so:
var scroller = new PlacesScroller('places.php', function(scrollerobject, xmlresult){
// put any initialization code for your HTML here, so it can build after
// the scrollerobject gets its data.
// You can also register event handlers here
myNextButton.onclick = function(e){
var placedata = scrollerobject.getNextFeature();
myPictureDisplayingThing.update(placedata);
}
// etc
});