Javascript variables to php - javascript

I am working with javascript and php, and I am trying to pass javascript variables from an html file to an php file. I already try a lot of ways using window.location.href and $_GET and $_POST. I dont know what I am doing wrong, or if his something missing, any suggestions to how pass javascript variables to php?
html file:
<script type="text/javascript" src="zepto.min.js"></script>
<script type="text/javascript">
function values() {
var wind = 300;
var rain = 0;
var speed = 35;
window.location.href = "getData.php?s1=" + wind + "&s2=" + rain + "&s3=" + speed;
}
</script>
php file:
<?php
$sensors=new Sensor();
if (isset($_GET['s1']) && isset($_GET['s2']) && isset($_GET['s3'])) {
$wind = $_GET['s1'];
$rain = $_GET['s2'];
$speed = $_GET['s3'];
$sensors->create();
}
?>

Your (JS) code isn't working because you never called the values() function.
<script type="text/javascript">
function values() {
var wind = 300;
var rain = 0;
var speed = 35;
window.location.href = "getData.php?s1=" + wind + "&s2=" + rain + "&s3=" + speed;
}
values(); // Add this to fire up the function
</script>
This assuming that the rest of your code checks out for the class you're using.
You will also have to echo out those values in your PHP:
echo $wind = $_GET['s1'];
echo $rain = $_GET['s2'];
echo $speed = $_GET['s3'];

Related

JQuery fails to load when i use a php variable

I'm incorporating PHP code into JQuery like this:
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
/* This is the line */var c = $c;
$('#data').load('data.php?v=' + count + '&c=' + c)
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
})</script>";
The PHP variable shows as blue, there are no errors showing, but when I run it it refuses to work. I've tested everything else and I'm 100% sure PHP is the one causing the problem.
How can I fix this?
If $c is your php variable you will need to quote and join it inside an echo tag.
But as Carton (+1) said, is it a string, integer, object?
If it's an integer, this should work...
<?php
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
var c = " . $c . ";
$('#data').load('data.php')
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
});
</script>";
If it's a string this should work...
<?php
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
var c = '" . $c . "';
$('#data').load('data.php')
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
});
</script>";
If it's an object, you will have to parse the var or encode it.
Sometimes if you want to echo or return big blocks of html inside php, you can use an output buffer to capture the html, and then you can either return the html via a function, or echo it. This just makes your html easier to read when it's not wrapped inside echo quotes tags.
<?php
// c sting php var
$c = 'string';
// start output buffer
ob_start();
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
let count = ($('.data').length + 25);
let c = '<?=$c?>';
$('#data').load('data.php');
$(this).on('click', '.btn-data', function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c);
});
});
</script>
<?php
// store everything between ob_start() and here into a php variable
$script = ob_get_clean();
// return script html
return $script;
// or echo script html
echo $script;
// not both together obviously
?>

Using PHP to populate Javascript Variables

I'm trying to populate a Drop-Down menu from a csv file located on a network share.
I've come as far to get the file to create all the options successfully when the file is in the wwwroot folder however, now I'm faced with the external url reference issue.
Ajax does not support local File:/// directories and when attempting to use the network share location it also fails: \\Server\Folder\File.csv
Is there any way to read the data from the csv file using php or other server-side language in order to perform my work on the data?
Code Below for your reference:
<script>
function SubmitBy(){
$.ajax({
url: encodeURI('./PrinterLookup.csv'),
success: function(data) {
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Looking for something like this,,, to bypass the ajax url limitation:
<script>
function SubmitBy(){
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = $Data;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Any assistance on this will be greatly appreciated.
Thank you in advance.
in this line var data = $Data; you need to print $Data see below
<script>
function SubmitBy(){
<?php
$Datapath = "file:///Server/Folder/Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = <?php echo $Data; ?> //correction here
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Please check first this is .php file .
If this is .php file.
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
<script>
function SubmitBy(){
var data = <?php print_r( $data ); ?>;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>

Call PHP function inside JavaScript inside echo

I have read the other similar questions, but not found the answer, so here it is:
<?php
function load($page) {
echo "page: ".$page;
}
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '<?php load(page); ?>'
}
})
</script>
";
?>
The problem is that <?php load(page); ?> is not executed. If I write load(page); outside the echo, it works. Can anyone help me ?
Change the function to return:
function load($page) {
return "page: ".$page;
}
You're executing PHP with the echo so just use the return of load():
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '" . load($page) . "'
}
})
</script>
";

php javascript echo javascript variable to php loop condition dynamically using onclick or how can I use ajax to solve it?

How can I store only the value of f() into $ab?
How can I also change $ab dynamically in the loop condition when the button is pressed so that the integers are printed out dynamically?
<script type="text/javascript">
var i = 0;
function f(){
i = i + 10;
document.getElementById("more").innerHTML= i;
}
</script>
php
$ab = "<p id='more'> </p>";
echo $ab;
for($x=0;$x<$ab;$x++) echo $x . "<br>";
echo "<button type='button' onclick='f()'> > </button>";
Try this,
Hope this work for you.
<script type="text/javascript">
var i = 10;
function f(){
i = i + 10;
var html = "";
for(var j=0;j<i;j++){
html += j+"<br/>";
}
document.getElementById("more").innerHTML= html;
}
</script>
You need to send the variable $x to your function f
echo "<button type='button' onclick='f($x)'> > </button>";
Then in the function you can count how many times the buttons all together are clicked, i++:
var i = 0;
function f(x) {
x += i * 10;
i++;
document.getElementById("more").innerHTML= i;
}

autoincrement id in javascript variable

didn't really succes with assigning values to new ids in my while(row) statement:
Here is an easy example, hope you understand what I want to do. Thanks
<?php...
$id=0;
while(rows = mysql_fetch_data){
$id = $id + 1;
$teamname = rows['team'];
?>
<script>
var team = '<?php echo $teamname; ?>';
var id = 'id_<?php echo $id; ?>';
//Here I want to save the teamnames as javascript variable "id_1", "id_2" etc, which I can use outside the while statement.
//For each row id = id_1, id_2, id_3, id_4.
//I want to make id_1 a variable which outputs teamname
//So that
//var id_1 = team; //team 1
//var id_2 = team; //team 2
<?php
}
?>
var id_1;
var id_2;
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>
I would recommend using an array rather than individual variables, as you have a list of team names:
<?php
$teamnames = [];
while(rows = mysql_fetch_data){
$teamnames[] = rows['team'];
}
?>
<script>
var teamnames = <?php echo json_encode($teamnames); ?>;
</script>
Then you end up with a client-side JavaScript array of team names. While you could then output them with document.write, there's probably a better option.
But here's your document.write updated to use the array:
var n;
for (n = 0; n < teamnames.length; ++n)
{
// Note: There's almost certainly a better choice than `document.write`
document.write("Teamname " + (n + 1) + " = " + teamnames[n] + "</br>");
}
Replace your code with the following and it should give you the output that you're after...
<script>
<?php
//...
$id_counter = 1; //Initialise counter
while($row = mysql_fetch_assoc()){
echo 'var id_'.$id_counter.' = "'.$rows['team'].'";'; //Echo row in the format: var id_X = "team_name";
$id_counter++; //Increment the counter
}
?>
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>

Categories

Resources