How to bring PHP array value to Javascript? - javascript

<html>
<head>
<script language="javascript">
function validatefrm(){
for (var i= 0 ; i< 3 ; i++){
window.alert(i+window.document.contact[i].value);
}
return false; //to prevent form from submitting for debugging
}
</script>
</head>
<body>
<form name="editform" onsubmit="return validatefrm();" method="POST">
<?php
for($i=0; $i<3; $i++){
print "<input type='textbox' id='contact".$i."' value='".$i."'>";
}
?>
<input type="submit" value="Submit Values">
</form>
</body>
</html>
Hi, I'm new to php and javascript.
I'm trying to call the form with the value of 0,1,2 with javascript but it wont work. Unless i delete the for loop in javascript function and hard code it as Window.alert (window.document.contact0.value) and so on....Anyone can help? Must appreciate.

If I get your question correctly, you need to access the elements by ID. And the correct way is to use document.getElementById(...). In your case:
for (var i= 0 ; i< 3 ; i++){
window.alert(document.getElementById('contact' +i).value);
}

You are setting an ID for each element with php contact0, contact1 etc.
So in javascript look for that ID
function validatefrm(){
for (var i= 0 ; i< 3 ; i++){
window.alert(i+ ' '+ document.getElementById('contact'+i).value);
}
return false; //to prevent form from submitting for debugging
}

Your best choice would most likely be to use json_encode. This method outputs the array as a JSON array which can be assigned to a JavaScript variable in <script> tags. Associative arrays on the PHP side would get converted into JSON objects.
json_encode in the PHP documentation
<?php
$myArr = array(0, 1, 2);
?>
<!-- somewhere in the HTML document -->
<script>
var myArr = <?php echo json_encode($myArr); ?>;
// do something with myArr
console.log(myArr);
</script>

The php is executed on the server side, before it makes it to the browser. The javascript is executed on the client side, in the browser. You cannot pass php values to javascript like this.
You can make the php output javascript (in a script tag), and use that in your javascript code though.
<script>
var foo = [];
<?php
for($i=0; $i<3; $i++){
print "foo[".$i."] = ".$i;
}
?>
console.log(foo[0] + ", " + foo[1] + ", " + foo[2]);
<script>

Related

$.getJSON Use data argument to modify text on HTML element

