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');
});
Related
I am new in php . I have the following code to retrieve categorytype data from database?. I want to add them into php object for temporary using while loading page. First, I want to load all predefined data, then i will use it when i click function. Could you enlighten me how to create it
categoryDao.php
namespace category;
use Exception;
use PDO;
class categoryDao{
public function categorytype(PDO $connection){
$conn = $connection;
try {
$conn = $connection;
$sql="SELECT * FROM `tb_category` WHERE id != parent_id;";
$categorytype = $conn->prepare($sql);
$categorytype->execute();
$data1 = array();
while (
$result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
return $data1;
} catch (Exception $e) {
echo $e;
throw $e;
}
}
}
categoryservice.php
use category\categoryDao;
require '../dao/categoryDao.php';
require 'Dao.php';
class categoryService{
public function categorytype(){
$dao = new Dao();
$conn= $dao->connect();
$conn->beginTransaction();
$categoryDao = new categoryDao();
//$data1 = array();
$data1=$categoryDao->categorytype($conn);
return $data1;
$dao->disconnect($conn);
}
}
categorytypecontroller.php
<?php
require '../service/categoryService.php';
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
//$ctype = array();
$ctype = $category->categorytype();
$return["json"] = json_encode($ctype);
echo $return["json"];
Head.php
function categorytype() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname1 = window.location.protocol + "//" + window.location.hostname+ "/servicegateway/sgw/modules/controller/categorytypecontroller.php";
alert (hosname1);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname1 , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data1){
alert(data1);
var obj =data1;
// var leng = Object.keys(obj).length;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#c_type").html(areaOption);
}
});
}
A couple of things. If you want the data to be an array of records, you'll probably want to change this part:
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
as that is putting all the fields, one after the other, into a normal array.
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = array(
'id' => $result['id'],
'c_name' => $result['c_name']
);
}
That will create a small associative array of the id and name fields and put it into another array, with the other records. PHP associative arrays will turn into Javascript objects when sent via ajax.
Then, in Javascript, you'll want to make use of those objects to create your options, so:
areaOption += '<option value="' + obj[i].id + '">' + obj[i].c_name + '</option>'
Below are a couple of queries that ultimately build an array.
if(isset($_POST['getarray'])){
try{
$ret = array();
$stmt = $db->prepare('SELECT groupdate, groupid
FROM participationtemp
WHERE memberid = :memberid
AND groupid = :groupid
ORDER BY groupdate, groupid DESC');
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row){
$attenddate = $row[0];
$stmt = $db->prepare('SELECT h.clientid, attend, attend_date
FROM history AS h
INNER JOIN suspended AS s on s.clientid = h.clientid
WHERE h.memberid = :memberid
AND h.groupid = :groupid
AND attend_date = :attenddate
AND suspend = "N"');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':attenddate', $attenddate, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row ) {
array_push($ret, ['id' => $row[0], 'gdate' => $row[2]]);
}
}
echo json_encode($ret);
exit();
} catch (PDOException $ex){
mail_error($ex);
}
}
After returning to JQuery, alert(re); shows I successfully created the array.
success:function(re){
alert(re);
But I'm having trouble accessing the array data. Without success, this is what i've tried:
data = $.parseJSON(re);
$.each(data, function(i, val) {
alert(i + "=" + val);
});
and this:
data = $.parseJSON(re);
$.each(data, function(i, val) {
if(i == "id"){
alert(i + "=" + val);
}
if(i == "gdate"){
alert(i + "=" + val);
}
});
I've also tried dot notation.
$.each(re.id, function(i, val) {
alert(i + "=" + val);
}
});
$.each(re.gdate, function(i, val) {
alert(i + "=" + val);
});
I've never used JSON before and don't understand why I can't retrieve the array data. Any help will be appreciated. Thanks.
The following code checks whether re is a string, or an object. The latter is possible if jQuery.ajax() method is used with "json" dataType. Also, jQuery is capable of parsing JSON automatically, if the response MIME type is application/json (the Content-Type HTTP header), particularly. So it is a good idea to check if re has been parsed by jQuery.
var d = typeof re === 'string' ? JSON.parse(re) : re;
var i;
for (i = 0; i < d.length; i++) {
console.log("id = ", d[i].id,
"gdate = ", d[i].gdate);
}
I'd recommend returning the appropriate content type from PHP:
header ('Content-Type: application/json');
echo json_encode($ret);
exit();
$.each(re, function(i, val) {
alert(val.id + "=" + val.gdate);
});
Try this code :)
// Json in string format
var jsonString = '[{"id":"1", "gdate":"2016-10-13"},{"id":"2", "gdate":"2016-10-13"},{"id":"3", "gdate":"2016-10-13"},{"id":"4", "gdate":"2016-10-13"},{"id":"5", "gdate":"2016-10-13"},{"id":"6", "gdate":"2016-10-13"}]';
// Convert string to json object
var json = JSON.parse(jsonString);
// Iterate over json object
jQuery.each(json, function(index, value) {
console.log(index, value);
});
// Simple access to attribute in json object
console.log('json[1][\'id\'] = ', json[1]['id']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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
I am using the following php code with a form which updates a table. However I want to add a javascript variable to the sql so that the variable will be added to a column in the database.
The variable is in a different file to the php.
php :=
$name = $_POST['firstname'];
$lastname = $_POST['lastname'];
$userAddress = $_POST['address'];
$userPostCode = $_POST['postcode'];
$delivery = $_POST['deliverytype'];
$sql = "INSERT INTO USERS (FIRSTNAME, SECONDNAME, ADDRESS, POST_CODE, DELIVERY_TYPE) VALUES ('$name', '$lastname', '$userAddress', '$userPostCode', '$delivery') ";
$conn->exec($sql);
i then want to add to that a totalcost variable from the following javascript that will go in Total_Order_Cost and $totalCost
here is the js function that i wish to take the variable totalPrice from
function displayBasket(){
basket = document.getElementById("basket");
string = "";
var basketStorage = localStorage.getItem("basket");
jsonBasket = JSON.parse(basketStorage);
var totalPrice = 0;
itemTotal = 0;
for (var property in jsonBasket){
var qPrice = jsonBasket[property ].quantity * jsonBasket[property ].cost;
var total = jsonBasket[property ].quantity;
string += "<section id='basketPageSection'>";
if(jsonBasket.hasOwnProperty(property )){
string += "<p>Item: " + jsonBasket[property ].name + "</p>";
string += "<p>Price: £" + jsonBasket[property ].cost + "</p>";
string += "<p>Quantity: " + jsonBasket[property ].quantity + "</p>";
}
totalPrice += qPrice;
itemTotal += total;
string += "</section>";
}
string += "<section id='basketSection'> <h3> Total Cost: £" + parseFloat(totalPrice).toFixed(2) + "</h3></section>"
basket.innerHTML = string;
displayQuant();
}
You could use a hidden input field change it value attribute and submit along with rest of the form.
<input type="hidden" name="calc" id="calc" value="">
Use Jquery to set its value
$('#calc').val(someval);
Update Javascript
document.getElementById("calc").value="Your Value";
You can use ajax.
It is the best solution for me :
Use a code like that in your javascript :
value1= ... ; // firstname
value2= ... ; // lastname
$.ajax({
type: 'post',
url: 'post.php',
data: 'firstname='+value1+'&lastname='+value2+'&address= ....,
success: function () {
alert('data sent');
}
});
Another Way
$.ajax({
type: 'post',
url: 'post.php',
data: $('#formID').serialize()+"&extraval=1&extraval2=2...",
success: function () {
alert('data sent');
}
});
I'm trying to check textbox input against a set of words in a certain order from the database to see if they match. If they do, the user's "quest" will be incremented, which will be sent to the relational database to return a new set of words for that given quest ID. the JavaScript questNum and PHP questNum variables seem to be appropriately incrementing, but the query is not getting the right result sets.
Utilities.js file:
When the page loads, I load the words for the first quest:
$(document).ready(function() {
$.each(wordsArray, function(key, value) {
$(".wordBank_Words").append("<div class='bank-word' word='" + key + "' ><b>" + key + "</b>: " + value + "</div>");
});
/*If user clicks word in word bank, word is added to text box*/
$(".bank-word").click(function (event) {
$('#textBox').val($('#textBox').val() + " " + $(this).attr('word'));
//hide word from word bank
$(this).hide();
});
/*If User removes word from text box, add it back to word bank*/
$('#textBox').on('change', function(){
var words = $(this).val().split(' ');
$('.bank-word').each(function(){
if( words.indexOf( $(this).attr('word') ) !== -1 ){
$(this).hide();
}
else {
$(this).show();
}
});
});
});
/*Check player sentence input to see if grammar is correct*/
function submitMe() {
var input = document.getElementById('textBox').value;
if ($.trim(input) == getSentence(questNum)) {
$("#responseVerify").html("Great job");
$("#textBox").val("").trigger("change");
questNum++;
$.get("php/Quests.php", { "_questNum" : questNum},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
else {
$("#responseVerify").html("Keep going...");
}
}
Quests.php file:
<?php
//if user's input is correct, increment task number
include 'DbConnect.php';
$questNumber = (isset($_GET['_questNum']) ? ($_GET['_questNum']) : 1);
echo "testing..." . $questNumber;
$sql = $mysqli->query(
"SELECT t.*, v.*
FROM task t
INNER JOIN vocabtask vt ON (t.id = vt.taskid)
INNER JOIN vocab v ON (v.id = vt.vocabid)
WHERE vt.taskid = " . $questNumber);
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
$wordsArray[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
echo "<script type='text/javascript'> var wordsArray = " . json_encode($wordsArray) . "; </script>";
?>
Before the user enters the correct sentence into the text box, echo "testing..." . $questNumber; gives output:
testing...1
When the user enters the correct string into the text box, the JS variable questNum++; is incremented, and then echo "testing..." . $questNumber; gives output:`
testing...2
So I know that the incremented JS questNum is being sent to the PHP file...
Yet the query WHERE vt.taskid = " . $questNumber); doesn't seem to be returning the appropriate new sets of words.
DB is set up as such, so I would expect that the new relational set for the new quest number would be displayed, but it's the same set of values.
So why isn't the query being changed?
Thanks
EDIT: Echoing out the sql gives:
1) Before I increment the questNum:
SELECT t.*, v.* FROM task t INNER JOIN vocabtask vt ON (t.id = vt.taskid) INNER JOIN vocab v ON (v.id = vt.vocabid) WHERE vt.taskid = 1
2) After I increment the questNum:
SELECT t.*, v.* FROM task t INNER JOIN vocabtask vt ON (t.id = vt.taskid) INNER JOIN vocab v ON (v.id = vt.vocabid) WHERE vt.taskid = 2
I copied both of these into phpMyAdmin with success:
<?php
//if user's input is correct, increment task number
include 'DbConnect.php';
$questNumber = (isset($_GET['_questNum']) ? ($_GET['_questNum']) : 1);
echo "testing..." . $questNumber;
$sql_str = "
"SELECT t.*, v.*
FROM task t
INNER JOIN vocabtask vt ON (t.id = vt.taskid)
INNER JOIN vocab v ON (v.id = vt.vocabid)
WHERE vt.taskid = " . $questNumber";
$sql = $mysqli->query($sql_str);
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
$wordsArray[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
echo json_encode($wordsArray);
?>
function submitMe() {
var input = $("#textBox").val();
if ($.trim(input) == getSentence(questNum)) {
$("#responseVerify").html("Great job");
$("#textBox").val("").trigger("change");
questNum++;
$.ajax({
url: "php/Quests.php",
dataType: "json",
method: "GET",
data: {"_questNum":questNum},
success: function(result){
$.each(result, function(key, value) {
$(".wordBank_Words").append("<div class='bank-word' data-word='" + key + "' ><b>" + key + "</b>: " + value + "</div>");
});
}
});
}else {
$("#responseVerify").html("Keep going...");
}
}