get value in php from js function - javascript

I am confused that how to get data from js to php variable.In JS function, I am getting data frequently on event.The problem is I want to get data in php frequently because it is real time data.payload contains the data whenever the data comes.So I have to get value of payload continuously.
<html>
<head>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="mqttws31.js" type="text/javascript"></script>
<script>
function myFunction(p1, p2) {
return p1 * p2;
};
var mqtt,payload;
var value = 10;
var reconnectTimeout = 2000;
function MQTTconnect() {
if (typeof path == "undefined") {
path = '/mqtt';
}
mqtt = new Paho.MQTT.Client(
'broker',
1883,
"/mqtt",
"a:" + "abcdef" + ":" + Date.now()
);
var options = {
timeout: 3,
useSSL: false,
cleanSession: true,
onSuccess: onConnect,
onFailure: function (message) {
$('#status').val("Connection failed: " + message.errorMessage + "Retrying");
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
options.userName = 'user';
options.password = 'password';
mqtt.connect(options);
}
function onConnect() {
document.writeln("connected");
// Connection succeeded; subscribe to our topic
mqtt.subscribe('iot-2/type/+/id/+/evt/evt1/fmt', {qos: 0});
//$('#topic').val('iot-2/type/" + "+" + "/id/" + "+" + "/evt/evt1/fmt');
}
function onConnectionLost(response) {
setTimeout(MQTTconnect, reconnectTimeout);
//$('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");
};
function onMessageArrived(message) {
var topic = message.destinationName;
payload = message.payloadString;
//document.writeln(payload);
//document.write("\n");
//$('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
};
</script>
</head>
<body>
<?php
$db = '<script type="text/javascript">document.write(MQTTconnect());</script>';
$db1 = '<script type="text/javascript">document.write(payload);</script>';
echo $db;
echo $db1;
?>
</body>
</html>

You can do something like
echo '<script type="text/javascript">'
, 'document.write(MQTTconnect());'
, '</script>'
;

the applicable way to get data in php frequently is to assign js data for an php element when it change .
for example , when js function executed you can write
$("Element").val(output)// from js function
, $("element").html(output) or
by document.getElementById(element) etc...`
So , any change will change the value of php element accordingly

Related

Function to get a value json to string in javascript

I need help to get a value of a json for a function and pass this value of the function to the console, but now i'm recive var = undefined, follow the code below, thanks
var Site = {
baseUrl: "https://www.usereserva.com/",
visitUrl: "https://cloud-commerce-visit.oracleoutsourcing.com/"
}
var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId;
var prodId = '0058597';
console.log("============= SCRIPT CALLCAPRODUCT ==============");
console.log("url API: " + prodAPI);
console.log("Id buscada: " + prodId);
var request = require('request');
var price;
function prodPrice() {
request(Site.baseUrl + "ccstoreui/v1/prices/" + prodId, function (error, response, body) {
var corpo = JSON.parse(body);
price = corpo['sale'];
console.log(price); // result 169
});
}
console.log("preço: " + prodPrice());
console.log("Requisição CALLPRODUCT foi bem sucedida");
console.log("================================================");
Yes, you are using prodId variable before assigning the value to prodId. This will return error. Here hoisting will take place. Your code will be compiled as
var Site = {
baseUrl: "https://www.usereserva.com/",
visitUrl: "https://cloud-commerce-visit.oracleoutsourcing.com/"
}
var prodId ;
var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId; // so here
// prodId is undefined,thats why error.
prodId = '0058597';
console.log("============= SCRIPT CALLCAPRODUCT ==============");
console.log("url API: " + prodAPI);
console.log("Id buscada: " + prodId);
var request = require('request');
var price;
function prodPrice() {
request(Site.baseUrl + "ccstoreui/v1/prices/" + prodId, function (error, response, body) {
var corpo = JSON.parse(body);
price = corpo['sale'];
console.log(price); // result 169
});
}
console.log("preço: " + prodPrice());
console.log("Requisição CALLPRODUCT foi bem sucedida");
console.log("================================================");
initialize and assign the prodId variable first and then use it
var prodId = "0058597";
var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId;
Another one is that you are not returning any value from prodPrice() method and default return is undefined.
return the required value from method.
Please read about hoisting in java script. this will help Hoisting
Use Let or const instead of var to avoid such problems.
https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75

Cannot retrieve data from PHP array, which is returned by a function() that uses JQuery Ajax

I have this "click Listener" that calls and sends a userId parameter to the function-"getModalData" which then returns an array value to the variable-"arrayedUserData".
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '',
arrayedUserData = getModalData(userId);
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
This is the function-"getModalData". The returned php array from the Ajax's "success" will then be passed to the variable-"UserData" that is then returned by the function.
function getModalData(passedUserId) {
var UserData;
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
UserData = data;
}
}
);
return UserData;
}
this is the "get_modal_data.php".
<?php
include "../includes/connect.php";
if (isset($_POST['passedUserId'])) {
$UserId = mysqli_real_escape_string($con, $_POST['passedUserId']);
$getUserData = mysqli_query($con, "SELECT * FROM tblUserAccounts WHERE uaUserId = '".$UserId."'");
$uaRow = mysqli_fetch_assoc($getUserData);
$UserDataArr = array("UserId" => $uaRow['uaUserId'],
"EmailAddress" => $uaRow['uaEmailAddress'],
"FirstName" => $uaRow['uaFirstName'],
"LastName" => $uaRow['uaLastName'],
"BirthDate" => $uaRow['uaBirthDate'],
"Address" => $uaRow['uaAddress'],
"Gender" => $uaRow['uaGender'],
"ContactNumber" => $uaRow['uaContactNumber'],
"BloodTypeId" => $uaRow['uaBloodTypeId'],
"AccountStatus" => $uaRow['uaAccountStatus'],
);
echo json_encode($UserDataArr);
exit();
}
?>
this error appears on the console:
Uncaught TypeError: Cannot read property 'LastName' of undefined get_user_accounts.js:66
this is the line 66 of get_user_accounts.js, which is present on the "click listener".
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
but, I am confused because the php array appears on the browser's Network Response:
Successful Connection{"UserId":"1","EmailAddress":"paulanselmendoza#gmail.com","FirstName":"Paul Ansel","LastName":"Mendoza","BirthDate":"1998-12-17","Address":"Phase 1B Block 8 Lot 20 Olivarez Homes South, Sto. Tomas, Binan City, Laguna","Gender":"Male","ContactNumber":"2147483647","BloodTypeId":"0","AccountStatus":"ACTIVE"}
Did you see that you get: Successful Connection before the JSON data? You have to remove that, if not it will be an invalid JSON response. The code you have shared doesn't have the particular stuff.
I believe you have to check your database connection, where on successful connection, it is set to output Successful Connection, which breaks your response. Please remove that bit of code.
include "../includes/connect.php";
It can be something like:
$conn = mysqli_connect() or die("Error");
echo "Successful Connection";
Because getModalData fucntion return the UserData before it asign by ajax(UserData = data;). use a callback function:
using callbacks
function getModalData(passedUserId,callback) {
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
callback(data);
}
}
);
}
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '';
getModalData(userId, function (arrayedUserData) {
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
});

Getting results from logger to return to web app

I am very close, however not there yet. The logger displays the search results- however I still am not able to get the results to display on the web app.
The search on the web app does work and the results display in the logger.
Please advise. Thanks!
Here is updated,
Code:
function SearchFiles(searchTerm) {
var searchFor ="title contains '" + searchTerm + "'";
var owneris ="and 'Email#email.com' in Owners";
var names =[];
var fileIds=[];
Logger.log(searchFor + " " + owneris);
var files = DriveApp.searchFiles(searchFor + " " + owneris);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}
for (var i=0;i<names.length;i++){
//this is showing in the Logger
Logger.log(names[i]);
Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);
}
}
function returnNames() {
var names = SearchFiles();
return '<b>returnNames has ran.!</b> <br>' + names ;
}
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate()
.setTitle('Hello World')
// .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn)
// shows as undefined in the logger
return resultToReturn;
}
function helloWorld()
{
return "Hello World!";
}
INDEX:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.processForm(searchTerm);
google.script.run.withSuccessHandler(handleResults).returnNames();
}
function handleResults(returnVal){
console.log('Handle Results was called! ');
document.writeln(returnVal);
}
</script>
</head>
<body>
<input type="text" id="idSrchTerm" name="search">
<input type="button" value="submitButton" name="submitButton" onclick="displayMessage()"/>
</body>
</html>
You are missing the withSuccessHandler of the script runner.
Check out the docs at:
https://developers.google.com/apps-script/guides/html/reference/run#withSuccessHandler(Function)
example:
<script>
google.script.run
.withSuccessHandler(handleResults)
.processForm(searchTerm);
function handleResults(returnVal){
console.log(returnVal)
}
</script>

Store value in DB with PHP - Ajax call from JavaScript

i want to store a value in a database with PHP. I call a PHP-function with AJAX.
I check on document.ready() if the website was called with a parameter called temperature:
$(document).ready(function(){
var data = 5; //gup('temperature', location.href);
if(data != undefined){
var sendData = 'func=storeValue&value=' + data + '&datetime=' + getDateTime();
$.ajax({
data: sendData,
type: "POST",
url: "FunctionManager.php",
success: function(data){
alert("Data Saved " + data);
},
error: function(xhr){
alert(xhr.responseText);
}
})
}
}
I use a the php file "FunctionManager" to call the according function which i determine with the passed parameters. So i pass dataand datetime. My FunctionManager looks like this:
<?php
include "$_SERVER[DOCUMENT_ROOT]/SQLCommunication.php";
header('Content-Type: application/json');
if(!isset($_GET['func']) && empty($_GET['func'])){
exit();
}
if($_POST['func'] === "readValue"){
echo readValue();
}elseif($_POST['func'] === "storeValue"){
echo storeValue($_POST["value"], $_POST["datetime"]);
}
?>
So as you can see i first check which function is called and then call the function itself with parameters. I know that this works because i have a new row in my database after calling the website with a parameter. But the fields datetime and value are always zero.
My storeValue- function is located in SQLCommunication.phpand looks like this:
function storeValue($val, $datetime){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
//$datetime = date_default_timezone_get();
//$datetime = '2016-01-04 00:18:00';
$sql = "INSERT INTO tempvalues (datetime, value) VALUES ('$datetime', '$val')";
$conn->query($sql);
$conn->close();
}
This is the function i use to read the temperature parameter:
function gup( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url ).toString();
return results == null ? null : results[1];
}
Do you have any ideas which mistake i made?
Thanks
The jquery code must be like this. If you look at your browser console, you may see some errors.
The jquery should be like this:
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
newdate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
$(document).ready(function(){
var storeValue = 'storeValue';
var data = gup('temperature', location.href);
if(data != undefined){
yourData = 'func='+storeValue+'&value='+data+'&newdate='+newdate;
$.ajax({
data: yourData,
type: "POST",
url: "FunctionManager.php,
success: function(data){
alert("Data Saved " + data);
},
error: function(xhr){
alert(xhr.responseText);
}
});
}
});
In Functionmanager.php
print_r($_POST);
include "$_SERVER[DOCUMENT_ROOT]/SQLCommunication.php";
header('Content-Type: application/json');
if(!isset($_POST['func']) || empty($_POST['func'])){
exit();
}else{
$func = isset($_POST['func'])? $_POST['func']: 'storeValue';
$val = isset($_POST['value'])? $_POST['value']:'';
$datetime = isset($_POST['newdate'])? $_POST['newdate']:'';
if($func == 'readValue'){
echo readValue();
}elseif($func == 'storeValue'){
echo storeValue($val, $datetime);
}
}
In your date field in your table, set datatype as datetime. Hope this may help.

Function didn't run as expected

To start i'm using jquery,php,sql,html & css.
I am facing a issue that is giving me serious problem. I am trying to run a $.post function to retrieve values from my database of a party group(4 members value stored in 4 columns in the database. After retrieving the value, i run a while loop and append each value of the party onto a listview.
Then i send the current while loop value over to another $.post function to check for the rating score for the member i'm currently checking, and retrieve the result to display onto the li that i am currently appending.
This is what i have
$('body').on("pagebeforeshow","#p-partyDetail",function(){
var teamID = globalIndex;
var currentMem = "";
$.post("retrieveMemDetails.php",
{
teamID:teamID, // data to pass into php
username:globalUsername,
}, // data to pass into php
function(response)
{
var x = 1; // define value as 1
while(x<=4){ // if loop is below or equal to 4, run loop
//member = response.mem + x;
member = response['mem' + x]; // define member1 in variable,
currentMem = member;
console.log("current x value is " + x);
if(member !=""){
var y = x.toString();
console.log("y is " + y);
$.post("retrieveRatingDetails.php",
{
username:currentMem, // data to pass into php
}, // data to pass into php
function(response2)
{
$("p#" +y).html(response2.rating);
console.log("full name is " + response2.name + " rating is " + response2.rating);
console.log("retrieve rating valued:"+response2.rating+" to p#"+y);
console.log("end of loop cycle" + y);
}, 'json'
);
$("#partyDetail-listview").append('<li> <img src="images/final-fantasy-7-final-fantasy-vii-6973833-1024-768.jpg"> <h2>'+ member + '</h2> <p id="'+ x +'"></p> </li>').listview("refresh");
console.log("appended count:" + x);
}
x++;
}
}, 'json'
);
});
my php for retrieving member detail
include_once('db.php');
session_start();
$teamID = ($_POST['teamID']);
$username = ($_POST['username']);
$result = $db->query("SELECT * FROM `studentparty` WHERE `id` = '".$teamID."'");
$result3 = $db->query("SELECT *` FROM `userdetails` WHERE `username` = '".$username."'");
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_array($result);
$mem1 = $row["mem1"];
$mem2 = $row["mem2"];
$mem3 = $row["mem3"];
$mem4 = $row["mem4"];
$result2 = json_encode(array("mem1"=>$mem1, "mem2"=>$mem2, "mem3"=>$mem3, "mem4"=>$mem4));
echo $result2;
}
my php for retrieving rating scores
include_once('db.php');
session_start();
$username = ($_POST['username']);
$result4 = $db->query("SELECT * FROM `userdetails` WHERE `username` = '".$username."'");
if(mysqli_num_rows($result4)>0)
{
$row = mysqli_fetch_array($result4);
$rating = $row["Rating"];
$name = $row["FullName"];
$result5 = json_encode(array("rating"=>$rating, "name"=>$name));
echo $result5;
}
my member & rating are under different table so i called $.post twice.
Apparently after debugging for hours, i found out that it will loop through
console.log("current x value is " + x);
then
console.log("y is " + y);
then
console.log("appended count:" + x);
running through a total loop count of 4 before it run
console.log("full name is " + response2.name + " rating is " + response2.rating);
console.log("retrieve rating valued:"+response2.rating+" to p#"+y);
console.log("end of loop cycle" + y);
this caused the rating to only keep updating on the value y, as the flow of the function are already wrong.
My ideal flow is
-retrieve party member details from php
-while displaying mem1 from php using while loop, append a li only my ul.
-send the current mem1 data into my next $.post function to retrieve rating data
-update the li with the rating data
-end of loop and begin with member2
Can someone point out to me what wrong with my script? Thanks!
I strongly recommend that one ajax request is enough to get requested data. If you make inner ajax request, you have to wait other lines to be executed. Because it is asynchronous functions. You can also set your ajax call synchronously with the code as in below:
$.ajax({
...
async: false,
...
});
But then you have to wait until your callback function is executed. So, sometimes it is dangerous for your performance.
If you change your php side as in below, you will get an array with objects which have member and member's detail.
include_once('db.php');
session_start();
$teamID = ($_POST['teamID']);
$result_detail = $db->query("SELECT * FROM `studentparty` WHERE `id` = '".$teamID."'");
if(mysqli_num_rows($result_detail) > 0)
{
$data = array();
$mem = array();
$row = mysqli_fetch_array($result);
$mem[0] = $row["mem1"];
$mem[1] = $row["mem2"];
$mem[2] = $row["mem3"];
$mem[3] = $row["mem4"];
for($i = 0; $i < count($mem); $i++) {
$result_rating = $db->query("SELECT *` FROM `userdetails` WHERE `username` = '".$mem[$i]."'");
$rating_array = array();
if(mysqli_num_rows($result_rating) > 0)
{
$row2 = mysqli_fetch_array($result_rating);
$rating = $row2["Rating"];
$name = $row2["FullName"];
$rating_array = array("rating"=>$rating, "name"=>$name));
}
$data[$i] = array_merge(array("member" => $mem[$i]), $rating_array);
}
$result_json = json_encode($data);
echo $result_json;
}
I also adopted your javascript code to new response. I couldn't test both. I hope it will work well.
$('body').on("pagebeforeshow","#p-partyDetail",function(){
var
teamID = globalIndex,
currentMem = "",
callback = function(response) {
var member, id;
$.each(response, funciton(i, obj) {
member = obj['member'];
id = (i+1); // if you have ids for members, you can send in php additionally. it would be better than (i+1)
$("#partyDetail-listview").append('<li> <img src="images/final-fantasy-7-final-fantasy-vii-6973833-1024-768.jpg"> <h2>'+ member + '</h2> <p id="'+ id +'"></p> </li>').listview("refresh");
console.log("appended count:" + id);
if (member) {
$("p#" + id).html(obj['rating']);
console.log("full name is " + obj['name'] + " rating is " + obj['rating']);
console.log("retrieve rating valued:"+obj['rating']+" to p#" + id);
console.log("end of loop cycle" + id);
}
});
};
$.post("retrieveMemDetails.php",
{
teamID:teamID, // data to pass into php
username:globalUsername,
}, // data to pass into php
callback, 'json');
});

Categories