I am having a bit of trouble with this bit of code. I am to take the values of 4 inputs, pass them to a PHP API using jQuery, compute a password with the PHP API file I have created and return that password as the data argument as a json_encoded. Below you will find the code:
PHPPasswordGenerator.php
<?php
header("Content-Type: application/json; charset: UTF-8;");
$letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$special = array('!','?',"'",'"','£','$','%','&','/','(',')','=','#','#','§','[',']','{','}');
$minLetters = array();
$maxLetters = array();
$numbers = array();
$specialCharacters = array();
$final = '';
$min = $_REQUEST["typeA"];
$max = $_REQUEST["typeB"];
$num = $_REQUEST["typeC"];
$spec = $_REQUEST["typeD"];
if(isset($min) or isset($max) or isset($num) or isset($special)){
for($i = 0; $i < $min; $i++){
array_push($minLetters, $letters[rand(0,count($letters)-1)]);
}
for($i = 0; $i < $max; $i++){
array_push($maxLetters, strtoupper($letters[rand(0,count($letters)-1)]));
}
for($i = 0; $i < $num; $i++){
array_push($numbers, rand(0,9));
}
for($i = 0; $i < $spec; $i++){
array_push($specialCharacters, $special[rand(0,count($special)-1)]);
}
$final .= implode('',$minLetters) . implode('',$maxLetters) . implode('',$numbers) . implode('',$specialCharacters);
}
print(json_encode($final));
?>
jQuery Code
$(document).ready(function(){
//Chiamata AJAX sui dati generati dal generatore di Password in PHP
$("#generator").on("click", function(){
//Mentre il focus è sull'input, modifica il valore val()
$.getJSON("passwordgenerator.php",
{
typeA : $("#typeA").val(),
typeB : $("#typeB").val(),
typeC : $("#typeC").val(),
typeD : $("#typeD").val()
},
function(data){
console.log("Success: " + data);
$("#generated").append("<h3></h3>").html(data);
}).fail(function(err){console.log(err)});
});
});
This is part of the body
<form>
<label for="A">Lettere Minuscole</label><input type="text" name="typeA" id="typeA">
<label for="B">Lettere Maiuscole</label><input type="text" name="typeB" id="typeB">
<label for="C">Numeri</label><input type="text" name="typeC" id="typeC">
<label for="D">Caratteri Speciali</label><input type="text" name="typeD" id="typeD">
<button id="generator">Generate Password</button>
</form>
<div id="generated"></div>
Now, the thing is: whenever I put a number inside the inputs and send it to the PHP file, the $final variable is json_encoded and sent back to the javascript file. If I do something like console.log(data), I actually get to see a randomly generated password with the specs I wanted it to be, but then I try to do something like:
$("#generated").text(data);
but the data doesn't go inside generated. I also tried to use html(data), but to no use. I did a console.log(typeof data); to see that it really was a string, as I wanted, and it actually is.
JSON.stringify(jsondata) to convert JSON into string. If you want to parse data string to JSON than use JSON.parse(string). I didn't get what is your actual question
So, the thing is I had to use val() and $.getJSON() at all costs, because the professor wanted so! The problem: I was using a form. The data passed as expected, but when I tried to append the data to an HTML element, since this event would occur in the same time the default form event would occur, the data would not get appended.
Removing the element was all it took. I could have also prevented default, yes.
Thank everyone for the nice help! :)

Echoed Javascript Code from PHP Via AJAX Not Running

My code is meant to get the author of an inputted book using the Google Books API via AJAX. If nothing is inputted it prints "Empty". What it actually does is print out the Javascript code when a book is inputted. When nothing is inputted, it prints "Empty" as it should. How could I modify my code to make the echoed Javascript execute and hence get the author of an inputted book?
Just to see, I replaced the echo part with echo "<script>document.getElementById('txtBox').innerHTML = 'Hello';</script>";. It also prints out the javascript code, so I don't think it has something to do with using the API.
getAuthor.html
<!DOCTYPE html>
<html>
<body>
<!-- Input -->
<div class="form">
<form onsubmit="makeRequest(); return false">
<input type="text" id="inputText" name="inputText">
<input type="submit">
</form>
</div>
<br>
<!-- Output -->
<div class="txtBox">
<textarea id="txtBox">
</textarea>
</div>
<!-- AJAX to create output using jEcho.php file-->
<script>
function makeRequest() {
httpRequest = new XMLHttpRequest();
console.log(httpRequest.responseText);
httpRequest.onreadystatechange = function() {
document.getElementById("txtBox").innerHTML = httpRequest.responseText;
};
httpRequest.open("POST", "jEcho.php", true);
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpRequest.send("inputText=" + document.getElementById("inputText").value);
}
</script>
</body>
</html>
jEcho.php
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>
<script src='$scriptSource'></script>";
}
?>
Links
Echoing Javascript From PHP:
How to call a JavaScript function from PHP?
Echoing javascript from PHP
Google Books API:
https://developers.google.com/books/docs/v1/getting_started
https://developers.google.com/books/docs/v1/using
<script> elements are only run when your page is first loaded. Script elements created later on, either by assigning to an element's .innerHTML, creating them using document.createElement(), or otherwise, are not executed.
If you want to have a PHP script send back code to be evaluated, you'll have to do that directly, e.g:
httpRequest.onreadystatechange = function() {
eval(httpRequest.responseText);
};
(And remove the <script> tags from the response.)
Try setting header in jEcho.php file (not tested)
header('Content-Type: application/javascript');
I'm not allowed to comment so:
I'm not certain what has caused it for but could <script src='$scriptSource'></script>"; be called before the handleResponse function. I'm not too sure what is causing it, at the moment, that is my best idea.
Also could you not just have the url already in the code like this: (jEcho.php)
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
//$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "
<script src='https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse'></script>
<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>";
}
?>

