function is not working if I put this into js folder - javascript

I have a add.ctp file, where I can add a multiple rows, and if I put addNumber function to app/webroot/js, then its not working, why?
My view file (add.ctp)
<table id="mytable">
<tr id="number0" style="display:none;">
<td><?php echo $this->Form->button(' - ',array('type'=>'button','title'=>'Click Here to remove this number')); ?></td>
<td><?php echo $this->Form->input('lisanumbrid', array ('name'=>'data[Kontaktid][lisanumbrid][0]')) ?></td>
</tr>
<tr id="trAdd"><td> <?php echo $this->Form->button('+',array('type'=>'button','title'=>'Click Here to add another number','onclick'=>'addNumber()')); ?> </td><td></td><td></td><td></td><td></td></tr>
</table>
<?php
echo $this->Form->end('Lisa');
?>
Adding multiple rows function(addNumber.js) is here app/webroot/js:
var lastRow=0;
function addNumber() {
$("#mytable tbody>tr#number0").clone(true).attr('id','lisanumbrid'+lastRow).removeAttr('style').insertBefore("#mytable tbody>tr#trAdd");
$("#lisanumbrid"+lastRow+" button").attr('onclick','removeNumber('+lastRow+')');
$("#lisanumbrid"+lastRow+" input:first").attr('numbrid','data[Lisanumbrid]['+lastRow+'][lisanumbrid]').attr({'id':'numbridlisaNumber'+lastRow,'name': 'data[Kontaktid][lisanumbrid]['+ lastRow +']'});
lastRow++;
}
function removeNumber(x) {
$("#lisanumbrid"+x).remove();
}
Jquery file is in the same folder like a function, and its echoed in C:\wamp\www\cakephp-2.5.6\app\View\Layouts\default.ctp
echo $this->Html->script('jquery-2.1.1.min.js');
If I put this addNumber function into add.ctp file and put into add.ctp
<?php echo $this->Html->script(array('jquery-2.1.1.min.js'));?>
then its working nice, put I dont want these into add.ctp file.
Thanks for helping !

Solution
Added <?php echo $this->Html->script('addNumber'); ?> in to add.ctp file, after </table>

Are you calling addNumber.js in your add.ctp?
You could call this js file in app\View\Layouts\default.ctp and then
echo $this->Html->script(addNumber.js);
or you can create a script tag inside add.ctp calling it:
$.getScript('/epedidos/app/webroot/js/addNumber.js');
By the way, check in your console on firebug (pressing F12 on your keyboard) if the error calling this function is not defined.

You have to add all javascript's files used in your view in the working order using script method of Html object in your header section or at the end of your ctp file.
For example:
I will suppose that you have not added jquery and your addnumber before, so at the end of your ctp file:
<?php echo $this->Html->script(array('jquery','addNumber')); ?>
Regard the order, i.e jquery must be before addNumber and both of them must be in webroot/js/

Related

How do I add a php variable to a onclick function argument?

Beginner JS here.
I am trying to add a PHP variable to a Javascript onclick function. I converted the PHP variable to a JS variable just fine. However, when adding the JS variable to the function I'm not receiving the desired output. What am I doing wrong?
<script>
js_logo_number = "<?php echo $logo_number; ?>";
</script>
<img src='<?php echo $image1[0]; ?>' onclick="openModal();currentSlide(js_logo_number)">
You can do like this :
<img src='<?php echo $image1[0]; ?>' onclick="openModal();currentSlide(<?php echo $logo_number; ?>)">
This code works for me. Be sure you use a let or const (or the outdated var) prefix to declare js_logo_number a new variable. Also make sure that $logo_number is set like this:
<script>
let js_logo_number = <?php isset($logo_number)?$logo_number:null; ?>;
</script>
Then make sure you convert it to an integer in Javascript, if that's how you want to use it:
function currentSlide(num){
console.log('currentSlide fired', parseInt(num));
}
let js_logo_number = "5";
function openModal(){
console.log('openModal fired');
}
function currentSlide(num){
console.log('currentSlide fired', parseInt(num));
}
<img src='https://placekitten.com/200/200' onclick="openModal();currentSlide(js_logo_number)">
When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
See: PHP tags
1) echo
<?php echo 'if you want to serve PHP code in XHTML or XML documents, use these tags'; ?>
Solution:
<img src='<?php echo $image_src ?>'
onclick="openModal();currentSlide(<?php echo $logo_number ?>)">
2) Short echo
You can use the short echo tag to <?= 'print this string' ?>.
It's equivalent to <?php echo 'print this string' ?>.
Solution:
<img src='<?= $image_src ?>'
onclick="openModal();currentSlide(<?= $logo_number ?>)">
3) If short_open_tag is enabled
<? echo 'this code is within short tags, but will only work '
.'if short_open_tag is enabled'; ?>
Solution:
<img src='<? echo $image_src ?>'
onclick="openModal();currentSlide(<? echo $logo_number ?>)">
See: PHP tags

Cannot echo .load function

