Looping with php over a php-Statement wrapped in javascript - javascript

I am using dygraphs to plot a graph. I am using a database to store all the values i need. to use dygraphs i have to use javascript. but the data im getting from the database needs to fill the dygraphs constructor dynamically. i could do it like this, but that isnt dynamic and not what i need.
<script type="text/javascript">
g = new Dygraph(
document.getElementById('graphdiv'),
"Travel(mm),Force(N)\n"+
"0,0\n"+
"<?php $sql = "SELECT daten FROM azubi3 where pau_table_id=2";
$result = pg_query($sql);
$row = pg_fetch_row($result);
$toEcho = str_replace("{","[",$row[0]);
$toEcho = str_replace("}","]",$toEcho);
$toEcho = json_decode($toEcho);
echo $toEcho[0][0].','.$toEcho[0][1].'\n';
?>"+
"<?php echo $toEcho[1][0].','.$toEcho[1][1].'\n';?>"+
"<?php echo $toEcho[2][0].','.$toEcho[2][1].'\n';?>"+
"<?php echo $toEcho[3][0].','.$toEcho[3][1].'\n';?>"+
"<?php echo $toEcho[4][0].','.$toEcho[4][1].'\n';?>"+
"<?php echo $toEcho[5][0].','.$toEcho[5][1].'\n';?>"+
"<?php echo $toEcho[6][0].','.$toEcho[6][1].'\n';?>"+
"<?php echo $toEcho[7][0].','.$toEcho[7][1].'\n';?>"+
"<?php echo $toEcho[8][0].','.$toEcho[8][1].'\n';?>"+
"<?php echo $toEcho[9][0].','.$toEcho[9][1].'\n';?>"+
"<?php echo $toEcho[10][0].','.$toEcho[10][1].'\n';?>"+
"<?php echo $toEcho[11][0].','.$toEcho[11][1].'\n';?>"+
"<?php echo $toEcho[12][0].','.$toEcho[12][1].'\n';?>"+
"<?php echo $toEcho[13][0].','.$toEcho[13][1].'\n';?>"+
"<?php echo $toEcho[14][0].','.$toEcho[14][1].'\n';?>"+
"<?php echo $toEcho[15][0].','.$toEcho[15][1].'\n';?>"+
"<?php echo $toEcho[16][0].','.$toEcho[16][1].'\n';?>"+
"<?php echo $toEcho[17][0].','.$toEcho[17][1].'\n';?>"+
"<?php echo $toEcho[18][0].','.$toEcho[18][1].'\n';?>"+
"<?php echo $toEcho[19][0].','.$toEcho[19][1].'\n';?>"+
"<?php echo $toEcho[20][0].','.$toEcho[20][1].'\n';?>"+
"<?php echo $toEcho[21][0].','.$toEcho[21][1].'\n';?>"+
"<?php echo $toEcho[22][0].','.$toEcho[22][1].'\n';?>"+
"<?php echo $toEcho[23][0].','.$toEcho[23][1].'\n';?>"+
"<?php echo $toEcho[24][0].','.$toEcho[24][1].'\n';?>"+
"<?php echo $toEcho[25][0].','.$toEcho[25][1].'\n';?>"
);
</script>
because i have to seperate the data with "...."+ i dont know how to control that i echo as much as my array is long. i thought of a loop over the javascript code which itself contained php. it didnt work. some ideas? or questions, i dont know if anyone will understand me...

This looks to me like a perfect case for using foreach
Output will look like
"123,123\n;"+
.....
"126,143\n;"
Code:
$setCount = 0; // keeps track of sets so i dont put a linebreak before the first one
$toEcho = json_decode($toEcho);
foreach ($toEcho as $set){
if($setCount>0) echo "+"; // every set is seperated with a plus
echo "\""; // put double quote down
$valueCount = 0;
foreach($set as $value){
if($valueCount>0) echo ',';
echo $value;
$valueCount++;
}
echo "\\n;\""; // puts the weird \n into the string and final quote
$setCount++;
}
Let me know if something is unclear.

Related

How to avoid the new line and extra space issue? Because I have contionously getting this error "unterminated string literal"

