Trouble getting php data from database through javascript function - php

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

Related

Ajax post work but PHP doesn't recognize it

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.

Passing 2 datas from AJAX to PHP

So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;

Pass dropdown options to PHP variable (without page refresh)

I'm trying to pass the value of the dropdown menu to the PHP variable $anno, so the print_r() function at the end can use the realtive $coefficiente variable (which depends on $anno).
<select name="anno">
<option>1940</option>
<option>1941</option>
<option>1942</option>
</select>
<?php
$importo = "100";
$anno = $_POST["anno"];
if ( $anno == "1940" ) { $coefficiente = "10"; } ;
if ( $anno == "1941" ) { $coefficiente = "20"; } ;
if ( $anno == "1942" ) { $coefficiente = "30"; } ;
print_r(($importo*$coefficiente)/1936.27); echo '€';
?>
Can this be "AJAXified"?
At this time when I choose the dropdown option, the print_r function isn't updated. Do I need a submit button?
If you want to calculate your formula in the same page, don't use PHP use Javascript
<select name="anno">
<option>1940</option>
<option>1941</option>
<option>1942</option>
</select>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("select[name='anno']").on('change', function(e) {
var importo = "100";
var anno = $(this).val();
var coef = "";
if (anno == 1940) { coef = 10; }
if (anno == 1941) { coef = 20; }
if (anno == 1942) { coef = 30; }
alert(importo*coef/1936.27 + "€");
})
});
For PHP handling, use AJAX (warning I couldn't test this!)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("select[name='anno']").on('change', function(e) {
$.ajax({
type: "POST",
url : "your_php_script.php",
data: { anno: $(this).val() },
})
.done(function(data) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Something went wrong!\n" + errorThrown);
});
})
});

Jquery .Ajax - How to Pass Data

I'm trying to pass a variable via jquery ajax call. I'm not exactly sure how to do it properly. I get the lon lat coordinates through another html5 script.
How do i get the coordinates on the other side? I tried $_GET(lat).
I'm also not sure if i'm able to use the location.coords.latitude in a different < script >.
$.ajax({
cache: false,
url: "mobile/nearby.php",
dataType: "html",
data: "lat="+location.coords.latitude+"&lon="+loc.coords.longitude+,
success: function (data2) {
$("#nearbysgeo").html(data2);
}
});
These scripts are above the jquery code
<script type="text/javascript">
google.setOnLoadCallback(function() {
$(function() {
navigator.geolocation.getCurrentPosition(displayCoordinates);
function displayCoordinates(location) {
var map = new GMap2(document.getElementById("location"));
map.setCenter(new GLatLng(location.coords.latitude, location.coords.longitude), 12);
map.setUIToDefault();
var point = new GLatLng(location.coords.latitude, location.coords.longitude);
var marker = new GMarker(point);
map.addOverlay(marker);
}
})
});
</script>
<script type="text/javascript" charset="utf-8">
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
document.getElementById("output").innerHTML = "Your browser doesn't handle the GeoLocation API. Use Safari, Firefox 4 or Chrome";
}
}
function success(loc){
console.log(loc);
strout = "";
for(l in loc.coords){
//strout += l +" = " +loc.coords[l] + "<br>";
}
strout += '';
strout += '<center><img src="http://maps.google.com/maps/api/staticmap?center='+loc.coords.latitude+','+loc.coords.longitude+'&markers=color:blue%7Clabel:Y%7C'+loc.coords.latitude+','+ loc.coords.longitude+'&zoom=15&size=400x250&sensor=false&center=currentPosition"></center>';
document.getElementById("output").innerHTML = strout;
document.forms['newPostForm'].lat.value = loc.coords.latitude;
document.forms['newPostForm'].lon.value = loc.coords.longitude;
document.getElementById("coords").innerHTML = '';
document.getElementById("coords").innerHTML = 'CURRENT: Lat:' + loc.coords.latitude + ' Lon:' + loc.coords.longitude;
}
function error(err){
document.getElementById("output").innerHTML = err.message;
}
function clearBlog() {
document.getElementById("listview").innerHTML = '';
}
</script>
ADDITIONAL INFO:
It works if I use this line. So i guess i can't use loc.coords.latitude this way.
data: "&lat=43&lon=-79.3",
Well i hacked it for now to get it working. I filled two hidden form elements on the page with lon and lat values. Then used 'document.forms['newPostForm'].lat.value' to create a line like this.
data: "&lat="+document.forms['newPostForm'].lat.value+"&lon="+document.forms['newPostForm'].lon.value,
Still would like an actual solution.
Here's some code from a project I'm working on. Very simple.
$.post("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
You can switch out .post with .get with no other changes, like so:
$.get("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
Data is passed in name value pairs like so.
{ post_action: "getRecentPosts", limit: "10" }
Rewrite:
$.get("mobile/nearby.php", { lat: location.coords.latitude, lon: loc.coords.longitude }, function(data2){
$("#nearbysgeo").html(data2);
});
$lat = preg_replace('#[^0-9\.]#', '', $_GET['lat']);
You probably can use location.coords.latitude if it is defined before.
jQuery.ajax(
{
url : 'mobile/nearby.php',
data : {
'action' : 'update',
'newname' : 'enteredText',
'oldname' : 'original_html',
'userid' : '10'
},
success : function(msg){
if(msg == 1)
{
alert('success');
}
}
});
this is the proper syntax of jQuery.Ajax(); function

Solving Dual URL Problem..?

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.

Categories