Insert values generated by PHP in a Javascript array [duplicate] - php

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I'm trying to make a list where the user can select 5 items. Those items are generated through PHP. When the user clicks on 1 item that item needs to be saved in an Javascript array. Once the user selected 5 items, those needs to be saved into an mysql database.
Atm I can select items, but the array remains empty.
My code:
<script type="text/javascript">
var genrearray = new Array(4);
var i=1;
$(document).ready(function kleurveranderen() {
$(".keuzeDiv").on("click", function kleurveranderen() {
if(i<=5){
$(this).toggleClass("green");
genrearray[i] = document.getElementById("$Keuzescherm['Genrenaam']").innerHTML;
i++;
}
else{
alert("Teveel genres geselecteerd.");
}
})
});</script>
this is standing between script tags but for some reason he isnt showing them.
my php code:
<?php while($Keuzescherm= $allGenres->fetch_assoc())
{
echo "<div class='keuzeDiv' id='".$Keuzescherm['Genrenaam'] ."'>"
. $Keuzescherm['Genrenaam']."</div>";
}?>
the id of the div is the same as the value.
my css code to indicate that the div is selected
.keuzeDiv{
background-color:#dddddd;
padding-top:5%;
color: black;
padding-bottom: 10px;
}
.green{
background-color:#8eb461;
color:white;}
So my question is: How can I fill the array with the php values and save that array to a MySql database?

I think what you should be doing is:
genrearray[i] = $(this).text();
You can't reference PHP variables in Javascript. And the variable you were trying to reference is from the while loop, so its value outside the loop is not very useful.

Related

In Angular4, Array from .subscribe is empty in component.ts [duplicate]