This is my onchange function, But i keep getting this error SyntaxError: unterminated string literal
function OrganizationPrefill(type){
if(type == 'org' ){
var orgdts = "<?php echo $orgDets['state']; ?>";
var myStr = "<?php echo $orgDets['address']; ?>";
var newStr = myStr.replace('\n', '');
$('#states option[data='+orgdts+']').prop('selected','selected');
$("#address").val(newStr);
$("#zip").val("<?php echo $orgDets['zip']; ?>");
$("#city").val("<?php echo $orgDets['city']; ?>");
}else if(type == 'orguser'){
var myStr1 = "<?php echo $doctorDets['address']; ?>";
var newStr1 = myStr.replace('\n', '');
$("#address").val(myStr1);
$("#zip").val("<?php echo $doctorDets['zip']; ?>");
$("#city").val("<?php echo $doctorDets['city']; ?>");
$('#states').val("<?php echo $doctorDets['state']; ?>");
}
}
This is the address that I have in my database
Al Ameen
CCNA street
uzbaskistan
I want these 3 things in a single line, I already tried trim,str_replace but cant get the correct solution can anyone please assit me
What I need is ==>
Al Ameen CCNA street uzbaskistan
Thanks Everyone, Now its Working. This is my answer
function OrganizationPrefill(type){
if(type == 'org' ){
var orgdts = "<?php echo $orgDets['state']; ?>";
<?php $orguserAddr = str_replace(array("\n", "\r"), ' ', $orgDets['address']); ?>
$("#address").val("<?php echo $orguserAddr; ?>");
$('#states option[data='+orgdts+']').prop('selected','selected');
$("#zip").val("<?php echo $orgDets['zip']; ?>");
$("#city").val("<?php echo $orgDets['city']; ?>");
}else if(type == 'orguser'){
<?php $userAddr = str_replace(array("\n", "\r"), ' ', $doctorDets['address']); ?>
$("#address").val('<?php echo $userAddr; ?>');
$("#zip").val("<?php echo $doctorDets['zip']; ?>");
$("#city").val("<?php echo $doctorDets['city']; ?>");
$('#states').val("<?php echo $doctorDets['state']; ?>");
}
}

Jquery val() cannot read html tags received by php echo

