Display laravel variable using javascript - javascript

when i try dd($conv) the data are there, but I still can't display them inside the script.
Anyone know whats the problem, I have tried many ways but they doesn't seem to work.
<h4>{{$row->transcript_text}}</h4>
<?php $conv = json_encode($row->transcript_text); ?>
<script type="text/javascript">
function splitArray() {
var myStr = <?php echo $conv; ?>;
var strArray = myStr.split(/(?= \| \d)/);
// Display array values on page
for (var i = 0; i < strArray.length; i++) {
$("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
})
}
splitArray();
</script>

I don't know which version of Laravel you're using but the recommended way to embed plain PHP in your HTML templates is with the #php notation (cf doc).
Anyway, that's something I'd try to avoid. Instead, Laravel blade has native ways of doing what you're trying to do.
#if(! empty($history))
#foreach($history as $row)
<script type="text/javascript">
function splitArray() {
var myStr = JSON.parse("{{json_encode($row->transcript_text) }}");
var strArray = myStr.split(" | 0");
// Display array values on page
for (var i = 0; i < strArray.length; i++) {
$("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
}
}
</script>
<body onload="splitArray()" style="color: lime">
</body>
#endforeach

Related

Incrementing Array Index on button click in Javascript

Below is my javascript code! I'm trying to increment the index of array $arr everytime the user clicks a button. The array is defined in a separate php tag! Where am I going wrong?
function option1() {
var i = 0;
document.getElementById("btn0").value = "newButtonValue";
document.getElementById("question").innerHTML =
"<?php echo $arr["results"][i++]["question"] ?>";
}
Where your compiler return output to browser your php code was compiled and you can't run it such as javascript.
you can use this js:
var arr = <?php echo json_encode($arr["results"]);?>;
function option1() {
var i = 0;
document.getElementById("btn0").value = "newButtonValue";
document.getElementById("question").innerHTML = arr[i++]["question"];
}
.html file
<button onclick="addIndex(this)" queNo="0">newButtonValue</button>
in .js file
function addIndex(btn) {
var i = btn.getAttribute("queNo")
console.log(i);
btn.setAttribute("queNo", i++);
document.getElementById("question").innerHTML = "<?php echo $arr['results']["+i+"]['question'] ?>";
}
Hope it's help you

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!

Javascript not displaying what i would expect

I'm having a little trouble with Javascript/php/html. I have written this code below to display "GetM" if the time is > 480 seconds this seems to work great when there is just one instance of this. However, I have 14 blocks and any other blocks do not show their GetM values. Below is an image of what U mean by "blocks". The value for GetM on the first block is the percentage
<div id ="ZL01001Percent" class="BottomboxPercent">
<script type="text/javascript">
var time = <?php echo $machine1->data(); ?>;
var M = <?php echo $machine1->GetM(); ?>;
var P = M.toFixed(1);
if (time > 480) {
document.write(P * 100 + '%');
}
</script>
</div>
Any help would be much appreciated
I strongly recommend you create a JS Object representation of your data. If you create a PHP array, you can use json_encode to generate
var machines = <?PHP echo json_encode($myValues); ?>
which should result in
var machines = {
ZL01001: { time:500, M : 733},
ZL01002: { time:600, M : 556}
}
and then you can do
window.onload=function() {
for (var m in machines) {
var machine = machines[m];
document.getElementById(m+"Percent").innerHTML=machine.time>480?(machine.M.toFixed(1)*100)+"%":"";
}
}

How to bring PHP array value to 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>

Javascript get title value from <li>

In general: What I want is to have PHP output an unordered list with books. When the user clicks on one of the titles, the details will be pulled from the DB and inserted into the page using AJAX.
I can't seem to figure out how to pull the title value from the < li > using javascript, so I can pass that to AJAX.
(To simplify the example code, I left out the AJAX part and am using an alert instead.)
<html>
<head>
<script type="text/javascript">
window.onload = function()
{
var shelve = document.getElementById( 'books' );
var books = shelve.getElementsByTagName( 'li' );
for( var i=0; i < books.length; i++ ){
books[i].onclick = function(){
alert(books[i].title); //I know this doesn't work
};
}
}
</script>
</head>
<body>
<div id="txtHint"><b>Book info will be listed here using AJAX.</b></div>
<?php show_allBooks(); ?>
</body>
</html>
<?php
function show_allBooks(){
db_connect();
$query = "Select * from tblBooks order by title";
$result = mysql_query($query);
echo "<ul id='books'>";
while ($row = mysql_fetch_array($result))
{
echo "<li title='" . $row['id'] . "'>" . $row['title'] . "</li>";
}
echo "</ul>";
db_close();
}
?>
I tried fooling around with variations of the following code, but this did not seem to work either.
books[i].getAttribute("title")
Can anyone point me in the right direction? Any help would be greatly appreciated.
By the time your onclick handler gets called, i has been incremented to books.length. Instead, you can reference this to get the element.
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = function () {
alert(this.title);
};
}
http://jsfiddle.net/gilly3/cPMAU/
However, if you do need to know the value of i in the click handler, you can do it by creating your handler in a factory, that is a function that returns a function:
function createBookHandler(books, i) {
return function() {
alert(books[i].title);
};
}
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = createBookHandler(books, i);
}
http://jsfiddle.net/gilly3/cPMAU/1/
Start with
books.item(i)
Then it depends how title is stored in the list. If its
<li title="">
then
books.item(i).getAttribute("title")
But the closure related answer is probably more important.

Categories