use one function array to other function without returning the array like javascript
this code l'm converted js to php in js same code working perfect but in php return error
Undefined variable: const
$const = array();
$array = array(1,2,3,4,5,6,7,8,9);
readdata();
for ($i = 0 ; $i < count($array) ; $i++) {
$const[5]=$i;
getall($array);
}
function dependent($array,$tances) {
echo $index5 = $const[5];
echo $index4 = $const[4];
$index3 = $const[3];
// $tances and $array for other purpose in this function
}
function getbid($array) {
$mid = 1.0;
dependent($array,$mid);
}
function getall($array) {
getbid($array);
}
function readdata() {
$latd=40;
$latm=11;
$lond=44;
$lonm=30;
$alt=0;
$tz=5;
$const[0]=$latd;
$const[1]=$latm;
$const[2]=$lond;
$const[3]=$lonm;
$const[4]=$tz;
}
i'm converted js library to php maximum js function use those array to declare in the previous function.so i want to use the same code in PHP as it is
this js i'm converted into php
in js all functions, arrays, and variables working perfect
var sconst= new Array();
var array= new Array(1,2);
readdata();
for (var i = 0 ; i < array.length ; i++) {
sconst[5]=i;
getall(array);
}
function dependent(array,mid) {
index5 = sconst[5];
index4 = sconst[4];
index3 = sconst[3];
alert(index5+' '+index4+' '+index3)
// $tances and $array for other purpose in this function
}
function getbid(array) {
var mid = 1.0;
dependent(array,mid);
}
function getall(array) {
getbid(array);
}
function readdata() {
var latd=40;
var latm=11;
var lond=44;
var lonm=30;
var alt=0;
var tz=5;
sconst[0]=latd;
sconst[1]=latm;
sconst[2]=lond;
sconst[3]=lonm;
sconst[4]=tz;
}
Your error is because $const doesn't exist in the scope of the dependent function. It also doesn't exist in the readdata function but you don't get an error there since you are not trying to read a value from it. You can resolve this most easily by adding global $const; to the dependent and readdata functions e.g.
function dependent($array,$tances) {
global $const;
echo $index5 = $const[5] . "\n";
echo $index4 = $const[4] . "\n";
$index3 = $const[3];
// $tances and $array for other purpose in this function
}
function readdata() {
global $const;
$latd=40;
$latm=11;
$lond=44;
$lonm=30;
$alt=0;
$tz=5;
$const[0]=$latd;
$const[1]=$latm;
$const[2]=$lond;
$const[3]=$lonm;
$const[4]=$tz;
}
Alternatively you need to modify your function calls to pass $const as a parameter (and return it as a value from readdata) i.e.
$const=array();
$array=array(1,2,3,4,5,6,7,8,9);
$const = readdata();
for ($i = 0 ; $i < count($array) ; $i++) {
$const[5]=$i;
getall($const, $array);
}
function dependent($const, $array, $tances) {
echo $index5 = $const[5] . "\n";
echo $index4 = $const[4] . "\n";
$index3 = $const[3];
// $tances and $array for other purpose in this function
}
function getbid($const, $array) {
$mid = 1.0;
dependent($const, $array, $mid);
}
function getall($const, $array) {
getbid($const, $array);
}
function readdata() {
$latd=40;
$latm=11;
$lond=44;
$lonm=30;
$alt=0;
$tz=5;
$const[0]=$latd;
$const[1]=$latm;
$const[2]=$lond;
$const[3]=$lonm;
$const[4]=$tz;
return $const;
}
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.
When i put
$link15 = $link15.$U;
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
this line of code in foreach/for loop the the script is stop after displaying one result. and when i remove this line of code it runs.
Below is the complete script:
for ($i = 0, $count = count($arr1); $i < $count; $i++) {
print $arr1[$i]."\r\n\r\n";
$_SESSION['arrayvalue'] = "$arr1[$i]";
$in = $arr1[$i];
$in = str_replace(' ','+',$in); // space is a +
$result15 = httpGet("https://www.google.com/cse?cx=003255331468891741234:xxxxxxxxxx&client=google-csbe&output=xml_no_dtd&q='.$in.'&oq='.$in.'");
//echo $result15;
//this is to get perticular tag/node value
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($result15);
$N = $dom->getElementsByTagName('U');
foreach ($N as $U) {
echo $U->nodeValue, PHP_EOL."<br/>";
$link15 = $link15.$U;
}
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
}
Where i am doing error in concatenation or any other error.
Thank You!
Based on your code, $U is an object, yet you're trying to concatenate it to $link15.
Try changing this:
$link15 = $link15.$U;
To this:
$link15 = $link15.$U->nodeValue;
You cannot concatenate an object with a string
try the below code (what I have changed is I am accessing the particular key named as "nodeValue" in your $U object. If you want to add another change it accordingly, you need to access the particular key or bunch of keys depending on your requirement)
for ($i = 0, $count = count($arr1); $i < $count; $i++)
{
print $arr1[$i]."\r\n\r\n";
$_SESSION['arrayvalue'] = "$arr1[$i]";
$in = $arr1[$i];
$in = str_replace(' ','+',$in); // space is a +
$result15 = httpGet("https://www.google.com/cse?cx=0032553314688917412345:xxxxxxxxx&client=google-csbe&output=xml_no_dtd&q='.$in.'&oq='.$in.'");
//echo $result15;
//this is to get perticular tag/node value
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($result15);
$N = $dom->getElementsByTagName('U');
foreach ($N as $U) {
echo $U->nodeValue, PHP_EOL."<br/>";
// here you need to access the particular key or bunch of keys depending on your requirement
$link15 = $link15.$U->nodeValue;
}
$newpdf1 = $newpdf1.$_SESSION['arrayvalue']."\r\n\r\n".$link15."\r\n\r\n";
$link15 = "";
}
Hope this helps.
I wanted to display a graph in javascript using data from php. My code is:
<?php $i = 20; ?>
while (data.length < totalPoints) {
array_js.push(<?php echo json_encode($array_php[++$i][1]);?>);
}
The problem is that even though $i is declared before the while loop, it gets back to 20 all the time, so the data pushed in array_js is always $array_php[21][1].
Edit: here is more code, (not same variable name...)
startConn(); //connect to database
$query = "SELECT * FROM Reading";
$data = getAllDatas($query);
?>
<script type="text/javascript">
$(function() {
var data = [], totalPoints = 300;
function getRandomData() {
<?php $i = 20; ?>
while (data.length < totalPoints) {
data.push(<?php echo json_encode($data[--$i][1]);?>);
//data.push(<?php echo ++$i;?>);
}
} // END getRandomData()
You have a misunderstanding on how server side and client side code work.
I think this may help you
$(function() {
var data = [], totalPoints = 3;
var i = <?php $i = 1;echo $i; ?>;
var j = parseInt(i);
var arr = <?php echo json_encode($data); ?>;
function getRandomData() {
while (data.length < totalPoints) {
data.push(arr[j][1]);
j++;
}
return data;
}
var data1 = getRandomData();
console.log(data1);
});
Try this one. You can pass the value of the php variable using echo while declaring another variable on the java script.
<?php $i = 20; ?>
var i = <?php echo $i;?>;
while (data.length < totalPoints) {
array_js.push(<?php echo json_encode($array_php[++i][1]);?>);
}
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
I'm trying to transfer php variables, that I have pulled out of a database, into three different javascript arrays. I use a php function to dynamically create a css dropdown menu, and then use a php loop to transfer the php variables into the javascript arrays. I then try to use a javascript function to initialize the attributes of the css menu. The same function is called from each of the links of the menu to update the menu based on the javascript arrays.
Here is the php function:
function createMenu()
{
//create the proper drop down menu, based on the total number of games played and the max number of games
$totalVods = count($this->VodID);
$menuArray = array();
for($i = 0; $i < $totalVods; ++$i)
{
if ($this->currentVodID != $i)
{
$menuArray[] = ($i+1);
}
}
if ( $totalVods < $this->MaxGames )
{
for ($i = $totalVods; $i < $this->MaxGames; ++$i)
{
$menuArray[] = ($this->currentVodID+1);
}
}
$totalGames = count($menuArray);
printf("<p>$this->Name</p>");
printf("<div id='cssmenu2'>");
printf('<ul>');
if ($menuArray)
{
printf('<li id="vod1" class="has-sub last"><span></span><img class="arrow" src="/images/Arrow.png">');
printf('<ul>');
if ($totalGames > 1)
{
for ($j = 0; $j < ($totalGames - 1); ++$j)
{
$vodNum = 'vod'. ($j+2);
printf("<li id='$vodNum' onclick=''><span></span></li>");
}
}
$vodNum = 'vod'. ($totalGames + 1);
printf("<li id='$vodNum' class='last' onclick=''><span></span></li>");
printf('</ul>');
}
else
{
printf('<li id="vod1"><span>Game 1</span>');
}
printf('</li>');
printf('</ul>');
printf('</div>');
//---------------------------------------------------
// function works fine up till here
// ------------------------------------------------
printf('<script>');
printf('alert("Right after totalGames");'); /* If I take this part out, up till the next comment, the rest works, but none of this part, even the alerts, works */
for($i = 0; $i < $totalVods; ++$i)
{
printf("vodName[$i] = 'Game ". ($i + 1) ."';");
printf("alert('vodName[$i]= '+vodName[$i]);");
$this->VodObject->selectVod($this->VodID[$i]);
$address = $this->VodObject->returnVod();
printf("vodAddress[$i] = '$address';");
$date = $this->VodObject->returnDate();
printf("vodDate[$i] = '$date';");
}
if ($totalVods < $this->MaxGames )
{
for ($i = $totalVods; $i < $this->MaxGames; ++$i)
{
printf("vodName[$i] = 'Game ". ($i + 1) ."';");
$gameNum = $i +1;
$address = "<div class='matchNoVOD'>There is no Game $gameNum<br />Series ended before this game.</div>";
printf("vodAddress[$i] = '$address';");
printf("vodDate[$i] = '';");
}
}/* End of the section that is having problems- if I take this out, the rest of the alerts work */
printf('alert("Right before window.onload");');
printf('window.onload = function() { switchVod(0); };');
printf('</script>');
}
In the javascript part of the above function, I access a php class called vodObject- that just accesses the database and returns the strings I want to place in the javascript array.
The javascript function that updates the css menu is placed in the part of the html, and looks like this:
<script>
var vodName = Array();
var vodAddress = Array();
var vodDate = Array();
function createfunc(i)
{
return i;
}
function switchVod(vodID)
{
alert("switchVod ran");
alert('vodID= ' + vodID);
var x=document.getElementById("vod1");
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[vodID];
for (var i=0; i < vodName.length; i++)
{
if ( i != vodID)
{
var id = createfunc(i);
var gameNum = i + 2;
var gameID = "vod" + gameNum;
var x = document.getElementByID(gameID);
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[i]
x.onclick = function() { switchVod(id); }
}
}
alert("after for loop");
alert("1");
document.getElementById('vodObj').innerHTML = vodAddress[vodID];
alert("2");
document.getElementById("vodDate").innerHTML = vodDate[vodID];
alert("finished");
}
</script>
The createfunc(i) is meant to get around the closure issues I heard about.
Any ideas about what I can try to fix my code? Thank you for your help, in advance!
In the JS code, you can just use var city = '<?=$city;?>';, for example.
If I got you right, you can make it using AJAX. The PHP file while print this:
echo json_encode($your_php_array);
Then, using JQuery $.getJSON method
$.getJSON('json.php', function(response) {
/* do your stuff here */
console.log(response); // This var has the json object
});
Let me know if it's useful.