First of all I appreciate that all members are trying to help each other.
I want div content by id in my javascript function. I've got function and it works fine with one div and it's content. But now I've got multiple records from DB, so to make div unique I have done following. where $i=$i+1 in while loop
<div id="<?php echo 'fvd'.$i; ?>" class="fake-checkbox star-checkbox"><a id="<?php echo 'tvd'.$i; ?>" onclick="respuestas('<?php echo $user_id1;?>'); return false;" href="#">Add to favourites</a></div>
so here I generate fvd1, tvd1 for next record fvd2,tv2 and so on
Below function process user id and get response by Ajax call and change caption from Add to favourites to Added to favourites and add class name 'checked' which change text color.
function respuestas(str) {
var popID = str;
var gett = document.getElementById('tvd1').innerHTML;
if (gett == 'Add to favourites') {
$.post('personals/addfavourite.php', {
ref: popID
}, function (data) {
if (data == 'no') {
alert('Sorry! something gone wrong!')
} else if (data == 'yes') {
var d = document.getElementById("fvd1");
d.className = d.className + " checked";
document.getElementById('tvd1').innerHTML = 'Added to favourites';
}
});
}
}
Now how can I parse fvd2,tvd2 and so on in this function.
Any help will be much appreciated..Thanks
If you add your $i to the function parameters you can get each grouping dynamically
onclick="respuestas('<?php echo $user_id1;?>',<?php echo $i;?>); return false;"
and
function respuestas(str,num) {
...
var gett = document.getElementById('tvd'+num).innerHTML;
...
var d = document.getElementById("fvd"+num);
...
document.getElementById('tvd'+num).innerHTML = 'Added to favourites';
...
}
You can do
onclick="respuestas(this, '<?php echo $user_id1;?>');
and the first param would be the <a> so you can do
function respuestas(elm, str) {
elm.getAttribute("id");
}
or so. (Not sure about the DOM method name)
BTW why don't you just put the $i to the call as well? Or maybe I didn't get the question right? If not, pls explain.
If you need to access the elements, well then you already have the <a> in elm, and the <div> is in elm.parentElement.
Check HTML DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement
Related
I know ajax is probably the best method to do this.
So, i have this php file which returns a count:
<?php
include('globals.php');
$query = mysqli_query($con, "SELECT COUNT(*) as total FROM solicitacoes WHERE visualizada = 0");
$resultado = mysqli_fetch_array ($query);
$sem_visualizar = $resultado['total'];
return $sem_visualizar;
And i have this on my main page:
<?php
if($_SESSION['funcao_corrente']=="adm" || $_SESSION['funcao_corrente']=="analista"){
echo '<label onclick="mudaIframe();" id="visu" ';
if ($sem_visualizar == 0)
echo 'style="background-color: darkgray; color: black;"';
else if ($sem_visualizar<=5)
echo 'style="background-color: green;"';
else if ($sem_visualizar>5 && $sem_visualizar <= 15)
echo 'style="background-color: orangered;"';
else if ($sem_visualizar>15)
echo 'style="background-color: red;"';
echo '>'.$sem_visualizar.'</label>';
}
?>
Basically it just changes color based on value, but the thing is:
I want it to auto refresh it's own value via the PHP file which returns count, but I have absolutely no idea how can i do this.
I found this code in another answer, but it's not working.
<script>
function get_msg_count(){
$.ajax ({
data: {}, // not really needed
type: 'POST',
url: 'contar_sem_visualizar.php', // page to return your msg count
success: function(response)
{
$('#visu').html(response);
}
}
}); // End $.ajax
} // End Function
// and on DOM ready
$(function(){
// check for new messages every 3 seconds(3000ms)
setInterval(get_msg_count(), 3000)
});
</script>
You can just use $.load to achieve that:
HTML
<span id="count"></span>
jQuery
$("#count").load("contar_sem_visualizar.php");
You need an element to set the count and use jQuery to put the answer in there. The return from your PHP will be retrieved from the jQuery request and ever after a set interval the client's browser will send a request asking for this value, which will be added again to the counter.
You could do that:
function get_count(){
while()
{
$("#counter").load("contar_sem_visualizar.php");
setInterval(3000);
}
}
get_count();
I have a page that receives incoming values from $_POST. One such value is from a drop down selector that allowed the user to select values 0 -10. I want to trigger a JQuery function if a value greater than 0 was selected.
So, if $_POST['DropDownSelection'] > 0, then my JQuery function should run.
How do I trigger the function?
If the function needs to be called in the original page then you can do this -
$('select[name="DropDownSelection"]').change(function() {
var newValue = $(this).val();
if(newValue > 0) {
// your function here
}
});
You don't need PHP, you just need to see if the value changed and then if the value is greater than 0.
If the function is in the page that gets posted to then you could do this -
<script>
var DropDownSelection = <?php echo $_POST['DropDownSelection']; ?>;
if(DropDownSelection > 0) {
// call your function here
}
</script>
Something i like to do for passing a PHP var to Javascript is to put in in an hidden input like that :
<input id="myValue" type="hidden" value="<?= $_POST['DropDownSelection']; ?>" />
The in your javascript :
if(document.getElementById('myValue').value > 0) //Do something
Depends on how your PHP code is connected to the HTML output. In the simplest case where PHP and HTML are in the same file, you could do something like
<? if ($_POST['DropDownSelection'] > 0) { ?>
<script>$.myFunction(...);</script>
<? } ?>
You can do like that.
var x = <?php echo $_POST['DropDownSelection'] ?>;
if(x>0){
jqueryFunction(); // your function call.
}else{
// whatever else you want.
}
Maybe this is oversimplified and a little hacky, but I don't see why this wouldn't work...
<script type="text/javascript">
function overZero() {
// do stuff...
}
<?php
if ($_POST['DropDownSelection']>0) echo('overZero();');
?>
</script>
$(document).ready(function(){
$("#dropdown-id").change(function(){
//check if the value is > 0 and then
// trigger your jquery function()
})
})
However, I want to also call that function when the user lands on the page with
a particular $_POST value for a field
There are 2 easy ways of doing this:
Make global funciton:
ex:
function print(){
alert('hello')
}
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>print()</script>";
}
?>
Or use triger function from jquery:
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>$('#dropdown').trigger('change');</script>";// execute the onchange event(function) attached to the dropdown
}
?>
I am dynamically adding list items to a list in jQuery through an ajax call that is called every second.
Below is the code for the ajax call.
$.ajax({
url: 'php/update_group_list.php',
data: '',
dataType: 'json',
success: function(data) {
var id = data.instructor_id;
group_cnt = data.group_cnt,
group_name = data.group_name,
group_code = data.group_code;
for (i = current_row; i < group_cnt; i++)
{
//setInterval(function() { $('#group-list-div').load('php/group_list.php'); }, 5000);
$('#group-list').append("<li><a href='#' data-role='button' class='view-group-btns' id='"+group_code[i]+"' value='"+id+"' text='"+group_name[i]+"'>"+group_name[i]+"</a></li>");
$('#delete-group-list').append("<fieldset data-role='controlgroup data-iconpos='right'>" +
"<input id='"+group_code[i]+i+"' value='"+group_code[i]+"' type='checkbox' name='groups[]'>" +
"<label for='"+group_code[i]+i+"'>"+group_name[i]+"</label>" +
"</fieldset>");
}
current_row = i;
$('#group-list').listview('refresh');
$('#delete-group-list').trigger('create');
}
});
Now I am having two problems
FIRST PROBLEM:
When I try to run the code below (it should show an alert box if any of the list items created in this line $('#group-list').blah...blah in the code above), nothing happens.
$(".view-group-btns").click(function()
{
alert("check");
});
SECOND PROBLEM:
Also when I try to send the form data for the checkboxes (referencing line $('#delete-group-list').blah...blah in the ajax call code above) the post returns the error unexpected token <
What am I doing wrong? I think the two problems are related as I am creating the list items that are used dynamically.
Here is extra code relating to the SECOND problem
HTML:
<form id='delete-group-form' action='php/delete_groups.php' method='post'>
<h3 style='text-align: center;'>Check the Box Beside the Groups you Would Like to Delete </h3>
<div style='margin-top: 20px;'></div>
<div id='delete-group-list'>
</div>
<div style='margin-top: 20px;'></div>
<input type='submit' id='delete-groups-btn' data-theme='b' value='Delete Groups(s)'>
</form>
JS Code
$('#delete-group-form').submit(function(e)
{
e.preventDefault();
alert($('#delete-group-form').serialize());
if ($('#delete-group-form').serialize() == "")
{
alert('No groups selected to be deleted.')
return false;
}
else
if ($('#delete-groups-form').serialize() == null)
{
alert('No groups selected to be deleted.')
return false;
}
else
{
$.post('php/delete_groups.php',$('#delete-groups-form').serialize()).done(function(data)
{
obj = jQuery.parseJSON(data);
var group_codes = obj.group_list;
alert(group_codes);
alert("The selected groups have been deleted");
window.setTimeout(2000);
return false;
});
}
return false;
});
delete_groups.php
<?php
$group_codes = $_POST['groups'];
$items = array('group_list'=>$group_codes); //creating an array of data to be sent back to js file
echo json_encode($items); //sending data back through json encoding
?>
I think the root of the SECOND problem is the line $group_codes = $_POST['groups']; specfically the $_POST['groups'] because when I replace it with $group_codes = 'test'; (just for debugging purposes) , the code works as expected.
You need to use event delegation to make your newly-created elements function properly:
$("#group-list").on("click", ".view-group-btns", function() {
alert("check");
});
I noticed you have 3 single quotes on this line... missed one after controlgroup
$('#delete-group-list')."<fieldset data-role='controlgroup data-iconpos='right'>"
That would explain the unexpected token <
You have to use the jquery on event.
$(".view-group-btns").on("click", function(event)
{
alert("check");
});
Why?
Because you can only use the regular "click" on elements that are created BEFORE the DOM is updated.
When you are dynamically creating new elements into the dom tree, then you can't use .click anymore.
on (and in the past, .live(), which is deprecated now) can listen to modifications in the DOM tree and can use the later-on created elements.
You have to bind the click function after you get the element from ajax call. Binding on pageLoad event will only bind with those elements that are already in the dom. So do something like this.
$.ajax({
success : function(res){
//bind your click function after you update your html dom.
}
})
I am doing API call to box.net.
I wanted to show data from the response into a table.
But sometimes response is empty.
that time i want to show user some message.
So my idea is to show div containing table when i get some response and disable div containing message. and vice versa.
I an new to jquery. Didn't find suitable examples.
I tried something from those examples,but it was not successful.
here is
if (sizeof($folder_entries) == 0)
{
echo '<script>';
echo '$("#message").show()';
echo '$("#content").hide()';
echo '</script>';
}
else
{
echo '<script>';
echo '$("#message").hide()';
echo '$("#content").show()';
echo '</script>';
}
How can i get that?
Thanks in Advance.
seems like you need straightforward javascript or jquery to show and hide the div
<script>
if (some condition..... )
{
document.getElementById("test").style.display = '';
}
else
{
document.getElementById("test").style.display = 'none';
}
</script>
<div name="test" id="test">
jQuery:
$(document).ready(function() {
$('#hideh1').click(function(){
$('div.showhide,h1').hide();
});
$('#showh1').click(function(){
$('div.showhide,h1').show();
});
$('#toggleh1').click(function(){
$('div.showhide,h1').toggle();
});
});
I am have a table that shows the user suggestions that they have recieved on clicking read more some ajax is fired and in the database the suggestion is marked as read. Currently if the suggestion is new I show a closed envelope, if it is read I show an open envelope, however I can get it to reload the table when the user clicks the read more link so that the new class can be added. Currently it half works, they click read more and the full suggestions fades in but I need the envelope to change also.
<table>
<?php
$colours = array("#f9f9f9", "#f3f3f3"); $count = 0;
if(isset($newSuggestions)) {
foreach($newSuggestions as $row) {
if($row['commentRead'] == 0) {
$newRow = "new";
} else {
$newRow = "old";
}
?>
<tr id="a<?=$row['thoughtId'];?>" bgcolor="<?php echo $colours[$count++ % count($colours)];?>">
<?php
echo "<td class='".$newRow."'>".substr($row['thought'], 0,50)."...</td>";
echo "<td class='read'><a href='".base_url()."thought/readSuggestion/".$row['thoughtId']."' class='readMore'>Read More</a>";
echo "</tr>";
}
} else {
echo "You have no new suggestions";
}
?>
</table>
</div><!--/popular-->
</div><!--/widget-->
<div id="readMore">
</div>
<script type="text/javascript">
$(document).ready(function() {
//alert("hello");
$('#tabvanilla').tabs({ fx: { opacity: 'toggle', height:'toggle' } });
$('a.readMore').click(function(){
$('#readMore').fadeIn(500);
var url = $(this).attr('href');
$.ajax({
url : url,
type : "POST",
success : function(html) {
$('#readMore').html(html)
},
complete : function(html) {
$('table').html()
}
});
return false;
});
});
</script>
In the JavaScript where you open/fill in the full suggestions, you can modify the envelope image as well, using something like:
$('#envelope').attr('src', 'src/to/envelope.png');
I see no img tags, so you need to add one and fill in the id, so it is found by the JavaScript.
BTW: Having HTML and PHP on the same lines/parts, makes the total very unreadable. Only use <?php ... ?> for large PHP code blocks, otherwise use echo (or something similar).