On click action not working properly - javascript

My javascript function
function ConfirmDelete()
{
if (confirm("Delete Account?"))
var id= $(this).attr('data-id');
alert(id);
location.href='config-project-delete.php?id='+id;
}
onclick event trigger
<?php
echo "<span onclick=\"ConfirmDelete()\" data-id={$row['project_id']} class='button-content'>
<i class='glyph-icon icon-trash-o float-left'></i>
Delete
</span>
</div>
</a>
</li>"; ?>
I cant able to get the data-id.It keep saying undefined.Any help would be appreciated.

In your example, this doesn't refer to the element where you called the function, but rather refers to the owner of the function (which, as you've defined it, looks like it's in the global scope). So you'd have to call the function with the parameter of the value you want, then use it within the function, as such:
<?php
echo "<span onclick=\"ConfirmDelete(\$(this).attr('data-id'))\" data-id={$row['project_id']} class='button-content'>
...
(The $ is escaped because you're echoing it with PHP).
And then your function would look something like this:
function ConfirmDelete(data_id)
{
if (confirm("Delete Account?"))
var id= data_id;
alert(id);
location.href='config-project-delete.php?id='+id;
}
If you aren't using the data-id attribute anywhere else and only for this purpose, you can simplify the HTML side as well by passing the value directly:
<?php
echo "<span onclick=\"ConfirmDelete('{$row['project_id']}')\" class='button-content'>
...
Note that I haven't tested any of this code, and when mixing HTML, JS, and PHP, it can be easy to screw this up (at least for me), so tweak the above as needed.

try this
<span onclick="javascript:deleteConfirm('<?php echo 'config-project-delete.php?id='.$row['project_id'] ?>');" deleteConfirm class='button-content'>
javascript
function deleteConfirm(url)
{
if(confirm('Do you want to Delete this record ?'))
{
window.location.href=url;
}
}

You have to pass the triggering object to your function.
function ConfirmDelete(triggering_object)
{
if (confirm("Delete Account?")) {
var id= $(triggering_object).attr('data-id');
alert(id);
location.href='config-project-delete.php?id='+id;
}
}
And add the 'this' to your object:
echo "<span onclick=\"ConfirmDelete(this);\" data-id={$row['project_id']} class='button-content'>";

Although Nick Coons answer is an easier way to do this (pass the variable to the function), to get the results you first asked about using the data attribute method, you have to pass event to the function to get the proper node. http://jsfiddle.net/2t4hK/
function ConfirmDelete(e) {
var target = $(e.target);
if (confirm("Delete Account?")) {
var id = target.attr('data-id');
alert(id);
//location.href='config-project-delete.php?id='+id;
}
}
<span onclick="ConfirmDelete(event)" data-id="1" class="button-content">Delete</span>
<?php
echo '<span onclick="ConfirmDelete(event)" data-id="'.$row['project_id'].'" class="button-content">';
echo '<i class="glyph-icon icon-trash-o float-left"></i>Delete</span>';
?>
Also, in your code, I suggest you wrap the value for data-id inside of quotes.

Related

How to call a function in a php file using jquery load?

I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>
Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}

Unable to get element id dynamically in javascript

