PHP Variable inside PHP -> Echo -> Javascript - javascript

so I have issue I don't even know how to tell it. But here it is.
//Coupon Code?
if($row['coupon'] == null or $row['2email'] == 'Confirmed')
{
echo '<td>
<input type="text" onKeyup="trackChange(this.value)" id="myInput">
<script type="text/javascript">
var dID = <?php echo $dID; ?>;
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function trackChange(value)
{
window.open("/functions.php?cCODE="+value+"&ccID="+dID)
}
</script>
</td>';
All I need is to get "user ID" from $dID=$row['ID']; but as it seems It just echo out that to the result and don't do any job. How can I get php variable inside php -> inside Echo -> inside Javascript.
I thought by going other way but I need text box and then submit to url. But I can't seem to get it working. Only 1 request at a time and I need 2. (User ID, and text to text box response)
echo " <td><form action= functions.php?cID= method= 'post'><input
type='hidden' name='cID' value=$dID />
<input type= 'submit' name= 'type' value= Confirm></form></td>";
So I can't get them both to submit that. Only found a way inside javascript.
Picture of text field

You'll want to use string concatenation (using the . character) to insert a variable into your string. Like this:
echo '
[...]
<script type="text/javascript">
var dID = ' . $dID . ';
function wait(ms){
[...]
';
A . will concatenate two strings together. For example:
echo 'hello ' . ' world'
You can also insert a variable directly into a string, if you use double quotes. Single quotes do not allow you to do this:
$text = "world";
echo "hello $text";
In general, you should wrap your variables in curly brackets ({ and })
$text = "world";
echo "hello {$text}";

You can just concatenate the variable there
To concatenate use .
if($row['coupon'] == null or $row['2email'] == 'Confirmed')
{
echo "<td>
<input type='text' onKeyup='trackChange(this.value)' id='myInput'>
<script type='text/javascript'>
var dID = '".$dID."'
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function trackChange(value)
{
window.open('/functions.php?cCODE='+value+'&ccID='+dID)
}
</script>
</td>";

Related

Populate DIV with an PHP arrayelement based on a click on a link

What I want:
A list of links show events - a click on such a link shall show further details in a special DIV on the same page.
Idea:
I read from the database all events:
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
This gives me all available events in the DB that are not yet processed.
I assgin all found events identified by their UUID into a PHP array for further processing
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i",
$eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
Having that 2-dimensional array "eventInfo" I build the list
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
Last but not least I create a DIV to store the desired eventBody-Information:
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
To populate now the DIV when a link is clicked I tried this:
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
I wanted to pass the php-Array with JSON to make it available inside the function.
With the click-effect I wanted to load from this php-array the related array-element ['eventBody'] with the UUID given by the link-click.
Somehow I am stuck. I am able to pass the UUDI key to the javascript area and can write it into the DIV but I cannot identify a php-element by the given UUID and put the content into the DIV.
Any hint is appreciated, thank you.
As requested here is the code in total:
<?php
// Including jQuery
echo '<script src="http://code.jquery.com/jquery-1.11.3.min.js">/script>';
// Querying the Neo4J DB
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
// Parsing result and build the 2-dimensional array $eventInfo
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i", $eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
// Displaying list of events with UUID as forwarded parameter (-> JS)
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
// Creating a DIV Container to hold $eventInfo[eventUUID][eventBody]
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
// JavaScript Part
echo <<<EOT
<script type="text/javascript">
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
</script>
EOT;
?>
2nd EDIT:
I have stripped down everything to this functioncode, which is at the end of the php-file and no longer wrapped in the php-tags. So its like standard html. This way I avoid the uncaught syntax error.
<script type='text/javascript'>
$(document).ready(function (){
var passedArray = '<?php echo json_encode(array($test_array)); ?>';
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
console.log(p);
console.log(passedArray[p]['eventBody']);
$('#info').text(passedArray[p]);
});
});
</script>
Outcome:
I can console.log the array, which shows as a test:
[[{"UUID":"60762d3eb9949596701a2dfb700cd2c9","eventBody":"Hallo"},{"UUID":"620c16ced5097bf60f718abca7d979f8","eventBody":"Ciao"}]]
I see also that when I click a link that the UUID key is passed to the Javascript-Script:
60762d3eb9949596701a2dfb700cd2c9
But when I want to assign the related eventBody-element I receive this error:
Uncaught TypeError: passedArray[p] is undefined
As I have the array and the key I assume it must be a syntax error in this line:
console.log(passedArray[p]['eventBody']);
So two questions left:
How would I access one element of the given array?
How can I then populate the DIV with the element ['UUID']['eventBody']? Not sure if this is the way to go: $('#info').html().passedArray[p];
Resolution (with Uwe's help):
function findme(p) {
var passedArray = '<?php echo json_encode($test_array); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
thanks to your support here (Kudos to Uwe) here is the solution:
As we use jQuery we need to include this in the head:
echo '<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>';
The Javascript-Function (written in HTML, not in PHP tags):
function findme(p) {
var passedArray = '<?php echo json_encode($eventInfo); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
I was not able to find a way to write the whole code within PHP tags, as the double echo (Start and inside the array handover) and the additional PHP?-tags always generates syntax errors - thus the JS function is written as HTML-code outside the PHP code.
In the PHP the UUID of the array is passed onClick to the JS function - looks like
echo ' Find the element by UUID Brackets -- '.$UUID.'';
Please pay attention to the escaped quotation marks - important to avoid an error in JS that allows no identifiers starting with a number.
The DIV is marked by
echo '<p id="result"></p>';
For testing I made an array like this:
$eventInfo= array();
$eventInfo[] = array('UUID' => '60762d3', 'eventBody' => 'Text 1');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 2');
$eventInfo[] = array('UUID' => '6076299', 'eventBody' => 'Text 3');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 4');

placing php inside javascript

<script>
var strWidth = document.getElementById("mydiv").style.width;
var strHeight = document.getElementById("mydiv").style.height;
var link = "<?php if(isset($_GET["ggg"])) {
echo $_GET["ggg"].".php?width=800&height=460";
} else {
echo "page1.php?width=800&height=460";
}
?>";
</script>
this is my script, php inside javascript. how do i place this variable strWidth inside
php?width=800&height=460
so becomes some how like this
php?width=strWidth&height=460
EDIT 2
well, the only thing i am trying to do here to show variable value between those line is it a big deal ?
it might be done by separating like using concatenation or something ?
Add an input-field in PHP, hide it (if necessary) and read the value of this field with JS.
First of all if you want to use php values in javascript you need the script to be written in a php file. Suppose you do this then you can do this in this way:
<script>
var strWidth = document.getElementById("mydiv").style.width;
var strHeight = document.getElementById("mydiv").style.height;
var link='<?php echo (isset($_GET["ggg"]))?isset($_GET["ggg"]):''; ?>'; // this assigns the valueto link variable
if(link==''){
// your logic starts here
}else{
// your logic starts here
}
</script>
Add an input-field and assign a value to the hidden element and then get value through javascript.
It is not a good idea to combine PHP and Javascript.
Refer this about explanation on client-side vs server-side coding.
you can't really do that. but this works
<?php
echo "<script>\n";
echo "var strWidth = document.getElementById(\"mydiv\").style.width;\n";
echo "var strHeight = document.getElementById(\"mydiv\").style.height;\n";
if(isset($_GET["ggg"])) {
echo "var link =" . $_GET["ggg"] . ".php?width=800&height=460';\n";
}
else {
echo "var link ='page1.php?width=' + strWidth + '&height=' + strHeight + '';\n";
}
echo "</script>\n";
?>
the reference to ggg completely confuses the understanding of this process so really it should be taken out:
__ page1.php
<?php
if (!isset($_GET['foundWidth'])){
//stops double hit
echo "<script>\n";
echo "var strWidth = document.getElementById(\"mydiv\").style.width;\n";
echo "var strHeight = document.getElementById(\"mydiv\").style.height;\n";
echo "var link ='/page1.php?foundWidth=true&width=' + strWidth + '&height=' + strHeight + '';\n";
echo "window.location = link;"
echo "</script>\n";
}
elseif (isset($_GET['foundWidth']) && ($_GET['foundWidth']=='true')) {
if (isset($_GET['width']) && is_numeric($_GET['width'])){
//use your width here SERVER SIDE
// or
echo "<script> alert('Width is: '+ " . $_GET['width']) . "); </script>\n";
}
if (isset($_GET['height']) && is_numeric($_GET['height'])){
//use your height here SERVER SIDE
// or
echo "<script> alert('Height is: '+ " . $_GET['height']) . "); </script>\n";
}
}
?>
using this "trick" you can then write the PHP params into the javascript url with whatever get string you like, including triggering a reload of the page with the width as a param, so if you want to test if $_GET['width'] is set to a number you can insert it etc

PHP `file_get_contents()` output pass to JavaScript and calculate length

I want to pass the output from PHP's file_get_contents() to JavaScript and calculate its length. Everything ok but when passing the variable JavaScript evaluates it as HTML code, so I have to use PHP's json_encode() to keep it "sane" but this way the string length from JavaScript will be different from the one in PHP. Using JS's JSON.parse() doesn't help because again the HTML code gets interpreted. Any idea how can I achieve the same evaluated data length?
EDIT: Basically I need to count all the characters in the page source, that includes tags and special characters. To have the same output computed in JS like the one i get in PHP's strlen($url_data).
EDIT 2: I thought about doing bin2hex() on the $url_data then reconvert in JS and check the length. Would be that reliable?
Here is what I did so far:
<?php
ini_set('display_erros', -1);
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
$url = filter_var($_POST['urlinput'], FILTER_SANITIZE_URL);
$url_data = #file_get_contents($url);
$js_url_data = json_encode($url_data);
//$url_src = htmlspecialchars($url, ENT_IGNORE);
$url_data_len = mb_strlen($url_data);
$url_src = strip_tags($url_data);
echo '<ul id="resultList">';
echo "<li>The following page contains " . $url_data_len . " characters</li>";
echo "<li>Page URL: " . $_POST['urlinput'] . "</li>";
echo "<li>Page title: " . page_title($url_data) . "</li>";
echo "<li>Protocol: " . parse_url($url, PHP_URL_SCHEME) . "</li>";
echo "<li>Host: " . parse_url($url, PHP_URL_HOST) . "</li>";
echo "</ul>";
//var_dump($url_src);
} else {
$error = "URL is not valid!";
}
}
function page_title($str) {
$matches = array();
if (preg_match('/<title>(.*?)<\/title>/i', $str, $matches)) {
return $matches[1];
}
else {
return null;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP file_get_contents()</title>
</head>
<body>
<div class="url_class">
<form id="getsrc" method="post">
<input style="width: 300px;" type="text" name="urlinput" id="urlinput" placeholder="URL">
<input type="submit" name="submit" value="Get SRC">
</form>
</div>
<textarea rows="20" cols="50">
<?php
if (!empty($url_src)) {
echo $url_src;
}
?>
</textarea>
<?php echo '<br><span style="color:red">' . $error . '<span>'; ?>
<?php
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
var url_data = $js_url_data;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript page characters: " + url_data.length);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
}
?>
</body>
</html>
Simply use the value calculated by php, it can be used within EOT block:
...
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
...
$url_data = #file_get_contents($url);
$fileSize = strlen($url_data);
...
}
....
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
...
var textnode = document.createTextNode("JavaScript page characters: " + $fileSize);
...
</script>
EOT;
echo $script;
Since no good answer, I would post my solution to my problem. The only way I could find was to hex-encode $url_data, pass it to JS, decode it and count the characters. For the pack() function I used the one ported in php.js.
...
$js_url_data = bin2hex($url_data);
...
if (!empty($js_url_data)) {
/* This is a good example when one is forced to use inline JS */
$script = <<<EOT
<script>
var url_data = "$js_url_data";
var url_data_len = pack('H*', url_data).length;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript calculation page characters: " + url_data_len);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
...

jQuery and JSON: loop json array

I have an array in database:
a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}
So I unserialize with php and then encode it with json, code looks like following:
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
I get this on the page:
Array ( [1] => 1993 [2] => 1994 [3] => 1995 [4] => 1996 ) {"1":"1993","2":"1994","3":"1995","4":"1996"}
I need to loop it somehow with jQuery? so i can get 1993,1994,1995,1996 and so on.
I was testing jQuery.getJSON(), but cant figure out how exactly to use it?
All code together on the page:
<?php
$array = $_POST['inputarray'];
$str = serialize($array);
print $str . "\n";
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
?>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
jQuery(function ($) {
// Add children input fields
var childBlock = $('.block');
var countChildren = $('div.block div.row').size() + 1;
$('#addChild').live('click', function (e) {
e.preventDefault;
$('<div class="row"><input type="text" name="inputarray['+countChildren+']" id="inputarray'+countChildren+'" placeholder="inputarray['+countChildren+']">Delete</div>').appendTo(childBlock);
countChildren++;
});
$('#deleteChild').live('click', function (e) {
e.preventDefault();
if (countChildren > 2) {
$(this).parents('div.row').remove();
countChildren--;
var counter = 1;
$('input[name^="inputarray"]').each(function () {
$(this).attr('name', 'inputarray[' + counter + ']');
$(this).attr('placeholder', 'inputarray[' + counter + ']');
$(this).attr('id', 'inputarray' + counter);
counter++;
});
}
});
})(jQuery);
</script>
<form action="" method="post">
<div class="block">
<div class="row"><input type="text" name="inputarray[1]" placeholder="inputarray[1]"></div>
<input type="hidden" value="<?php echo $str; ?>">
</div>
<input type="submit">
</form>
Add a child
Thank you!
This could be done easily in PHP. Since I don't see any handlers for submit() or click() or anything that could suggest an ajax request.
And you also have the php in the same file, so why not simply loop with PHP and produce what you need?
echo "<select name='year'>";
foreach($unwp as $year) {
echo "<option value='{$year}'>{$year}</option>";
}
echo "</select>";
The above snippet will product exactly what you need.
Example
Edit
You're trying to generate a <select> right? If not, let me know so I can modify as required.
I would change
echo json_encode($unwp);
to
echo "<script> var fromPhP = ".json_encode($unwp). "</script>;
in this way you get json in variable and I saw you are using jquery so i would use $.each to loop it:
$.each(fromPhP ,function(index,item){
console.log(index,item);
});
Use $.getJSON like this:
$.getJSON("scriptname.php", function(data) {
html = '';
$.each(data, function(i, el) {
html += '<div class="block">' +
'<div class="row"><input type="text" name="inputarray['+i+']" placeholder="inputarray['+i+']"></div>' +
'<input type="hidden" value="'+el+'">');
});
$("form > div").delete();
$("form").prepend(html);
});

