How can I use JS attribute for links in PHP? - javascript

trying to understand.
I have a js code,
$(document).on('click','.plan_btn',function() {
$('.ui-dropdown').removeClass('active');
var tarifplanid=$(this).attr('data-tarifplanid');
$('.planid').text(tarifplanid);
$('.add_plan').addClass('show');
});
I have a php code, with button, where I pass attr.
<button type="button" class="ui-component ui-button plan_btn" data-tarifplanid="<?php echo($plan->plan_id)?>">Select</button>
So, by pressing Select button, I will have an planID, which is 2 or 3 stored in .JS
Then, as test, I have the following code:
<?php
$test = <<<EOD
<span class="planid"></span>
EOD;
echo $test;?>
Question is:
echo returns ID, 2 or 3, depends on which item I pressed "Select"
But, when I trying to add a link with $test, it will as <span class="planid"></span>
Why? I assume it should be https://localhost/2 but I have https://localhost/<span class="planid"></span>
Thank you!
I'm not a developer, just browsing and a learning a bit

Related

Check a button has been clicked in JS and then do something in PHP

I'm working in PHP and I have this button, than when clicked, should print something.
I've (unsuccessfully) tried the following:
<?php
echo '<button type="submit" id="enviarRecibos" class="btn btn-primary float-end">Imprimir Lista</button>';
?>
<script>
if(document.getElementById('enviarRecibos').clicked == true){
<?php
echo $listaDatos;
?>
}​;​
</script>
What am I doing wrong?
Note: $listaDatos is a variable that's already in the page with some content in JSON format.
I'm not sure i've well understand what you exactly want, but anyway your javascript script need improvement :
<?php
echo '<button type="submit" id="enviarRecibos" class="btn btn-primary float-end">Imprimir Lista</button>';
?>
<script>
document.getElementById('enviarRecibos').addEventListener('click', function (){
document.getElementById('enviarRecibos').insertAdjacentHTML('afterend', '<?php echo $listaDatos;?>') ;
}) ;
</script>
First the best way to track click on an element in javascript is with addEventListener.
Next, you want load content, ok, but you need to define the position / DOM element where the content need to be loaded. You can use "insertAdjacentHTML", an usefull function putting HTML content next to an existing element (here your button).
Take care "<?php echo $listaDatos;?>" doesn't contain a quote ' and return a valid HTML string.
AS #brombeer just told you, PHP is a server side language while Javascript is client side. PHP can only help you prepare the raw file code.

Uncaught SyntaxError: Unexpected token < while calling cakephp select form directly in javascript