I have a list of students that I am looping through and adding to my page. Each student has a unique ID, and when getStudentInfo is invoked, it does something with the id. The problem is that whichever student I click, I get back the same id, belonging to student1.
Where am I going wrong?
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo()"
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
js:
function getStudentInfo() {
var studentLink = $('.student-name-btn').attr('id');
console.log(studentLink);
}
Your code is selecting all the buttons on the page with that class and than reads the id of the first one in the list. You are not limiting it to the one that was clicked.
What most people would do is add events with jQuery and not inline.
//needs to be loaded after the element or document ready
$(".student-name-btn").on("click", function() {
console.log(this.id);
});
For yours to work, you would need to pass a reference to the button that was clicked.
onclick="getStudentInfo(this)"
and than change it to use the node passed in
function getStudentInfo(btn) {
var studentLink = $(btn).attr('id');
console.log(studentLink);
}
You can pass the reference to the element being clicked on the onclick event
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo(this)" // << added this which refers to the input
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
And then use that to fetch the id in the js
function getStudentInfo(el) {
var studentLink = $(el).attr('id');
console.log(studentLink);
}
Don't use inline events - there's no need to clutter up the HTML with that. You have a common class on your element, so just make a jQuery handler and use an instance of this
$('.student-name-btn').click(function() {
var id = this.id;
});
Like #epascarello alluded to, you are not selecting the button that was actually clicked. What you should do is have your event handling in your JS, not in the HTML so you can see better how it works and use the this keyword within the closure to reference the clicked button.
$(document).on('click', '.student-name-btn', function(evt) {
// Prevent default if trying to do your own logic
evt.preventDefault();
// Need to use the "this" keyword to reference the clicked element
var studentId = $(this).attr('id');
console.log(studentId);
});
You can do this without inline JavaScript and since you're using jQuery drop the onClick() and the form element:
echo '<tr>';
echo '<td id="'.$student['student_permalink'].'" >
'.$student['student_permalink'].'
</td>';
You also need to quote the identifier in the array variable, 'student_permalink'.
The jQuery will be this:
$('td').click(function() {
var studentLink = this.id;
console.log(studentLink);
});

echo-ed HTML Element from PHP is not read in JAVASCRIPT

so i have some html elements generated from PHP since most contents are fetched from the database
i.e.
<?php
...
while($row = $sqlQry->fetch_object()) {
echo "<li class = 'lstOption' id = 'opt$row->name' data-value = '$row->total_count'>
<h3>$row->given_reference<h3>
</li>";
}
...
?>
and this is a sample structure based on my javascript
<script>
$("ul li").click(function(){
alert($(this).data('value'));
});
</script>
but if i inject an onClick= attribute while inside the echo. the script executed properly. what i need is for the script to work with the echo-ed html elements from php.
Try using variable interpolation syntax, i.e. wrap your variables around curly braces
"{$var}"
take note that you have to use double quotes("") for this
"<li class = 'lstOption' id = 'opt{$row->name}' data-value = '{$row->total_count}'>
<h3>{$row->given_reference}<h3>
</li>"
Just put your script inside document ready as below. That will fix the issue
$(document).ready(function(){
$("ul li").click(function(){
alert($(this).data('value'));
});
});
You should try the code binding with the $(document).ready() method.
This is because once your all DOM elements are ready then after code bind with document ready will appear.
so do the following code.
<?php
...
while($row = $sqlQry->fetch_object()) { ?>
<li class = 'lstOption' id = 'opt<?php echo $row->name?>' data-value = '<?php echo $row->total_count?>'>
<h3><?php $row->given_reference?><h3>
</li>";
}
<?php ...
?>
<script>
$(document).ready(function(){
$("ul li").click(function(){
alert($(this).data('value'));
});
});
</script>
or write as follows
<script>
$(document).ready(function(){
$("ul li").on("click",function(){
alert($(this).data('value'));
});
});
</script>
You can try to select by id and use the on() method:
$(document).on('click', '[id^="opt"]', function () {});
Works only if you don't have anything else with id starting with "opt".
In my opinion id selectors are always stronger than any other selector.
The on() method is also preferable as it is also valid for dynamically generated elements (in case of adding content via ajax for example)
Also if you want to print the actual value and not the formula in your data-value, your quotes are wrong, here is the correct version :
while($row = $sqlQry->fetch_object()) {
echo "<li class = 'lstOption' id = 'opt".$row->name."' data-value = '".$row->total_count."'>
<h3>".$row->given_reference."<h3>
</li>";
}
try like
$(document).ready(function(){
$("ul li").on('click', function(){
console.log($(this).data('value'));
});
});
Since your html elements are generating dynamically you have to use on()

javascript variable to use insde html onclick