This question already has answers here:
How to return object from service to component in angular
(3 answers)
Closed 3 years ago.
I am fetching data from PHP API, But the variable after subscribe is empty in component.ts but, while using in component.html it displays data. I want to modify after fetching from API.
In service.ts:
get_tournaments(){
return this.http.get("http://localhost/Website/api/tournament/read.php")
.map(res=>res.json());
}
In component.ts:
tournaments:Object[] = [];
ngOnInit() {
this.ongoing_ser.get_tournaments()
.subscribe(value=>this.tournaments=value);
console.log("Main:",this.tournaments); <-- this is empty
}
In component.html:
it displays everything correct as required.
I want to modify the data fetched from API and then display in html
#Sudhindra Purohit
Javascript is synchronous so it will to wait to complete subscribe your request. So that It will return empty in console.
If you want to modify your data then you can do like below
this.ongoing_ser.get_tournaments()
.subscribe(value=> { this.tournaments=value;
// DO here what ever you want with tournaments
this.tournaments = this.tournaments.map(tour => {
console.log(tour);
}
});
You need to assign the value to the component variable and then alter it or display it using interpolation {{}}
In the componenet.ts
ngOnInit() {
this.ongoing_ser.get_tournaments()
.subscribe(
(data:any)=>{
this.data=data;
//you can do the data modification here
})
}
In component.html
<div>{{data}}</div>
This will display the data in HTML

How can I insert php while code into javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 3 years ago.
Hello there im learning php also javascript but i dont know how to put a while loop into javascript parameters area.
<script type="text/javascript" src="//....." async="true"></script>
<script type="text/javascript">
window.criteo_q = window.criteo_q || [];
var deviceType = /iPad/.test(navigator.userAgent) ? "t" : /Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Silk/.test(navigator.userAgent) ? "m" : "d";
window.criteo_q.push(
{ event: "setAccount", account: 62056}, // You should never update this line
{ event: "setEmail", email: "##Email Address of user##" }, // Can be an empty string
{ event: "setSiteType", type: deviceType},
{ event: "viewItem", item: "##HERE##" });
</script>
And the goal is output of "##HERE##" needs to be done php while loop from database. (I can give detailed description if asked)
If the file is .php exentension, you could have a <?php echo "JAVASCRIPT CODE" ?> with that you can could an output javascript inputing variables into it, by using concatenating. It is not a good pratice, but would soulve your problem.

how to post counter value from javascript to database [duplicate]

This question already exists:
how to post value of 3 input fields into database
Closed 9 years ago.
i have a java script function i want to post value of counter to my data base... how to do...this is a function to create 2 texbox and 1 select box on click... but whn i am applying another input tag to get and post counter value another input text box is getting reated... i dont want this i just want to post total value to counter whn submitt buttion is clicked
<script>
var counter=1;
function generateRow() {
var count="<font color='red'>"+counter+"</font>";
var temp ="<p> <div class='_25'><input type='textbox' id='textbox' name='stop"+counter+"' placeholder='Stop Name'></input></div> <div class='_25'><input type='textbox' id='textbox' name='timing"+counter+"' placeholder='Timing'></input></div> <div class='_25'><select id='ampm"+counter+"' name='ampm"+counter+"'><option>a.m</option><option>p.m</option></select> </div>";
var newdiv = document.createElement('div');
newdiv.innerHTML = temp + count;
var yourDiv = document.getElementById('div');
yourDiv.appendChild(newdiv);
counter++;
}
</script>
The absolute most basic way I can think of is:
Add an iframe somewhere in your page:
<iframe id="iframe"></iframe>
Create a php file counter.php
<?php
$counter = (int) $_GET['counter'];
$query = mysql_query('INSERT INTO table (counter) VALUES (' . $counter . ')');
// OR YOUR OWN QUERY TO DO THIS
?>
And add to your function the following javascript code:
document.getElementById('iframe').src = 'counter.php?counter=' + counter;
Obviously you can do it more complicated via ajax and read the json response etc but at its most basic level, this will suit you. Basically the trick is, you set the iframe source to the counter.php and pass the counter in a get parameter. When an iframe source is changed, it automatically loads, hence the server will then recieve the counter parameter and process it.
You can add display:none to the iframe to hide it visually.
Given the tags on the question:
Make an HTTP request (possibly using XMLHttpRequest) to a PHP handled URL that reads the data (likely from $_POST) and uses the PDO API to make an SQL query using that data.

Populating a <select> then changing another <select> based off the original [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Populating drop-down based on previous selection
Okay here's basically what I'm attempting to do. The first statement is populated by a query of a table on the server. The Second has 3 values: Elite, Core, Raider. Using AJAX and PHP I'm trying to make it so when someone selects a name from the first the second one always changes to the value that is in the database for that person; however this must remain a select in case an unoted switch happens(in which case the value of the second must be changed).
<?php
echo "<select name='playername' onchange='filldata(this.value)'>";
require("/home/a9299818/public_html/DKPTools/connect.php");
$query1 = mysql_query("SELECT player.id, player.primarytoon, player.rank, IFNULL( SUM(dkp.dkp ) , 0 )
FROM player
LEFT OUTER JOIN dkp ON player.id = dkp.player_id
GROUP BY player.id
ORDER BY player.id");
while ($row = mysql_fetch_array($query1, MYSQL_NUM)){printf("<option value='%s'>%s</option>",$row[0],$row[1]);}
echo "</select>";
echo "<select name='rank'><option value='1'>Elite</option><option value='2'>Core</option><option value='3'>Raider</option>";
?>
This PHP works and populates both selects correctly; however I'm totally lost in coding the AJAX which should change rank.value to whatever the database says it is WITHOUT REFRESHING THE PAGE.
There are 2 possibilities.
The first is to work with jQuery and Ajax.
function filldata(value) {
$.ajax({
type: "GET",
url: "URL_TO_PHP_FILE",
data: "playerID=" + value,
success: function(result) {
$("select[name=rank]").val(result);
}
});
}
URL_TO_PHP_FILE is the url to the PHP file in which you retrieve the rank_id from your database for the player with the given playerID.
In the PHP file you should only echo the rank_id.
So the PHP file would look like this:
<?php ## THE PHP FILE ##
require("/home/a9299818/public_html/DKPTools/connect.php");
$query1 = mysql_query("SELECT player.rank WHERE player.id = ".$_GET['playerID']);
$row = mysql_fetch_array($query1, MYSQL_NUM);
echo $row['rank'];
## END OF PHP FILE ## ?>
The seconds possibility is to make sure the option value of your first select is not equal to the "player_id", but to the "rank_id". So you can write a javascript function..
function filldata(value) {
$("select[name=rank]").val(value);
}

Changing content when reload [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
random images display
Have anyone see an image or other content that changing randomly when we reloading the page?
What is that? Can you tell me how to do that?
Guess, something like this would do the trick.
/* div for your future image */
<div id="img"></div>
<script>
window.onload = function(){
/* array of urls to your images and random integer number between 0 and array's length-1 */
var imgurls = [url1,url2,url3,...,urlN],
randn = Math.floor(Math.random()*imgurls.length);
/* create an HTML tag <img src="urlN"> in your div */
document.getElementById('img').innerHTML = '<img src=' + imgurls[randn] + '>';
}
</script>

Categories