To start with this. I have an associative array named $body (PHP).
Let's say I want to get the value of $body[1] or $body[2], depending on the id of an element.
So here's my code.
$(document).ready(function() {
$('.messages').on('click', function() {
var id = $(this).attr('id');
$('#generic-modal-title').html('Message Preview');
$('#generic-modal-body').html('" . $body[-concatenate id here-] . "');
});
})"
What I tried doing (doesn't work):
$('#generic-modal-body').html('" . $body["id"] . "');
Check this out i have tested this working fine as you required
<?php $body = array(0 => "content") ?>
<script>
$(document).ready(function() {
var id = 0;
<?php echo "var body = " . json_encode($body) .";"; ?>
$('#generic-modal-body').html(body[id]);
});
<div id="generic-modal-body"></div>
Related
I have created a list, generated from a query, that works (no problem here).
What i would like to do is to trigger an event (probably with jQuery, that I know little about) that would set a php variable.
Let's say I have a table with two columns, 'column 1' and 'column 2'.
The list has various links with the valor of 'column 2' displayed on them.
I want that, as you click to one of those links, you could set a valor to a variable that equals to the valor in 'column 1' of that row.
This is what I wrote in my index page:
<div class="example">
<?php
$test = new Test();
$list = $test->getValors($user_id);
echo '<div id="mylist">';
foreach ($list as $element) {
echo '' . $element->COLUMN2 . '';
}
echo '</div>';
$variable = ?;
?>
</div>
I have nothing in my JavaScript file about it because I don't know how to begin.
Can you give me some directions?
EDIT
I resolved partially, even if this is not complete, i include my new code:
index.php
<?php
$test = new Test();
$list = $test->getValors($user_id);
echo '<div id="mylist">';
foreach ($list as $element) {
echo '' . $element->COLUMN2 . '';
}
echo '</div>';
$variable = ?;
?>
Javascript
$(document).ready(function () {
$("a.pointer").click(function() {
var variablename = $(this).attr("id");
$.post("ajax/filewithajax.php", {"postname": variablename});
$("#content").load("ajax/filewithajax.php");
});
});
You could put a event onclick on <a> and call a php function in a other page with jQuery (search about ajax). The php function could return a value that you can use in your main page.
I'm trying to add a script element to the HTML from the PHP code and instantly remove it so it won't be visible in the HTML. The script only contains things to execute at the same moment and not functions. Generally, I'm trying to replicate ASP.NETs runat property, so I'll be able to set values of elements (inputs for now) right from the PHP code.
This is what I tried so far (which I found in a different question, with some changes of mine) and it adds the script properly, but won't remove it.
function JSSetValue($id, $value) // Input 'value' only
{
echo '<script>
var input = document.getElementById("' . $id . '");
input.value = "' . $value . '"
</script>';
$html = <<<HTML
...
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$script = $dom->getElementsByTagName('script');
foreach($script as $item)
{
$item->parentNode->removeChild($item);
break;
}
$html = $dom->saveHTML();
}
Thanks for everyone who were trying to help. Anyway, I found a solution to my question, which is this:
function JSSetValue($id, $value) // Input 'value' only
{
echo '<script id="phpjs">
var input = document.getElementById("' . $id . '");
input.value = "' . $value . '";
document.getElementById("phpjs").remove();
</script>';
}
It adds the script and removes it, so it won't be visible when inspecting elements anymore.
I have a data set of items coming from a SQL database. Those items are displayed in multiple divs like:
<?php
$url = 'DataBase';
$json_response = file_get_contents ( $url );
$json_arr = json_decode ( $json_response, true );
for($i = count ( $json_arr )-1; $i > 0; $i--) {
$json_obj = $json_arr [$i];
echo '<div id="MyDIV">';
echo $json_obj ['id'] ;
echo $json_obj ['title'];
echo $json_obj ['article'];
echo '<button id="read_more_btn">Read more</button>';
echo '</div>'
}
?>
My problem is that I cannot handle click events for EACH div, so I cannot identify which item has been clicked. I’ve been searching for a solution for quite a while, but haven’t found anything. So my question is – how can I identify the clicked item?
EDIT
I have no idea how I can dynamically assign an ID to a button
You could use a data attributes (HTML5 assumed) to attach the Id as meta data to your divs. Your PHP (note I am adding data-id attributes):
<?php
$url = 'DataBase';
$json_response = file_get_contents ( $url );
$json_arr = json_decode ( $json_response, true );
for($i = count ( $json_arr )-1; $i > 0; $i--) {
$json_obj = $json_arr [$i];
echo '<div data-id="' . $json_obj['id'] . '">';
echo $json_obj ['id'] ;
echo $json_obj ['title'];
echo $json_obj ['article'];
echo '<button id="read_more_btn">Read more</button>';
echo '</div>'
}
?>
JS - simple click handler attachment, using jQuery .data() [docs] to get data attribute:
$('div').click(function(e) {
var id = $(this).data("id");
alert(id);
});
JSFiddle Demo
How about when creating the html in the php, you echo the id inside the class.
echo '<div id="mydiv-' . $json_obj['id'] . '">';
So now in the html, it's going to look like
<div id="mydiv-1"> ... </div>
<div id="mydiv-2"> ... </div>
<div id="mydiv-3"> ... </div>
etc.
And then in Javascript, you could access them the same way you access any tag.
$('#mydiv-1').click(function(e){
console.log('a div was clicked');
console.log($(this))
});
So in order to assign listeners to each div, you could do a loop
for(var i = 1;$('#mydiv-container').children().length >= i,i++)
{
$('#mydiv-' + i).click(function(){
}
Make sure to add a container for all the divs.
Give each div a unique numeric class, so your jquery will be
$('div').click(function() {
var item_id = $(this).attr("class");
//do stuff here
});
or
$('div').click(function() {
var item_id = this.className;
//do stuff here
});
I am using Codigniter to redo a website. I have the following controller code:
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
foreach ($topics as $val) {
echo "<pre id = \"pre_" . $val['id'] . "\">";
echo $val['formula'];
echo "<br />";
// generate a unique javascript file.
$f = "file_" . $val['id'] . ".js";
if (!file_exists($f));
{
$file = fopen($f,"w");
$js = "\$(\"#button_" . $val['id'] . "\").click(function(){\$(\"#pre_" . $val['id'] . "\").hide();});";
fwrite($file,$js);
fclose($file);
}
echo "<script src=\"file_" . $val['id'] . ".js\"></script>";
echo "<button id=\"button_" . $val['id'] . "\">Hide</button>";
echo "</pre>";
}
}
The basic idea to make an AJAX call to the function to retrieve a list of formulas.
The purpose of the javascript is to be able to hide any of the formulas by
hiding the <pre> </pre> tag that surrounds them The js file (i.e. file_1.js) I generate looks like:
$("#button_1").click(function(){$("#pre_1").hide();});
and the button code is:
<button id="button_1">Hide</button>
The problem is that it doesn't work. The files get generated, but clicking on the "Hide"
button does nothing. The puzzling part is that the exact same code works on the original website where I just make an AJAX call to a PHP file that generates the same code.
Any ideas what could be going on here?
Edit:
On my old website I used:
$query = "SELECT * FROM topics WHERE term LIKE '%" . $term . "%'";
$result = mysql_query($query);
while ($val = mysql_fetch_array($result))
{
echo "<pre id = \"pre_" . $val['id'] . "\">";
etc.
etc.
}
and everything works fine. If I now put the results of the while loop into to an array and then do a foreach loop on that, the results are very intermittent. I'm wondering if the foreach loop is the problem.
i think you can return list buttons in json response
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
$response = array('buttons' => $topics);
header('Content-Type: application/json');
echo json_encode( $arr );
}
so client can parse which button element to be hide.
<script type="text/javascript">
$(document).ready(function(){
$('somEL').on('submit', function() { // This event fires when a somEl loaded
$.ajax({
url: 'url to getTopics() controller',
type : "POST",
data: 'input_data=' + $(this).val(), // change this based on your input name
dataType: 'json', // Choosing a JSON datatype
success: function(data)
{
for (var btn in data.buttons) {
$(btn).hide();
}
}
});
return false; // prevent page from refreshing
});
});
</script>
I have following code i want to show name that is the result of the query.
function lead_delete(del_id)
{
<?php
$lead_name = mysql_query("select lead_name from business_lead where id=" .
$del_id) Or die(mysql_error());
while ($nt_lead_name = mysql_fetch_array($lead_name)) {
$crm_lead_name = $nt_lead_status['lead_name'];
}
?>
var name=<?php $crm_lead_name; ?>;
var confirmation;
var confirmation=confirm("You Really want to Detele Leader "+name );
}
</script>
how can i print the name that get from above query...
You can't use <?php echo $del_id;?> tag in this function (because you may change del_id when call function), but you can create del_id on your page, if you have $del_id php value:
<script type="text/javascript">
var del_id = <?php echo $del_id;?>;
function lead_delete(del_id) {
var confirmation;
var confirmation=confirm("You Really want to Detele Leader " + del_id);
if(confirmation==true)
{
return true;
}
else
{
return false;
}
}
</script>
If del_id is php variable then it should be $del_id instead of del_id
var confirmation=confirm("You Really want to Detele Leader "+ <?php echo $del_id;?>);
As you passing del_id as a function parameter then no need to use php . you can easily get variable like below
var confirmation=confirm("You Really want to Detele Leader " + del_id);
As per updated question:-
var name=<?php $crm_lead_name;?>;
it should be
var name= '<?php echo $crm_lead_name;?>';
And also you want pass del_id lead_delete() function on click event then you have to use AJAX here.
For your reference
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php