i have this javascript variable
<script>var onclick_url_bid_o_matic = $(this).parent().find('.do_bid').data('urll');</script>
and this html button
<a style="cursor:pointer;" class="bido blu" onclick="+onclick_url_bid_o_matic+" id="btn-bidoo">Activate</a>
the javascript variable points to this:
data-urll="<?php
if($whim_available >= 1)
{
if($details['reward_type']=="play_to_win")
{
echo '$.auctions.bid(' .$details['id'] . ', $(this), event);';
}
if($details['reward_type']=="whim_it_now")
{
echo '$.auctions.claim(' . $details['id'] . ', $(this), event);';
}
}
else
{
echo "$.auctions.alert('You do not have sufficient Loots');";
}
?>"
but the button's onclick doesnt work. and i believe i am not passing the javascript variable right. any help?
Create a javascript function:
function setVariable(){
var onclick_url_bid_o_matic = $(this).parent().find('.do_bid').data('urll');
}
And call that function in your onClick like so:
<a style="cursor:pointer;" class="bido blu" onclick="setVariable()" id="btn-bidoo">Activate</a>
To test if the variable holds the value needed and that the funtion correctly executed, put it to the console:
console.log("Activate link clicked: " + onclick_url_bid_o_matic);

How to compose multiple $(document).ready() function

I have a function which creates dynamic <select>. I have to make it a multiple select options, so I have to initialise it as well.
The function is called multiple times; here's the function:
function renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for)
{
echo '<script>
$(document).ready(function()
{
$("#zoneFilter_criteria_'.$for.'_'.$r.'_'.$c.'").multiselect({
includeSelectAllOption: true,
enableFiltering: true,
enableCaseInsensitiveFiltering: true,
maxHeight: 150
});
});
</script>'.'<div class="time_zone_list"><select name="rules['.$r.']['.$c.']['.$for.'_timezone]" class="input_field zonefield" id="zoneFilter_criteria_'.$for.'_'.$r.'_'.$c.'" style="width:30%; margin-right:5px; float:left;">';
foreach ($this->timezoneArrayNotDefault as $k => $val) {
$selected = '';
$val_array = explode(")",$val);
if (isset($val_array[1]) && trim($val_array[1]) == trim($filterKey)) {
echo $selected = SELECTED;
}
echo '<option value="' . $val . '"' . $selected . '>' . $val . '</option>';
}
echo '</select></div>';
}
Now, as you can see, the html is made as php string (my client stated that by this way, the html loads faster so he used this technique, and U can't convince him to alter to another way.
Now let's come to the point: if the function is called multiple times, then it's also causing multiple $(document).ready(function(){});
Is there any way, that I can have only $(document).ready(){}); and initialise the multiple drop-downs in some other way??
Set a flag variable.
$firstCall = TRUE;
renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for, &$firstCall);
And check it:
function renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for, &$firstCall)
{
if($firstCall) {
echo '<script> $(doucment).ready(function() { ... ';
//your document.ready here
$firstCall = FALSE;
}
// your other stuff here
}
UPD: The better solution probably is to make single function wich echoes your document.ready, and call it once.
Here is an example of just rebinding your code when you add the new html.
http://jsfiddle.net/64e41LL9/
Html
<div id="container">
<button class="button-item">I am a button</button>
</div>
<br/>
<button id="add-html" >add button</button>
<br/>
<button id="rebind" >rebind</button>
Jquery
$(document).ready(function(){
//function to rebind
function rebind() {
$('.button-item').click(function(){
alert("Im binded");
})
}
//initial bind on page load
rebind()
//adding new html thats unbinded
$("#add-html").click(function(){
$("#container").append('<button class="button-item">I am a button</button>')
})
//calls function to bind new html
$("#rebind").click(function(){
rebind()
})
})
So essential what is happening here is when the page loads you will initially bind the alert code to the button but when you append new html to the page you will see the new button won't fire the on click event even though it has the same class. This is because its not binded. Once you click that rebind button it will rebind all the buttons with that class(button-item). You can use the same concept but it will call the rebind function everytime you add your dynamic html.

Categories

Resources