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.
Related
Trying to use AJAX to submit form data to a PHP file. Everything in the code seems to work except for a call to the PHP file.
I setup a Java Alert() on the PHP file and it never alerts.
I am sure it is an issue with the AJAX code but I don't know it well enough to figure out what is going wrong.
The AJAX Call:
$(document).on('click','.addItem',function(){
// Add Item To Merchant
var el = this;
var id = this.id;
var splitid = id.split("_");
// Add id's
var addid = splitid[1]; // Merchant ID
var additem = splitid[2]; // Item ID
// AJAX Request
$.ajax({
url: "jquery/addItem.php",
type: "POST",
data: { mid : addid , iit : additem },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(300, function(){
$(this).remove();
});
}
});
});
The HTML Form Call Within a Table:
<span class='addItem' id='addItem_<?php echo $m; ?>_<?php echo $list['id']; ?>' >Add Item</span>
Ok Simple PHP code that it calls to with some alerts for testing:
<?php
require_once("../includes/constants.php");
require_once("../includes/functions.php");
$iid = filter_input(INPUT_POST, 'iit', FILTER_SANITIZE_STRING); // Item ID
$mid = filter_input(INPUT_POST, 'mid', FILTER_SANITIZE_STRING); // Merchant ID
$slot = 0;
$slot = getMerchSlot($mid);
?>
<script>
alert ("Slot Value: <?php echo $slot; ?>");
</script>
<?php
$result = $pdoConn->query("INSERT INTO merchantlist (merchantid, item, slot)
VALUES
('$mid', '$iid', '$slot') ");
if ($result) {
?>
<script>
alert("Looks like it worked");
</script>
<?php
}
echo 1;
?>
I am getting particular list of product items through ajax, by passing their unique id to server. Now each product has its own set of properties which I have to display on page with product image. When I set the values through jquery, only last value in the array got printed. Following are my coding files.
images.php
while($fetch = mysql_fetch_array($result))
{
?>
<div class="col-sm-4">
<div class="thumbnail">
<a class="productitemid" href="productpurchase.php?id=<?php echo $fetch['itemID'];?>"><img class="img-responsive productimage" src="uploadedfiles\<?php echo $fetch['imageURL'];?>" alt="<?php echo $fetch['imageURL'];?>" /></a>
<div class="text-center productitemname" style="font-weight:bold;"><?php echo $fetch['itemName']; ?></div>
<div class="badge col-sm-offset-1 productprice"><?php echo $fetch['price']; ?></div>
<span class="col-md-offset-7"><a class="productitemid btn btn-success" href="productpurchase.php?id=<?php echo $fetch['itemID'];?>">BUY</a></span>
</div>
</div>
<?php
}
js file
$(document).ready(function(){
$('.menProdCatgry').on('click',function(){
$.ajax({
type: "post",
url: "getselectedproducts.php",
data:{
"prodId" : $('.menProdCatgry').attr('prodCatId')
},
dataType: "json",
success: function(data){
console.log(data);
$.each(data, function(){
var getprodId = this.prodId;
var getimageURL = this.imageURL;
var getprice = this.price;
var getitemName = this.itemName;
var getitemID = this.itemID;
$('.productimage').attr('src','uploadedfiles\/'+getimageURL);
$('.productitemname').text(getitemName);
$('.productprice').text(getprice);
$('.productitemid').attr('href','productpurchase.php?id='+getitemID);
});
},
error: function(data){
console.log(data);
}
});
});
});
You can see the code of the foreach is only overwriting the values and attributes of the
$('.productimage'),
$('.productitemname')
// and so on
so you only see the last data of the response
$.each(data, function() {
var getprodId = this.prodId;
var getimageURL = this.imageURL;
var getprice = this.price;
var getitemName = this.itemName;
var getitemID = this.itemID;
// create a tag
var a = $('<a/>');
a.attr('href', 'productpurchase.php?id='+getitemID);
// create new image
var img = $('<img/>');
img.attr('src', 'uploadedfiles/'+getimageURL);
var prodname = $('<div/>')
prodname.html(getitemName);
var prodprice = $('<div/>');
prodprice.html(getprice);
// insert image to a
a.append(img);
var container = $('<div/>');
// combine them all
container.append(a);
container.append(prodname);
container.append(prodprice);
// append to document
// you can change this according to you need
// to accomplish
$('body').append(container);
});
here i created a dynamic dom element for every iteration of the foreach
then it will create a new sets of data then it will insert/include/append
to the html element
An alternative solution..
If you added some sort of identifier for each product-block, like below:
<div class="thumbnail" id="prodId<?php echo $fetch['prodId'];?>">
You could narrow the selector in your each to a specific scope:
$.each(data, function(){
var getprodId = this.prodId;
var getimageURL = this.imageURL;
var getprice = this.price;
var getitemName = this.itemName;
var getitemID = this.itemID;
var myScope = '#prodId' + getprodId;
$('.productimage', myScope).attr('src','uploadedfiles\/'+getimageURL);
$('.productitemname', myScope).text(getitemName);
$('.productprice', myScope).text(getprice);
$('.productitemid', myScope).attr('href','productpurchase.php?id='+getitemID);
});
This will make sure that only classes found within your defined scope (#prodIdX) are selected and altered.
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();
});
I have a form that uses the jQuery UI autocomplete function on two elements, and also has the ability to clone itself using the SheepIt! plugin.
Both elements are text inputs. Once a a value is selected from the first autocomplete (continents), the values of the second autocomplete (countries) are populated with options dependent on the first selection.
My problem is, when clones are made, if the user selects an option from the first autocomplete (continent), it changes the first input values on all clones. This is not happening for the second input (country).
What am I missing?
Note: the #index# in the form id and name is not CFML. I am using PHP, and the hash tags are part of the SheepIt! clone plugin.
Javascript:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script src="../../scripts/jquery.sheepIt.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
$('#location_container_add').live('click', function() {
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
var location_container = $('#location_container').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: false,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
maxFormsCount: 10,
minFormsCount: 1,
iniFormsCount: 1
});
var continent_autocomplete = {
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
}
var continent_autocomplete_keyup = function (event){
var code = (event.keyCode ? event.keyCode : event.which);
event.target.value = event.target.value.titleCase();
}
var country_autocomplete = {
source: loadcountry,
}
var country_autocomplete_keyup = function (event){
event.target.value = event.target.value.titleCase();
}
var country_autocomplete_focus = function(){
if ($(this).val().length == 0) {
$(this).autocomplete("search", " ");
}
}
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
</script>
HTML:
<div id="location_container">
<div id="location_container_template" class="location_container">
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name_#index#" name="continent_name_#index#" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete_#index#" name="country_autocomplete_#index#" class="country_autocomplete" />
</div>
</div>
</div>
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
That code says explicitly to set the value of every <input> with class "continent_autocomplete" to the selected value.
You probably want something like
$(this).val(ui.item.value);
but it depends on how your autocomplete code works.
This line: $("input.continent_autocomplete").val(ui.item.value); is updating all inputs with class continent_autocomplete.
UPDATE:
From jQueryUI Autocomplete Doc:select:
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
You shouldn't need the select bit at all, it looks like you're simply trying to achieve the default action.
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.