i have a basic problem related to javascript and PHP,
I am trying to include a select option in javascript. For debug purpose I did the same with input text box and it works fine. As soon as i load the options using cakephp form helper through a list of array passed from controller i get this above error. I will explain what i am trying to achieve with code example:
i have a form and a div tag where i want to append a select options using javascript, jquery in my case.
my view file:
<?php echo $this->Form->create('GenericDrug'); ?>
<div class="voca">
</div>
<button type="button" class="btn btn-success btn-add" >
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Add more
</button>
<?php echo $this->Form->end(); ?>
Values passed from my controller:
public function admin_edit($id = null) {
//other codes
$this->set(compact('drugClasses','genericDrugs','drugClassList'));
}
these classes are modeled using ORM
Now i want a jquery/javascript function such that it will append my select option in div tag classed as 'voca'.
So far i have done:
In my view file:
<script type="text/javascript">
var i = <?php echo $this->Form->input('drug_class_id'); ?>
$(function()
{
$(document).on('click', '.btn-add', function(e)
{
$(i).appendTo( ".voca" );
</script>
input drugclassid will generate list of options for select. However, I tried a lot of fiddling around but cant find a solution. The page does get rendered at the backend and sends all the option data, however i get a javascript error message
Click to see error message
Try it
<script>
var myvar = <?php echo json_encode($this->Form->input('drug_class_id')); ?>
</script>

Show PHP object data inside javascript

I know there have been just too many questions so far asking about PHP and JS working together...I went through them, but I cannot find an elegant solution for my use case.
What I currently have is following PHP code in my webpage that fetches product info and shows it:
<?php
$p= new Product($prodId);
$p->getProductInfo();
//now show product info...
echo "<div>Product Name: ".$p['productName']."</div>";
echo "<div>Product Rating: ".$p['productRating']."</div>";
//etc...
?>
Now what I have been asked to do is instead of showing this data directly in the page, I should show it only when a button is clicked. And I should show it inside a bootbox modal dialog box
So I did:
<span id='prod-details'> View Product Details </span>
<input type='hidden' id ='prod-id' value='<?php echo $p['productId'];?>'>
And in my jquery file I have:
$('#prod-details').click(function(
var prodId = $('#prod-id').val();
productDetail = "Product Details for "+prodId;
//how do I get rest of product details from PHP object?
bootbox.alert(productDetail);
));
Any help is very much appreciated...I have been trying hard to make this work.
What I normally do is echo the information inside the bootbox modal div and just hide/show the bootbox modal div with an onClick function
you can either put it in your html file like this:
<script>
var productName = <?php echo $p['productName'];?>;
</script>
or exactly like you did with the product id, just put all the data you need inside the input div (or any oher div releated to that product)
<input type='hidden' id ='prod-id' value='<?php echo $p['productId'];?>' productName='<?php echo $p['productName'];?>'>
and then using jquery get that data like you got the id
var prodName = $('#prod-id').attr('productName');

PHP, Javascript Help Required

I am new to this forum. I have been developing a interface and have got stuck with PHP and Javascript.
My Site has 3 Buttons
<button id="ProjectSource" class="testbutton" onClick="AddNewProject(this.id);">Project Source</button>
<button id="SelfCons" class="testbutton" onclick="AddNewProject(this.id)">Self Cons</button>
<button id="Currency" class="testbutton" onclick="AddNewProject(this.id)">Currency</button>
These buttons are sent to a Javascript function on the same page which will store the button ID in a variable, which is later used in another PHP.
Now I have an Select Box in the same page and I get the data from the database using PHP.
<select size="10" id="Database" onClick="ClearAdd()" >
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['ProjectSource'])?>" >
<?php echo($row['ProjectSource']) ?>
</option>
<?php
}
?>
</select>
My First Problem is
If you see I am currently using $row['ProjectSource']), But what I need is the ID of the buttons which corresponds to the field name in the database.
My Second Problem is
The Select functions loads when the page loads, I want that to refresh when I click on any buttons.
Thanks in Advance for your help!
use mysql fetch query
For example:
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
}
For your second Problem you should implement ajax. Either using javascript or jquery.
Regarding first problem it is not clear What are the field names and how button Id is implemented? It would be better if you post some code
Can you implement some kind of mapping of your fieldName to your buttonId using associative array? like array("fieldName1"=>"id1",....)

PHP link written into page not being retrieved by a JAVASCRIPT function

I'm writing on a page the following code with PHP. This code creates a A HREF link with the ID equal to $intIdType, which is the value of the PRIMARY KEY in a database, and $count gets the amount of records per category on the database. All of this is inside a WHILE that reads each record and writes on the PAGE the results
echo "<a href='#' id='$intIdType'>";//Starts creating the link
echo "$intIdType -";
echo $arrBusinessTypes["business_Description"];
echo "(";
echo " $count1 )"."</a>";
Now, after the results are on the page it will look like this:
$intIdType $arrBusinessTypes $count
--------------------------------------------
1 -Auto Sales ( 1 )
2 -Auto Repair ( 1 )
5 -Web Desig & I.T. Services( 2 )
6 -Computer Shop ( 1 )
The above result displays each rown as a link where I can click on it, but nothing happens. Even just a simple Alert in javascript does not show up. It seems that it never reaches even the Javascript at all.
What I need now is to retrieve that PHP generated code on the page by a Javascript file, that will allow me to use the hiperlink generated by PHP into the .HTML page
It works if I write directly into the page what PHP is suppose to write. I wonder if this happens because Javascript can not read posted data from PHP into the page.
The Javascript File looks like this:
window.onload=post_result
function post_result() {
$("#1").click(function() { //This is the HREF ID that is written by PHP into the page
$('#list_results').load("results.php");//This seeks to run a PHP file in a DIV
$('.title').text('Listing Categories');//This just replaces the Title in the page
})
I'm just a beginner trying. Thanks for any help.
echo "<a id='$intIdType'>";//Starts creating the link echo "$intIdType -";
echo "$intIdType -";
echo $arrBusinessTypes["business_Description"];
echo "("; echo " $count1 )"."</a>";
just remove href attribute and try
Remark #1: quote custom data when outputs it to HTML:
echo $arrBusinessTypes["business_Description"]; must be
echo htmlspecialchars($arrBusinessTypes["business_Description"]);
Remark #2: you don't need window.onload handler here. In this piece of code you select complex way to do simple thing. Why do not write direct onclick handler? Write function loading some data depending of parameter and do something like:
$htmlspecialchars = function($s){return htmlspecialchars($s);};
echo <<<HTML
<a href='#' id='$intIdType' onclick='loadInfo($intIdType)'>
$intIdType -{$htmlspecialchars($arrBusinessTypes["business_Description"])} ( $count1 )
</a>
HTML;
(converted to heredoc to make HTML more clean)

Categories

Resources