i am using PHP Codeigniter and trying to pass array from Controller to JavaScript function using onClick() but could not find any solution.
Here is my code in controller:
function get_class_students_mass_pdf($class_id) {
$students = $this->db->get_where('enroll', array(
'class_id' => $class_id, 'year' => $this->db->get_where('settings', array('type' => 'running_year'))->row()->description
))->result_array();
$invoiceid = array();
foreach ($students as $row) {
$invoice_id = $this->db->get_where('invoice', array('student_id' => $row['student_id']))->row()->invoice_id;
$invoiceid[] = $invoice_id;
}
$invoiceid = json_encode($invoiceid);
echo '<br><br><button style="margin-left: 36px;" type="button" class="btn btn-default" onClick="invoice_view_modal('.$invoiceid.')"> ' . get_phrase('generate_pdf') . ' </button>';
}
My JavaScript Function in View:
function invoice_view_modal(invoiceid) {
showAjaxModal('<?php echo site_url('modal/popup/modal_view_mass_invoice/');?
>' + invoiceid);
}
$invoiceid is my array that I am trying to access in my JavaScript Function using onClick() method.How do I access it?
I have same problem in my project and after debugging i came to know that javaScript function not accepting the special characters in the array like ",". so i simply use htmlspecialchars() and it works for mine.
Try this,
$invoiceid = htmlspecialchars(json_encode($invoiceid));
<?php $text="Alice's";?>
($text data comes form database, I just put an example like Alice's)
<button type="submit" onclick="Remove('<?php echo $text; ?>')"></button>
<script>
Remove(text){
alert(text);
}
</script>
When I use ' at $text variable Javascript function Remove() does not work. I use php htmlentities() function but it does not work
This is because once your string is passed into the onClick function it is getting confused with all the ' and ".
So to make this work you could escape your variable ' with a \
Depending where the data is coming from you may need to write something that escapes these automatically for you.
<?php $text="Alice\'s"; ?>
<button type="submit" onclick="Remove('<?php echo $text; ?>')"></button>
<script>
function Remove(text){
alert(text);
}
</script>
I'm trying to create a nice and easy iterator and it worked at first, then I realized I'd need more information for the function so I tried to extend it and well it did not work.
Example Usage
$easyCMS->iterate($post,
echo $content[0];
echo $content[1];
);
Class Function
public function iterate($d,$fn){
$this->item = $d;
foreach($this->item as $post){
echo $fn;
}
}
Current Index.php Usage
$post = $easyCMS->my_query('SELECT * FROM `newsPost`');
//returns array
$easyCMS->iterate($post,
$content[0]."<br>",
$content[1]."<br>",
$content[2]."<br>",
$content[3]."<br>",
$content[4]."<br>",
);
//$post would be the first argument and after that would be what we want our function to do.
I get the error =>
Parse error: syntax error, unexpected ';' in .../index.php on line 23
Which I know that it's the constant $content[num] but I'd like to know how I'd do this for I know I could with JavaScript using the call method.
My database table looks something like
id: 1 == content: "Whats up" == ...etc
I want my code to iterate over these so then I can write like so
$easyCMS->iterate($post,
'<div class="hello">'.$content[0].'</div><div id="post_'.$content[1].'"><div class="content">'.$content[2].'</div>'
);
the error is caused by:
$easyCMS->iterate($post,
$content[0]."<br>";
$content[1]."<br>";
$content[2]."<br>";
$content[3]."<br>";
$content[4]."<br>";
);
which should be
$easyCMS->iterate($post,
$content[0]."<br>",
$content[1]."<br>",
$content[2]."<br>",
$content[3]."<br>",
$content[4]."<br>"
);
i don't think that this code solves your needs
Here is the best way for an easy iterator, took me some time but I finally solved it.
Class Function
public function iterate($d,$fn){
foreach($d as $item){
$txt = str_replace('{author}',$item["author"],$fn);
$txt = str_replace('{id}',$item["id"],$txt );
$txt = str_replace('{content}',$item["content"],$txt);
$txt = str_replace('{date}',$item["date"],$txt);
echo $txt;
}
}
PHP page IE index.php
$post = $easyCMS->my_query('SELECT * FROM `newsPost`');
$easyCMS->iterate($post,'<div class="hello">{author}</div><div id="post_{id}"><div class="content">{content}</div></div>');
$easyCMS->my_query is just a regular query which returns specific information
my_query
public function my_query($sql)
{
$array=array();//add an array
$query = mysqli_query($this->connect,$sql);
if($query > 0){
$c = mysqli_num_rows($query);//get how many rows there are
if($c > 1){//if greater than one push into the array
while($fetch = mysqli_fetch_array($query)){//while loop to push
array_push($array, $fetch);
}
return $array;
}else{
return mysqli_fetch_row($query);//rows is only one
}
}else{
return "No such query";//if the query does not exist!
}
}
Can't help but think you're over-complicating things here.
If you're using an array without an index key then it would be as simple as:
public function iterate($d,$fn){
foreach($d as $content){
echo $content;
}
}
Only if an index is key=>pair do you need to it like:
foreach ($d as $key=>$value) {
stuff//
}
$easyCMS->iterate($post,
'<div class="hello">'.$content[0].'</div>
<div id="post_'.$content[1].'"><div class="content">'.$content[2].'</div>'
);
Is wrong. When using " and ', you want to wrap ' inside of the ".
If, what you want is to irerate through a loop inside a loop, you'd want something like:
Foreach($post as $pos) {
$class->some_func($pos);
}
public function some_func ($post) {
/formatting.
echo $post;
/formatting.
}
The simplest I can come up with, based on your code currently is:
foreach($stuff_from_database_call as $content)
echo "formatting stuff". $content . "/close formatting";
Technically you could 1 line it, so long as dont mind using . to join strings :)
Note the lack of [0] [1] etc, which is un-needed, since you are iterating through the array. However, if it was a key=>pair you'd do it like this:
foreach($stuff_from_database_call as $key=>$content)
echo "formatting stuff". $key[$content] . "/close formatting";
Updated this after you wrote out and accepted your own answer. Instead of:
public function iterate($d,$fn){
foreach($d as $item){
$txt = str_replace('{author}',$item["author"],$fn);
$txt = str_replace('{id}',$item["id"],$txt );
$txt = str_replace('{content}',$item["content"],$txt);
$txt = str_replace('{date}',$item["date"],$txt);
echo $txt;
}
}
I'd suggest something more like:
public function iterate($d,$fn){
foreach($d as $item=>$value){
$txt = str_replace('{$value}',$item[$value],$fn);
echo $txt;
}
}
This will make it a LOT more flexible, as you can easily add fields, without having to touch the function itself. When coding, ALWAYS try and do so with as much forethought as you can, so you save yourself headaches down the road.
Either way, glad you got it sorted, and glad you came back to post your sollution.
1 last afterthought. Try naming your variables a little more reader friendly :) $d is nowhere near descriptive enough. Just another avoidable headache, for yourself and for anyone else having to look at your code :)
im using ajax to query my mysql to my database.
But im stock at issue with my php generated html form input - javascript/jquery will simply not pick up the value. From normal html is no issue of course.
php (works fine, all echos are good)
<?php
function getAge() {
$age = "<select name='age'>";
$result = $mysqli->query("select * from ages");
while ($row = $result->fetch_row()) {
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
}
$age.="</select>";
return $age;
}
?>
html
<form id="myform">
<input name='name' value='Nick'>
<input name='sport' value='Football'>
<?php echo getAge(); ?>
<input type='submit'>
</form>
javascript
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = {}
$.each(this.elements, function(){
json[this.name] = this.value || '';
});
}
Everything works well except it wont get the value of the <select>. If i make a normal html select it works.. ?!
Also anybody know how to delete the submit button from the json object? :-)
Any dynamically generated HTML will not have the events applied to them, as those events are applied on page load. So if you apply the events to the document, you will be able to pull values from dynamically generated html. Like so:
var json = {};
$(document).on('submit', 'form#myform', function(e){
$('*', this).each(function(){
json[$(this).attr('name')] = $(this).val();
});
});
Hope this helps!
change this line:
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
to this:
$age.="<option value='" . $row[0] . "'>". $row[1] ."</option>";
//----------------^---------------^------put quotes
And i think you can make use of .serializeArray() which does the same you want but in a different way like multiple objects with multiple [{ name : value}] pairs:
$(function(){ //<-----put this block too
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = $(this).serializeArray();
}); //<----checkout the closing
}); //<---doc ready closed.
This is my php code
foreach($resource as $res) {
$PDF = $res->res_link;
$pdfname = $res->$res_name; (which is Dimesional_analysis)
echo "<a class='pdflink' href='#' onClick=OpenPdf('$PDF','$pdfname');><div class='txt'><table class='txt-in'><tr><td>$icon</td><td> $temp </tr></table></div></a>";
}
and my onclick javascript code
function OpenPdf(pdf,pdfname) {
some functionality;
}
However, on clicking the link it is showing "unterminated string literal". however, when the pdfname has no underscore, that is if I give like $pdfname = 'Dimension' it is working fine.Hope someone will help me solve this. Thanks.
Always look at the generated HTML:
<a class='pdflink' href='#' onClick=OpenPdf('something','Dimensional_analysis');>
That doesn't look valid to me :p It's certainly vulnerable to problems.
Try this: (newlines added for readability)
echo '<a class="pdflink" data-pdf="'.htmlspecialchars($PDF).'"
data-pdfname="'.htmlspecialchars($pdfname).'"
onClick="OpenPdf(this.getAttribute(\'data-pdf\'),
this.getAttribute(\'data-pdfname\'));">';
try this:
echo "<a class='pdflink' href='#' onClick=OpenPdf('".$PDF."','".$pdfname."');><div class='txt'><table class='txt-in'><tr><td>$icon</td><td> $temp </tr></table></div></a>";