Passing php database result to javascript array

I have to create a dropdown list and a button that will add another dropdownlist once click. i used this javascript code:
var array = ["Volvo","Saab","Mercades","Audi"];
var cell2 = row.insertCell(1);
var element2 = document.createElement("select");
element2.name="activity_dropdown"
element2.id="activity_dropdown"
cell2.appendChild(element2);
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", array[i]);
option.text = array[i];
element2.appendChild(option);
}
but i want that my var array will come from the database result query. what can i do to pass php array to javascript array?
by the way.. i have tried to used json_encode but it seems not working.. here is the my code:
for data.php
<?php
include('connection/dbConn.php');
// get data and store in a json array
$activity=$conn->query("SELECT activity_name FROM rehab_activities");
while ($row =mysqli_fetch_array($activity)) {
$activities[] = array(
'actvityName' => $row['activity_name']
);
}
echo json_encode($activities);
?>
and try it here, but nothing comes out:
<script>
jQuery(document).ready(function(){
jQuery("#add").click(function(){
var res = new Array();
jQuery.getJSON("data.php", function(data) {
var i= 0;
while(i<data.myarray.length){
res[i]=data.myarray[i];
i++;
}
jQuery("#result").html(res[0]);
});
});
});
</script>
<body>
<input type="button" id="add">
<div id="result"></div>
</body>
</html>
Make php write that part of your script while it loops through your query. Like so:
var array = [
<?php
$query = mysql_query("SELECT * FROM cars");
while ($car = mysql_fetch_assoc($query)) {
$car_name = $car["name"];
echo "'$car_name',";
}
?>
];
For this to work, your file must be a php file and not a javascript file, since inside a php file you can also write html and therefore, javascript.
I personally solve this by making a file called db-to-js.php that only contains javascript arrays created by php. Whenever the database is modified, one or more of these javascript arrays are also modified since they are created every time this file is executed.
Lastly, you have to include the file where you need it as a script:
<script type="text/javascript" src="db-to-js.php"></script>
I hope this helps.
I had a similar problem in vue js, renamed my 'app.js' file to 'app.php', where i added all my php functions and changed the reference script tag to
<script> type='text/javascript' src='app.php' </script>
Worked For me!

Sending PHP array to Javascript

I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.
$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
$ValidatinArray[$J] = $RowVal['Validation_Type'];
$J++;
}
And This is my javascript code.
$(document).ready(function() {
$("form").submit(function(){
var P= <?php echo json_encode($ValidatinArray); ?>;
var O = P.length;
alert(O);
return false;
});
});
But this gives me an error like this
SyntaxError: syntax error
var P= <br />
Isn't it possible to get the array in this way. Please someone help me.
UPDATE: This is the final out put of my error message
<script>
$(document).ready(function() {
$("form").submit(function(){
alert('AAAAAAAAAAAAAAAAAAA');
var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
var Data = document.getElementsByName("DataInputValue[]");
var A = IDsOfTheColumns.length;
alert(A);
<br />
<b>Notice</b>: Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
var P = null; return false;
});
});
</script>
Sorry for the late response...Try rewriting your document.ready as:
$(document).ready(function() {
$("form").submit(function(){
var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
var O = P.length;
alert(O);
return false;
});
});
The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:
http://www.php.net/manual/en/language.variables.scope.php
Try this:
<?php
echo ' <script>
$(document).ready(function() {
$("form").submit(function(){
var P= '. json_encode($ValidatinArray) . ';
var O=P.length;
alert(O);
return false;
});
});
</script>';
?>
What you do is simply echo the js using php.
Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));
Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.
Hope this helps
first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".
the error you show indicates that from the beginning the variable that contains the array does not exist.
if the SQL query is inside a php function check that you are returning the variable.
example
<?php
function GetData(){
// ... here is the code to get the information from the database ...
return $ValidatinArray;
}
$ValidatinArray = GetData();
?>
once you have validated that this array exists we can now see the problem of passing the data to JavaScript:
It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:
// ... php file code
?>
<script>
$(document).ready(function() {
$("form").submit(function(){
// you can use any of the two methods that I leave you here
// Using only json_enconde
var P= <?= json_encode($ValidatinArray) ?>;
// Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');
var O = P.length;
alert(O);
return false;
});
});
</script>
In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:
You can generate a "global" JavaScript variable from the php code as follows
// ... code php file
?>
<script>
window.variablename = <?= json_encode($ValidatinArray) ?>
</script>
<?php
inside your JS file you can receive the array like this
$(document).ready(function() {
$("form").submit(function(){
var P= window.variablename ;
var O = P.length;
alert(O);
return false;
});
});
PD: using <?= is equivalent to using echo
In php json_encode the array like this:
$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";
and in javascript:
$(document).ready(function() {
$("form").submit(function(){
<?php echo $inlinejs; ?>
console.log(validatinArray);
});
});