For some reason this code doesn't work. Adding \ to the front of the $ doesn't change anything. Can anyone see the problem?
$commentid = 2; //for example
echo "<script>";
echo "<div id = 'commentinput".$commentid."'>";
echo "</div>";
echo "$('#commentinput".$commentid."').load('editcomments2.php')";
echo "</script>";
Do it like this:
echo '$("#commentinput'.$commentid.'").load("editcomments2.php")';
I'd suggest not using echo to output HTML (in most cases anyway), but closing the PHP tag instead.
This becomes (edited with a loop example, see comments below):
<?php while ($commentid = $dbObject->dbMethod()): ?>
<div id="commentinput<?= $commentid ?>">
</div>
<script>
$('#commentinput<?= $commentid ?>').load('editcomments2.php');
</script>
<?php endwhile ?>
Note that in this case, the <script> portion should probably be outside of the loop, with a jQuery selector matching all the comment inputs.
So besides all of the other answers, I found another solution to!
When echoing out js code, like
echo '$("#commentinput'.$commentid.'").load("editcomments2.php")';
//and
echo "alert('stuff')";
it might then print it out like: $("#commentinput2").load("editcomments2.php")alert('stuff') and the code will get confused. So lastly I need to added a semicolon to prevent the program from reading all my code as just 1 line:
echo '$("#commentinput'.$commentid.'").load("editcomments2.php")';

How I create a Read More button inside a table?

<?php $counter = 0 ?>
<table>
<?php foreach($attributes as $a): ?>
<tr>
<td><?php $a['name']?></td>
<td><?php $a['Price']?></td>
</tr>
<?php $counter++;
if ($counter > 3) ?> <!-- What to do here? -->
<?php endforeach; ?>
</table>
In a PHP Block like this, I would like to got a Read More button after three tr elements, and when I click the button show all the rest of elements...
Something to do with PHP?
No, it has nothing to do with php. You need JavaScript to implement this if you don't want to reload the whole page.
In PHP you could print the short and the long version into separate divs and then use the following JS-Code on the View-More-Button:
document.getElementById("shortId").style.display = "none";
document.getElementById("longId").style.display = "block";

Targeting dynamic id's within a javascript file

In a php file I have tags with dynamic id's.
Example:
<ul id="<?php echo 'ul_'.$xx; ?>">
<li id="test_li">...</li>
</ul>
In a separate JavaScript file I am wanting to use the load function and target that div.
$('<?php echo 'ul_'.$xx; ?>').load('../includes/myphpfile.inc.php #test_li');
My question is, how could I load that php within a JavaScript file?
Notes:- The reason I have it set up this way is due to looping multiple ul's. I just want my ajax file to refresh the li's within the specific ul I am inside of.
Edit: If I use classes instead of Id's it adds my newly inserted rows into all of the ul's with the same class. If I use a plain Id it only works on the first ul. Further explaining why I need to target the way I am.
Unable to find a solution using the path I was on, I looked for alternate methods. Worked out I could add the event in the php file on the submit form button click.
The reason I wasn't using this method at first was because the code was running before it submitted to the DB and therefore was always behind in relation to the new data being submitted.
To my surprise I fixed this by just duplicating the line of code.
<script>
$("<?php echo '#enter_submit_button'.$linkid ?>").click(function(){
/*1*/
$('#<?php echo 'ul__'.$linkid; ?>').load('../includes/pursuit.inc.php <?php echo '#li__'.$linkid; ?>');
$("<?php echo '#insert_new'.$linkid; ?>").fadeOut();
/*2 with delay*/
$('#<?php echo 'ul__'.$linkid; ?>').delay( 800 ).load('../includes/pursuit.inc.php <?php echo '#li__'.$linkid; ?>');
});
</script>
I honestly couldn't say exactly why this works but the logic behind trying the method came from hoping that the double load would pick up the latest submission.
The simplest answer would be to put your JavaScript code into the PHP file inside
<script></script> tags, i.e, just before closing your <body> tag, do this:
<script type="text/javascript">
$('<?php echo 'ul_'.$xx; ?>').load('../includes/myphpfile.inc.php #test_li');
</script>
But if you must use an external js file, then you could do this:
Create a (.php) file and write:
<?php
header("Content-type: application/javascript");
?>
// your js code with php inside (as you would do in HTML)
var othervar='<?php echo $phpVar; ?>';
//<?php //some php ;?>
Then, in your main (html/php) file, put in:
<script src='myjs.php' type='application/javascript'></script>
Hope that solves it.

Add XHR to a Javascript Function

When I execute the following code, a GET message appears in the Firebug Console however the variable is undefined, and I think that is due to the scope of the variable being limited to the function only.
My goal is to be able to click the table row, and upon clicking the table row, fetch some data from the server related to the record in the table, and then populate part (not all) of a web form, which I will then add more data to, and then submit the form (see image).
Here is the Javascript function which defines a variable called $id as the given rows' data-attribute ('recordID') which itself was been passed into the <tr> tag when the table was generated.
Javascript:
$(document).on('click', 'tr', function() {
//Get the ID from the row clicked
var $id = $(this).data('recordId');
//short-hand
$('#section2').load('data_entry_form.php?id='+id);
});
PHP snippet that includes the data-attribute:
<table = "all_aifs">
<tr>
<th><b>Document ID</b></th>
<th><b>Pubco Name</b></th>
<th><b>Filing Date</b></th>
<th><b>PDF</b></th>
</tr>
<?php foreach($result as $index => $row) : ?>
<tr data-recordId="<?=$row[fee_source_id];?>"
class="<?=$row["match"] ? "match" : "";?>">
<td><?php echo $row[fee_source_id]; ?></td>
<td><?php echo $row[company_name_per_sedar]; ?></td>
<td><?php echo $row[document_filing_date]; ?></td>
<td></td>
</tr>
<? endforeach;?>
</table>
Question: How can I have my web form contain some data related to the row I clicked? I think I need to use AJAX. Also, why is the variable "undefined" in the Console? I think I need it to be defined as the $id variable (which is the recordId).
The variable id is undefined because you never have defined it.
You only defined $id not id.

Categories