Pass PHP array integer to JavaScript function as a parameter? - javascript

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));

Related

Get variable to pass to php form

I'm working on getting the following block of code to send the array variable 'row' to another page. The other page should pull the vendor_id from this array and help populate a form with database information. I'm completely lost at how to accomplish this as I am relatively new to web dev. Can someone point me in the right direction?
function operateFormatter(value, row, index) {
return [
'<a class="remove" href="javascript:void(0)" title="Remove">',
'<i class="fa fa-trash"></i>',
'</a>',
'<a class="view" href="viewVendor.php" title="View">',
'<i class="fa fa-eye"></i>',
'</a>'
].join('')
}
window.operateEvents = {
'click .view': function (e, value, row, index) {
sessionStorage.setItem("vendor_id", JSON.stringify(row));
},
'click .remove': function (e, value, row, index) {
$table.bootstrapTable('remove', {
field: 'id',
values: [row.id]
})
}
}
viewVendor.php
<?php
include 'config.php';
require './db_inc.php';
$user = $_SESSION['username'];
## Fetch records
$stmt = $conn->prepare("SELECT * FROM vendor_data");
$stmt->execute();
$Records = $stmt->fetchAll();
$data = array();
foreach($Records as $row){
$data[] = array(
"name"=>$row['name'],
"company"=>$row['company'],
"type"=>$row['type'],
"status"=>$row['status'],
"owner"=>$row['owner'],
"descr"=>$row['descr'],
"owner_email"=>$row['owner_email'],
"dept"=>$row['dept']
);
}
return json_encode(($data));
?>
<script>
alert(sessionStorage.getItem("vendor_id[1]"));
</script>
I have a php page that includes the above mentioned viewVendor.php file which should pass along the information. Maybe I'm over complicating things?
You could add the vendor_id to the query string in your a tag like (assuming 'row' is the vendor id value):
'<a class="view" href="viewVendor.php?vendor_id=' + row + '" title="View">',
Then in your viewVendor.php file, access it with:
$_GET['vendor_id']
Though you may want to validate the vendor id in the PHP if it's going to be used to query your db.

Accessing hidden input array using ajax / php

I have a form that contains several of the following types of elements
<input type="hidden" name="selected_models[]" value="1">1</td>
<input type="hidden" name="selected_models[]" value="2">2</td>
<input type="hidden" name="selected_models[]" value="3">3</td>
<input type="hidden" name="selected_models[]" value="4">4</td>
I am trying to pass this array, along with all my other form data to a jQuery $.post function, but I can't access the data in php correctly.
I've tried to pass it using the following (jQuery):
var _data = { models: $('input[name="selected_models[]"]').serialize() }
and then access it in PHP using:
$models = $_POST['models'];
just for the purpose of trying to check the data, I pass this variable to the ajax response, and log it back to the console using:
Php
$response = jseon_encode(
array(
'success' => true,
'models' => json_encode($models)
)
);
and
JS
console.log(JSON.parse(response.models)
Which outputs the following:
selected_models%5B%5D=37&selected_models%5B%5D=51&selected_models%5B%5D=57
so, honestly now I'm just stuck with how to loop through those values in php so I can actually do something with them. Ideally, I would be able to do something like:
Php
foreach ( $models as $model ) {
$id = $model.selected_models
// Do more stuff
}
But this isn't working. What am I doing wrong?
I ended up solving this in jQuery and passing a parsed value to PHP, instead:
var uniqueModels = [];
if ( document.getElementById('acInheritFromVehicle').checked ) {
var models = jQuery( 'input[name="selected_models[]"]:checked');
var modelIDs = [];
//console.log(models);
models.each(function() {
if( jQuery.inArray( ))
modelIDs.push( jQuery(this).val() );
});
uniqueModels = unique(modelIDs);
uniqueModels = jQuery.grep( uniqueModels, function(value) {
return value != 0
});
//console.log(uniqueModels);
}
You were doing it correctly, just some minor PHP tweaks and you would have got it. Once you serialize your data and sent to PHP you can always check what that array looks like by using print_r($models) function.
To loop through your $models array, do the following:
foreach($models as $model) {
echo 'Value of hidden input is: ' . $model;
echo '<br />';
}
$model will represent an actual value received through PHP request. Check out this example

Dynamically add Yii form elements with jQuery

I have a problem integrating Yii and jQuery when trying to dynamically add fields generated by Yii to my form.
Namely, statically I use this code to have a dropdownlist on my form:
echo $form->label($model,Yii::t('candidates', 'Contact type'));
$options = CHtml::listData(HrpContactTypes::model()->findAll(),'id','type');
$ct = array();
$b=1;
for($i=0;$i<=count($options)-1;$i++) {
$ct[$b] = Yii::t('candidates', $options[$b]);
$b++;
}
echo $form->dropDownList($model,'contact_type_id',$ct,array('class'=>'form-control'));
and I use this code to have a text-input on my form:
echo $form->label($model,Yii::t('candidates', 'Contact')); ?>
echo $form->textField($model,'contact', array('required'=>'required', 'class'=>'form-control' ));
Then, I use this code to dynamically add elements to my form:
$('#addContact').click(function() {
$('#row').append(
'<br><div class="col-md-6">contact type</div><div class="col-md-6">contact</div>'
);
return false;
});
MY QUESTION IS: HOW TO DYNAMICALLY ADD YII DROPDOWNLIST AND YII TEXT-INPUT WITH THE HELP OF JQUERY?
At first please pay attention on coding.
Second parameter of CActiveForm::label() must be attribute, and translate it you must in your model class (overriding method attributeLabels()), not in form:
public functions attributeLabels() {
return array(
'candidates' => Yii::t('candidates', 'Contact type'),
ATTRUBUTE_NAME => ATTRIBUTE_LABEL
);
}
Read about loops in php. Instead of declaring additional varaible $b you can use loop varaible $i, also you get values from $optios starting from 1, so your last element of $ct always null, I think you want to write this:
$options = CHtml::listData(HrpContactTypes::model()->findAll(),'id','type');
$ct = array();
for($i=0; $i<count($options); $i++) {
$ct[$i+1] = Yii::t('candidates', $options[$i]);
}
Thanks.

Passing an argument to a Javascript function through PHP

i'm using PHP to get some values from the Database & echo html code. So i have something like this..
$values = $params->get('something');
And then i want to pass $values in to the doSomething() function of javascript.
echo('<html>');
echo('<head>');
echo('</head>');
echo('<body>');
echo('<button type="button" onclick="doSomething()">');
echo('</button>');
echo('</br>');
echo('</body>');
echo('</html>');
Any suggestions? :D
You can do this -
echo('<button type="button" onclick="doSomething(\'' . $values . '\')">');

Easy iteration for php in class function

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 :)

Categories

Resources