update php var with js var from ajax call

I'm trying to update php $questNumber with the incremented javascript questNum with jQuery $.get()
Console.log tells me that the js questNum var is being incremented correctly.
But echo "testing..." . $questNumber; outputs 1 even after I've incremented the value on the JS side. This means the updated value is not being sent to $questNumber to update the database, and return the appropriate new set of values to the javascript side.
JavaScript:
/*Check player sentence input to see if grammar is correct*/
function submitMe() {
var input = document.getElementById('textBox').value;
log(questNum);
if ($.trim(input) == getSentence(questNum)) {
$("#responseVerify").html("Great job");
$("#textBox").val("").trigger("change");
//post successful quest to Quests.php, which will increment questcount there, and get new vocab words
questNum++;
log(questNum);
$.get("php/Quests.php", { "_questNum" : questNum},
function() {
$(".wordBank_Words").empty();
$.each(wordsArray, function(key, value) {
$(".wordBank_Words").append("<div class='bank-word' word='" + key + "' ><b>" + key + "</b>: " + value + "</div>");
});
});
}
else {
$("#responseVerify").html("Keep going...");
}
}
PHP:
<?php
//if user's input is correct, increment task number, get next vocabulary
include 'DbConnect.php';
$questNumber = (isset($_GET['_questNum']) ? ($_GET['_questNum']) : 1);
echo "testing..." . $questNumber;
$qry =
"SELECT t.*, v.*
FROM task t
INNER JOIN vocabtask vt ON (t.id = vt.taskid)
INNER JOIN vocab v ON (v.id = vt.vocabid)
WHERE vt.taskid = " . $questNumber;
$sql = $mysqli->query($qry);
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
echo $row['chinese'];
$wordsArray[$row['chinese']] = $row['english'];
}
echo "testing..." . $questNumber;
mysqli_close($mysqli);
echo "<script type='text/javascript'> var wordsArray = " . json_encode($wordsArray) . "; </script>";
?>
HTML:
<!--ROW 3: RESPONSE-->
<div class="row">
<div class="span12">
<!--Select a word shown and it gets added to the input box-->
Create sentence:
<input type="text" id="textBox" value="" />
<br/>
<button onclick="submitMe()" id="testButton" >Submit Response </button>
<br/>
<i><span id="responseVerify"></span></i><br />
<div class="wordBank_Headings">Word Bank:
<span class="wordBank_Words"></span>
</div>
<div class="wordBank_Headings">Hint:
<span class="wordBank_Hint"></span>
</div>
<div class="wordBank_Headings">New Words:
<span class="new"></span>
</div>
</div>
</div>
Try this ajax format
$.ajax({
type: "GET", //method
url:"php/Quests.php", //your ajax page
data:"_questNum="+questNum, //pass values to this data
success: function(data){ //success function
alert('sasas');
}

Categories