How to pass data from a form to a php function to javascript to draw on a canvas without refreshing the page?

I am looking to create a basic graphic calculator using only html, php, and javascript. The code below refreshes the page so the javascript never gets a chance to draw the graph. The way this is supposed to work is that the php grabs the data from the form and outputs the results of the equation point by point into an array. The array is passed to the javascript which uses the index of the array for the x value and the value at that index for the y value. I tried having the form target a separate iframe but the graph still isn't drawing and I am not sure why. I heard there is a way to do this with AJAX but the current challenge is to do this with just html,css if needed, javascript, and php.
<?php
if( isset($_POST['submit']) )
{
$val1 = htmlentities($_POST['val1']);
$val2 = htmlentities($_POST['val2']);
$val3 = htmlentities($_POST['val3']);
$results;
for($i = 0; $i < 530; $i++)
{
$results[i] = pow($i,$val1) + $i*$val2 + $val3;
if($results[i] >= 530)
break;
}
}
?>
<form action="example4.php" method="POST">
x^:
<input type="text" name="val1" id="val1"></input>
+x*:
<input type="text" name="val2" id="val2"></input>
+1*:
<input type="text" name="val3" id="val3"></input>
<input type="submit" value="send"></input>
</form>
<canvas id="c" height="530" width="530" style="border:1px solid #d3d3d3;"></canvas>
<script type="text/javascript">
var b = document.body;
var c = document.getElementsByTagName('canvas')[0];
var a = c.getContext('2d');
var data = <?php echo json_encode($results); ?>;
a.beginPath();
a.moveTo(0,530);
a.strokeStyle="black";
for(var i=0; i < data.length-1; i++))
{
a.moveTo(i,data[i]);
a.lineTo(i+1,data[i+1]);
a.stroke();
}
</script>
I think the problem is you are setting data equal to the JSON string not to an array object.
Can you change the line that reads:
var data = <?php echo json_encode($results); ?>;
To the following:
var data = JSON.parse("<?php echo json_encode($results); ?>");
EDIT: I reread your question and see you want the php variables at the top of the page to be set by the user through the form on the page. The problem with how you are surrently thinking about it is that PHP is run on the server and HTML/Javascript is rendered and run on the user's browser. So all of the php has already executed before the user sees the form.
You can run php from an HTML page though by using AJAX. So you will AJAXing to a php file that performs the computations and builds the array and ultimately echo's the JSON of the array. The JavaScript will then handle the result like I talked about in my original answer above.
For an AJAX tutorial that deals with the components you will need: http://www.simpletutorials.com/?path=tutorials/javascript/simple_ajax

Categories