0

I am using codeigniter 3. Below is the code of the view page, where data inside the $row->poll_question; is coming from the database. Thus, the different values coming inside this variable are echoed on a page called voting.php. And just beside this variable, there is a button called View Poll. Now, on clicking this button I want to pass the data of this php variable to javascript section. And simply alert and check in javascript. Please help. I have pasted the code I tried.

voting.php

<h3 class="val" id="val" style="color:rgb(158, 158, 158);font-family: 
arial;margin-top: 2%;" ><?php echo $row->poll_question; ?></h3>
</td>

<td>

<a class="btn btn-lg btn-primary view_button" id="view_button" 
 style="margin-left: 18%;padding:10%;border-radius: 10px;" 
 onclick="fetch_val(<?php echo $row->poll_question ?>)">View Poll</a>

Javascript

function fetch_val(val)
{
     alert(val);
}

2 Answers 2

1

You have forgot to add quote on '<?php echo $row->poll_question ?>'. Check updated code below

<h3 class="val" id="val" style="color:rgb(158, 158, 158);font-family: 
arial;margin-top: 2%;" ><?php echo $row->poll_question; ?></h3>
</td>

<td>

<a class="btn btn-lg btn-primary view_button" id="view_button" 
 style="margin-left: 18%;padding:10%;border-radius: 10px;" 
 onclick="fetch_val('<?php echo $row->poll_question ?>')">View Poll</a>
Sign up to request clarification or add additional context in comments.

Comments

1

I don't recommend the redundant storage of the string.

You already have the value in your id'ed <h3> tag. Just use that.

Further advice move all stylings to an external stylesheet and use a javascript listener on your #view_button.

You could stay with an inline function call:

<h3 class="val" id="val"><?php echo $row->poll_question; ?></h3>

<a class="btn btn-lg btn-primary view_button" id="view_button" 
   onclick="fetch_val(document.getElementById('val').innerHTML);">View Poll</a>

Or trigger fetch_val() via a listener written in your javascript (this is the cleaner / more professional way):

document.getElementById('view_button').onclick = function() {
    alert(document.getElementById('val').innerHTML);
}

About writing a pure javascript onclick handler: https://stackoverflow.com/a/17633164/2943403

Assigning a custom function to an event: https://stackoverflow.com/a/24665785/2943403

Using either of my above techniques will remove the possibility of quoting issues caused by questions like What is your mother's maiden name?.

1 Comment

Thank you so much @mickmackusa . I will definitely keep this in mind too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.