See i have below Code in my javascript
var itemCount = 5, activeScroll = 0, countScroll = 0;
setInterval(function() {
if(countScroll == (itemCount - 2))
{
activeScroll = 0;
countScroll = 0;
$('#list').animate({scrollTop: 0});
}
else
{
activeScroll += 250;
countScroll += 1;
$('#list').animate({scrollTop: activeScroll});
}
}, 2000);
and my query string in php code is
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
i am trying to assign value of $adcount in javascript variable var itemCount;
query is running in test.php and javascript is scroller.js.
Please help me .
You can output javascript by test.php:
<?php
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
?>
<script type='text/javascript'>
var itemCount = <?php echo $adcount; ?>;
setupTimer(itemCount);
</script>
Make sure the scroller.js defines the function setupTimer(itemCount) that performs the task you want, instead of firing right away.
First you need to request the value from the server. Then you can assign it.
var itemCount;
setInterval(function() {
$.get('test.php', function(response) {
itemCount = response.itemCount;
// you scroll logic here
}, 'json');
}, 2000);
In test.php you should output the value by something like this:
$output = array(
"itemCount" => $adcount
);
print json_encode($output);
in scroller.js type this code:
$.ajax("test.php", {
type: 'post',
data: {
count:itemCount
},
sync: true,
success: function (adcount) {
itemCount=adcount;
}
});
in test.phptype this code:
if (isset($_POST['count']))
{
echo $adcount;
exit;
}
notice:you should use jquery file in your script for ajax
Related
If you want to see the part where I tried AJAX, go look down below. It completely messed up the page and I'm stuck on how to do this. I've got some code here:
$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id='$id'";
$INFO=mysqli_query($conn, $sql);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
echo "riskcoin: " . $row["riskcoin"]. "<br>";
$riskcoins = $row["riskcoin"];
}
} else {
echo "0 results";
}
?>
var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
// Bets methods
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
};
Bets.prototype.doubleDown = function() {
this.pot -= this.bet;
this.bet += this.bet;
};
Bets.prototype.potAmount = function() {
return this.pot;
};
Bets.prototype.betAmount = function(){
return this.bet;
};
Bets.prototype.disableDeal = function () {
$('#button-deal').addClass('disabled');
};
Bets.prototype.addBet = function(amount) {
if (this.pot >= amount) {
this.pot = this.pot - amount;
this.bet = this.bet + amount;
this.updateAmounts();
$('#button-deal').removeClass('disabled');
} else {
notEnoughChips();
}
};
First part is php second part js. I have an int value in my database called riskcoin. this.pot contains that riskcoin value (//Bets object) and shows itin another php file in a paragraph with id="pot".
When an image is clicked another function ads an amount to the bet depending on the picture (for example 5).
Now my question: after the line this.updateAmounts(); it executes
// Bets methods
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
Now my question would be if I could update the riskcoin value in my database with an update query after this function with the current this.pot value? It should show live updates without page refreshes. I've read about AJAX so I tried something like this:
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
window.history.pushState('page2', 'Title', '?coins=' + this.pot);
$(document).ready(function(){
var url = window.location.href;
var params = url.split('?coins=');
var id = (params[1]);
$("#button-deal").click(function(){ $.ajax({
type:"POST",
url:"blackjackgame.php",
data:{id:id},
success:function(result){
$("#pot").html(result);
}
});
});
});
};
But it for some reason when I click on the deal button (#button-deal) it shows up my login page in the middle of the page under all the other stuff, console gives me: GET http://riskybusiness.nglyceum.eu/games/login.css net::ERR_ABORTED 404 (Not Found)jquery-3.1.1.js:5921
PHP and Javascript execute in different contexts. PHP on the server, Javascript on the client (browser). Keep your PHP code and Javascript separate. Since PHP executes first on the server, you can embed PHP output into your HTML/Javascript/CSS—BEFORE—it is sent to the browser.
One problem you have with your code is intermingling PHP and Javascript, such as:
<?php
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
echo "riskcoin: " . $row["riskcoin"]. "<br>";
$riskcoins = $row["riskcoin"];
}
} else {
echo "0 results";
}
?>
var dealerHand = [];
var playerHand = [];
var currentHand;
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
The PHP (only) gets processed on the server, and this text is sent to the client:
riskcoin: 100<br>
var dealerHand = [];
var playerHand = [];
var currentHand;
// Bets Object
function Bets() {
this.pot = 100;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
Also, this $("#button-deal").click(function(){ in your code adds a click event handler to your button. The problem is, you're not adding this event handler until addBet() is executed, which then executes updateAmount(). Not only don't wait, but the handler is added each time addBet() is executed. Instead add the event handler on page load.
I've separated the various code components into server-side execution and client-side execution contexts, and properly connected them to each other:
var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();
// Bets Object
function Bets() {
this.pot = 100; // <?=$riskcoin?>;
this.bet = 0;
$('#bet span').text('$' + 0);
$('#pot span').text('$' + this.pot);
$('#deal button').addClass('disabled');
}
// Bets methods
Bets.prototype.updateAmounts = function() {
$('#bet span').text('$' + this.bet);
$('#pot span').text('$' + this.pot);
};
Bets.prototype.potAmount = function() {
return this.pot;
};
Bets.prototype.betAmount = function(){
return this.bet;
};
Bets.prototype.addBet = function(amount) {
if (this.pot >= amount) {
this.pot = this.pot - amount;
this.bet = this.bet + amount;
this.updateAmounts();
$('#deal button').removeClass('disabled');
} else {
notEnoughChips();
}
};
// add the click event handler on page load
document.querySelector("#deal button").addEventListener("click", evt => {
$.ajax({
type: "POST",
url: "deal.php", // <-- post data to separate PHP file, see PHP file below
data: {bet: bets.betAmount()},
success: function(result) {
const win = (result > bets.pot)? " (won)": " (lost)";
bets.pot = result;
bets.bet = 0;
$("#pot span").text('$' + bets.pot + win);
$('#bet span').text('$' + bets.bet);
$('#deal button').addClass('disabled');
}
});
});
document.querySelectorAll("#bet button").forEach(btn => {
btn.addEventListener("click", evt => {
bets.addBet(parseInt(evt.target.textContent));
});
});
function notEnoughChips() {
alert("Not enough chips.");
}
// mock ajax, remove in real world
$.ajax = (function () {
return function (params) {
if (Math.random() < 0.5) {
params.success(bets.pot + (params.data.bet * 2));
} else {
params.success(bets.pot);
}
};
}());
.disabled {
cursor: not-allowed;
pointer-events: none;
color: #c0c0c0;
background-color: #ffffff;
}
<!-- uncomment in the real world
<?php
$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id=?"; // <-- use prepared statements
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
$riskcoin = $row["riskcoin"];
}
} else {
$riskcoin = 0;
}
?>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="pot">Pot: <span><?=$riskcoin?></span></div>
<div id="bet">Bet: <span>0</span> <button>+5</button><button>+10</button><button>+15</button><button>+20</button></div>
<div id="deal"><button>Deal</button></div>
deal.php (The JQuery ajax function POSTs to this file.)
<?php
// this file called in JQuery ajax function found in "#deal button" "click" handler
$id = $_SESSION["id"];
$bet = $_POST["bet"];
$sql = "SELECT riskcoin FROM klanten WHERE id= ?";
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
$riskcoin = $row["riskcoin"];
}
} else {
$riskcoin = 0;
}
// random win or lose
$riskcoin += ((bool)random_int(0, 1))? ($bet * 2): (-1 * abs($bet));
$sql = "UPDATE klanten SET riskcoin = ? WHERE id = ?";
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ii", $riskcoin, $id);
mysqli_stmt_execute($stmt);
echo $riskcoin;
?>
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
You cannot put php code inside of javascript as PHP is server side so it runs before javascript.
I believe your best option would be to use php for all of it.
I am having to solve a problem involving code in both JS and PHP. For some reason, whenever this code executes, it puts the first entry in all the rows of the table instead of iterating through each entry and putting all of them in the rows. I would appreciate someone's help in giving me insights into how to fix this issue. Can this be fixed with just a "for in" loop? Thanks in advance.
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$sql = "SELECT COUNT(`LID`) AS `x` FROM `snipe`.`plobby` WHERE LID = '".$_POST['id']."';";
$result = $db->query($query);
$rst = $db->query($sql);
$cnt = 0;
if($rst->num_rows > 0)
while($row = $rst->fetch_assoc())
$cnt = $row["x"];
if ($result->num_rows > 0)
for($i = 1;$i<= $cnt;$i++)
echo json_encode($result->fetch_assoc());
else
echo json_encode([]);
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here is the object to which the above loop is referring:
<script type="text/javascript">
var state = {};
for($i = 1;$i <= <?php echo getLobbytPlayers($_GET['id']);?>;$i++ ){
var reloadTable = function (data) {
if ($.data(state) == $.data(data)) {
return;
}
$('#js-lobby-table').empty();
$.each(data, function (rowNumber, rowData) {
var row = $('<tr>');
console.log(data);
// Player
row.append($('<td>', {
'html': data.eName
}));
// Status
row.append($('<td>', {
'html': data.gameID == "000" ? 'waiting' : 'ingame'
}));
// Win %
row.append($('<td>', {
'html': 'TODO'
}));
// Games
row.append($('<td>', {
'html': 'TODO'
}));
// K/D
row.append($('<td>', {
'html': 'TODO'
}));
$('#js-lobby-table').append(row);
});
// Set the current table state.
state = data;
};
}
setInterval(function () {
$.ajax({
type: 'POST',
url: '/lobby/api/table.php',
data: {
id: '<?= $_GET['id'] ?>'
},
success: reloadTable,
dataType: 'json'
});
}, 10);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You shouldn't call json_encode() multiple times. The response has to contain a single JSON object, not multiple objects. You need to put all the results in an array, and call json_encode() on that array at the end.
There's also no need to get the count first. Just call fetch_assoc() until you get all the results.
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$result = $db->query($query);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
?>
I am trying to run a specific for loop every x seconds, but cannot seem to make `setInterval work. I am sure my syntax is incorrect, yet, I cannot seem to get it right.
I have added my full code below:
jQuery:
//Click saves this.id as userID
$(function() {
var rTitle, rText, qTitle, qText, numRows, userID;
$("#buttons").find(".btn").click(function() {
$(this).parent().toggleClass('fullscreen');
$(this).parent().siblings().toggleClass('master');
var userID = this.id;
//userID is then used for ajax to PHP script, information passed back is put in variables and generateProblems function is run
$.ajax({
type: "POST",
url: 'include/responseget.php',
dataType: 'json',
data: {
userID: userID
},
success: function(json) {
rTitle = json.rTitle;
rText = json.rText;
qTitle = json.qTitle;
qText = json.qText;
next = json.next;
numRows = json.numRows;
id = json.id;
generateProblems();
}
});
});
//Generate draggable html with an interval of 1000
function generateProblems() {
$('<div>' + qTitle + '</div>').data('number', qTitle).attr('id', 'question').attr('class', 'bold').appendTo($("#" + id).parent()).hide().fadeIn(2000);
for (var i = 0; i < numRows; i++) {
setInterval(function() {
$('<div>' + rTitle[i] + '</div>').data('number', next[i]).attr('id', +next[i]).appendTo($("#" + id).parent()).draggable({
containment: '.site-wrapper',
stack: '#testpile div',
cursor: 'move',
revert: true
}).hide().fadeIn(2000)
$('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).appendTo($("#" + id).parent()).hide().fadeIn(2000);
}, 1000);
}
//Rest of the code is not important, but I put it in nonetheless.
$('#testdrop').droppable({
drop: handleDropEvent,
accept: '#testpile div'
});
function handleDropEvent(event, ui) {
var problemNumber = ui.draggable.data('number');
ui.draggable.draggable('disable');
ui.draggable.draggable('option', 'revert', false);
$("#testpile").children().hide();
$.ajax({
type: "POST",
url: 'include/responseget.php',
dataType: 'json',
data: {
userID: problemNumber
},
success: function(json) {
rTitle = json.rTitle;
rText = json.rText;
qTitle = json.qTitle;
qText = json.qText;
next = json.next;
numRows = json.numRows;
generateProblems();
}
});
}
}
});
PHP:
<?php include 'login.php';
if(isset($_POST['userID'])){
$id = $_POST['userID'];
$stmt = $conn->prepare("SELECT DISTINCT AnswerTitle, AnswerText, QuestionTitle, QuestionText, Next FROM question_answers
INNER JOIN question
ON question_answers.QuestionID=question.QuestionID
INNER JOIN answer
ON question_answers.AnswerID=answer.AnswerID
WHERE AnswerGroup = ?;");
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$rTitle_array[] = $row['AnswerTitle'];
$rText_array[] = $row['AnswerText'];
$qTitle = $row['QuestionTitle'];
$qText = $row['QuestionText'];
$next_array[] = $row['Next'];
$numRows = ($result->num_rows);
}
$response = array(
'rTitle' => $rTitle_array,
'rText' => $rText_array,
'qTitle' => $qTitle,
'qText' => $qText,
'next' => $next_array,
'numRows' => $numRows,
'id' => $id
);
echo json_encode($response);
}
// close connection
mysqli_close($conn);
?>
It sounds like you're trying to get this effect of adding one row every second. You could use recursion.
Also, setInterval is for numerous calls. setTimeout is for a single call.
function generateProblems(i)
{
// if we're at the end then stop
if(i == numRows) return;
// wait 1000
setTimeout(function()
{
// do what you want with i here
// call the next iteration
generateProblems(i + 1);
}, 1000);
}
// then you kick it off with the 0 index
generateProblems(0);
Or if you want the first iteration to kick off immediately:
function generateProblems()
{
// if we're at the end then stop
if(i == numRows) return;
// do what you want with i here
// move to next row
++i;
setTimeout(generateProblems, 1000);
}
// global var to keep track of where we are
i = 0;
generateProblems
I am sending a javascript array by using jquery to a php script.
In ajax I have a myarr variable but this variable can't be accessed in php.
Error is :
Undefined index myarr
Please Please help me. this is really important.
This is my jquery code:
for (var n = 0; n < arraySubId.length; n++) {
var ansArr = [];
for (var m = 1; m <= 11; m++) {
ansArr[m - 1] = $('#' + arraySubId[n] + '-' + m + '').val();
}
* $.ajax({
type: 'POST',
data: ({
'sub_id': arraySubId[n],
'myarr': ansArr
}),
url: 'Scripts/insert_feedback.php',
success: function(data) {
if (data == "1") {
} else {
alert(data);
}
}
}); *
}
When I access myarr variable in php, it's displaying:
Undefined index myarr.
Please Please help me.
And this is my php code:
<?php
session_start();
$prn = $_SESSION['username'];
$sub_id = $_POST['sub_id'];
$ans_arr = $_REQUEST['myarr'];
include 'dbclass.php';
$dbclass = new DBClass;
$mysqli = $dbclass->connect();
$query = "INSERT INTO ".$sub_id."(student_prn, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, date) values('$prn', '$ans_arr[0]','$ans_arr[1]','$ans_arr[2]',
'$ans_arr[3]','$ans_arr[4]','$ans_arr[5]','$ans_arr[6]',
'$ans_arr[7]','$ans_arr[8]','$ans_arr[9]','$ans_arr[10]', now())";
$msg = $dbclass->insert($query);
echo $msg;
?>
Try to convert your array to Json String and send it in JS, and in PHP decode it using json_decode()
my problem is following:
I am using this code to pass a value to a different file called "benutzerstart.php". Debugging through the jquery shows, that the value in "var beta" is correct.
I do get a problem with getting the value to a PHP variable.
The error code is : "Notice: Undefined index: param in C:\xampp\htdocs\KVP\benutzerstart.php on line 76"
Referring to the error code my suggestion is that the passed value is not really passed to the php file.
JQuery code:
<script>
$('#form').submit(function() {
var arrayFromPHP = <?php echo json_encode($Email) ?>;
var newMail = $.trim($('#Email').val())
var pw1 = $.trim($('#Password').val())
var mailVorhanden = false;
var pwRichtig = false;
var idVondemShit = -1;
var tempindex = -1;
for ( var i = 0; i < arrayFromPHP.length; i++ ) {
// $.each(arrayFromPHP, function (i, val) {
if(newMail === arrayFromPHP[i].Email ){
mailVorhanden = true;
tempindex = i;
break;
}
};
if (mailVorhanden === true)
{
if(pw1 === arrayFromPHP[tempindex].pw)
{
idVondemShit = arrayFromPHP[tempindex].idName;
pwRichtig = true;
if(arrayFromPHP[tempindex].mode === "1")
{
location.href='startseite.html';
pwRichtig = false;
}
}
else
{
alert('Passwort oder Nutzername falsch.');
}
}
else{
alert('Passwort oder Nutzername falsch.');
}
var beta = arrayFromPHP[tempindex].idName
$.ajax({
url: 'benutzerstart.php',
data: {'param' : 'beta'},
});
return pwRichtig
});
</script>
PHP code from "benutzerstart.php":
<?php
// Collect data
mysql_connect("localhost", "root" , "Floradix94");
mysql_select_db("hallo");
$tstID = $_GET['param'];
$sql= "SELECT erfassung.Verbesserungsvorschlag,erfassung.megusta,login.Email,erfassung.id,erfassung.Betre ff FROM (erfassung INNER JOIN login ON erfassung.loginid=login.loginid)";
$query=mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($query)) {
$modals[] = array(
'id' => 'modal' . $row['id'],
'href' => '#modal' . $row['id'],
'FormDoneId' => $row['id'] . 'FormDoneId',
'Email' =>$row['Email'],
'Verbesserungsvorschlag' => $row['Verbesserungsvorschlag'],
'megusta' => $row['megusta'],
'betreff' => $row['Betreff'],
);
}
?>
Anyone got an idea?
Change this
data: {'param' : 'beta'},
To
data: {param : 'beta'},