this is my code, i have send value to input :
<script type="text/javascript">
Drupal.behaviors.devenirClientDepuisServiceform = {
attach: function (context, settings) {
jQuery(document).ready(function($) {
//$('.webform-component--nom-abnonnement>input').val('<?php echo $_GET['name']; ?>');
//$('.webform-component--produits-choisie>input').val('<?php echo $produitnid ?>');
jQuery('.webform-component--nom-abnonnement>input').val('<?php echo $produitname ?>');
jQuery('.webform-component--produits-choisie>input').val('<?php echo $produitnid ?>');
jQuery('.webform-component--type-de-client>input').val('<?php echo $type ?>');
jQuery('.webform-component--contrat>input').val('<?php echo $imageUrl; ?>');
});
}
};
//
</script>
$imageUrl is a text html
but jquery cannot understand and give me this error :
SyntaxError: unterminated string literal
try with using these quotes ` and removing line break of last one
jQuery(document).ready(function($) {
//$('.webform-component--nom-abnonnement>input').val('<?php echo $_GET['name']; ?>');
//$('.webform-component--produits-choisie>input').val('<?php echo $produitnid ?>');
jQuery('.webform-component--nom-abnonnement>input').val(`<?php echo $produitname ; ?>`);
jQuery('.webform-component--produits-choisie>input').val(`<?php echo $produitnid ; ?>`);
jQuery('.webform-component--type-de-client>input').val(`<?php echo $type ?>`);
jQuery('.webform-component--contrat>input').val(`<?php echo str_replace(array("\r", "\n"), '', $imageUrl); ?>`);
});
You forgot to write ";".. add ; after every echo statement
jQuery(document).ready(function($) {
//$('.webform-component--nom-abnonnement>input').val('<?php echo $_GET['name']; ?>');
//$('.webform-component--produits-choisie>input').val('<?php echo $produitnid; ?>');
jQuery('.webform-component--nom-abnonnement>input').val('<?php echo $produitname; ?>');
jQuery('.webform-component--produits-choisie>input').val('<?php echo $produitnid; ?>');
jQuery('.webform-component--type-de-client>input').val('<?php echo $type; ?>');
jQuery('.webform-component--contrat>input').val('<?php echo $imageUrl; ?>');
});

Assigning PHP Variables To Javascript Variables Not Working

I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.

Converting This Javascript to PHP to display Local Date?

What I'm trying to do is display the local date using PHP. Right now I have a javascript solution that prints the month that corresponds with the php variable for the month in whatever language I want. For example for <?php echo $one; ?> (January) it can be populated with January (english), Enero (spanish), or Gennaio (italian).
Is there any way to convert this bit of code completely to PHP? if not, is there any way I can turn the code into a php variable so I can just put something like <?php echo $date; ?> and still define $one, $two, $three, etc?
<script type="text/javascript">
var month = new Array();
month[0] = "<?php echo $one; ?>";
month[1] = "<?php echo $two; ?>";
month[2] = "<?php echo $three; ?>";
month[3] = "<?php echo $four; ?>";
month[4] = "<?php echo $five; ?>";
month[5] = "<?php echo $six; ?>";
month[6] = "<?php echo $seven; ?>";
month[7] = "<?php echo $eight; ?>";
month[8] = "<?php echo $nine; ?>";
month[9] = "<?php echo $ten; ?>";
month[10] = "<?php echo $eleven; ?>";
month[11] = "<?php echo $twelve; ?>";
//Array starting at 0 since javascript dates start at 0 instead of 1
var mydate= new Date()
mydate.setDate(mydate.getDate())
document.write(""+month[mydate.getMonth()]+" "+mydate.getDate()+", "+mydate.getFullYear());
</script>
Sorry for not having a fiddle, I would create one but since there is some php involved I'm not sure of where to go for that. If there is something like jsfiddle that also includes php ill set that up if needed so its much easier to understand.
In PHP, you can use setlocale() along with strftime().
So, for example if you want to print the current month in French, you could do:
setlocale(LC_TIME, "fr_CA");
echo strftime("%B");
List of Locales: List of All Locales and Their Short Codes?

Using a PHP variable inside JavaScript

I'm pretty new, so go easy. I am using a session in PHP with a few variables. I want to concatenate two strings together from my PHP session when the clicks a button. I am using JavaScript onclick to try and achieve this.
I am having trouble getting my JavaScript to accept my PHP variables. Does anybody have any suggestions?
PHP:
$_SESSION['user1'] = $_POST['user'];
$_SESSION['string3'] = $_POST['string1'];
$_SESSION['string4'] = $_POST['string2'];
echo $_SESSION['user1'];
echo $_SESSION['string3'];
echo $_SESSION['string4'];
if(isset($_SESSION['user1'])) {
echo 'Welcome, '.$_SESSION['user1'].". Lets concatenate ".$_SESSION['string3']." and ".$_SESSION['string4'];
} else {
echo "<meta http-equiv=\"refresh\" content=\"0;URL=">";
}
<button onclick="xy()">Try it</button>
<p id="answer"></p>
JS:
<script type="text/javascript">
function xy() {
var x = "<?php $_SESSION['string3']; ?>";
var y = "<?php $_SESSION['string4']; ?>";
document.getElementById("answer").innerHTML = x + y;
}
</script>
You need to echo the PHP variable there because otherwise they output nothing and the JS variable ends up empty:
var x = "<?php echo $_SESSION['string3']; ?>";
var y = "<?php echo $_SESSION['string4']; ?>";
So for example, if $_SESSION['string3'] is "abc", PHP will echo the value inside the JS and you'll get this:
var x = "abc";
instead of:
var x = ""; // no output from PHP when there's no echo
To simplify things, here is your whole function:
<script type="text/javascript">
function xy() {
var x = "<?php echo $_SESSION['string3']; ?>";
var y = "<?php echo $_SESSION['string4']; ?>";
document.getElementById("answer").innerHTML = x + y;
}
</script>
Maybe it should be something like this?
echo "<script type=\"text/javascript\">\n";
echo "function xy() {\n";
echo "var x = ".$_SESSION['string3']."\";\n";
echo "var y = ".$_SESSION['string4']."\";\n";
echo "document.getElementById(\"answer\").innerHTML = x + y;\n}";
echo "</script>";

Categories

Resources