In my PHP I am returning and updating a online users box however as it Echos each line out I also want it to activate a Jquery function. So if there is data there it will then echo it out and a Jquery function will take place.
example of php code ...
if($count1 > 0) {
foreach (user_list($user_name) as $user){
echo $user . "<br />";
};
echo ;// a message to activate a jquery function called userdisplay;
};
and the jquery code would look something like this...
function userdisplay(){
//do some amazing code like slide picture in from left fade text in at the top etc.
};
(I am not asking for help on the code which the function will do this is just an example)
Many thanks to anyone with an idea of how i should go about this my mind is completely blank.
just echo the call to the jquery function between a <script> tagfor example:
this is the page:
<html>
<head>
<script>
$(document).ready(function(){
//some jquery code here
});
//here is your function
function userdisplay(){
alert("triggered");
}
</script>
</head>
<body>
....
<?php
if($count1 > 0) {
foreach (user_list($user_name) as $user){
echo $user . "<br />";
};
echo "<script>userdisplay();</script>";
};
?>
....
</body>
</html>
if($count1 > 0) {
foreach (user_list($user_name) as $user){
echo $user . '<br />';
};
echo '<script>userdisplay();</script>';
};
You just have to make sure the function userDisplay() has been "echoed" before.
Related
I have the following problem on my wordpress project :
I have 2 div call "div_sc_1" and "div_sc_2" which are hidden on my page.
I want to show them with a jQuery function .show() if they are not "checked". "Checked" status is writen in my db.
With my actual code, If only div_sc_1 or div_sc_2 is not "checked", everything is allright BUT if both of the 2 divs are not checked, only one is displaying and I don't understand why.
This is my code :
foreach($list_id_scores as $scores){
$id_s = $scores->id_score;
$checked = $wpdb->get_var( "SQL query for 'checked' status");
if($checked == "1"){
echo " score n°".$id_s." is over<br />";
}else{
$div_id = "div_sc_".$id_s;
echo $div_id; /// this echo show me that my loop is working
?>
<script>
var div_sc = <?php echo json_encode($div_id); ?>;
jQuery(document).ready(function(){ jQuery("#"+div_sc).show(); });
</script>
<?php
}
}
What is the problem for you ? Thanks for your time
You're defining a global variable div_sc multiple times. All <script> tags share the same scope, so only one value is retained. The .ready() handler only executes after all variables have been defined (and the rest of the page has finished loading), not in between.
It might be better to do this instead:
<script>
jQuery(document).ready(function(){
<?php
foreach($list_id_scores as $scores){
$id_s = $scores->id_score;
$checked = $wpdb->get_var( "SQL query for 'checked' status");
if($checked == "1"){
echo " score n°".$id_s." is over<br />";
}else{
$div_id = "div_sc_".$id_s;
echo $div_id; /// this echo show me that my loop is working
?>
jQuery("#"+<?php echo json_encode($div_id); ?>).show();
<?php
}
}
});
</script>
i want insert user in db mysql, i have a controller php, im validate if user exist in db through a function, then if or not exist i want show alert function an redirect to php page, for that im using:
<?php
if(dao::existUser($user)) {
echo "<script type=\"text/javascript\">\n";
echo "alert('user exist!');\n";
echo "window.location = ('../insertUser.php');\n";
echo "</script>";
}
this function works!! but
i want to encapsulate the function in a method to later call it
example:
<?php
class Utils {
static function responseText($message, $url) {
echo "<script type=\"text/javascript\">\n";
echo "alert('"+$message+"');\n";
echo "window.location = ('"+$url+"');\n";
echo "</script>";
}
}
then, in my controller:
<?php
if(dao::existUser($user)) {
Utils::responseText("user exist",'../insertUser.php');
}
but not work, and after call responseText, my page goes blank
I don't know what is wrong ( likely a quoting issue ), but I would suggest using a HEREDOC style for this and return the text not output the HTML from the class by itself. Latter it could be hard to track where this output is coming from by looking just in the class that calls it. By doing echo Utills::.. you'll be able to easily see it's outputting something, whiteout having to look into what the class does.
So like this.
<?php
class Utils {
static function responseText($message, $url) {
return <<<HTML
<script type="text/javascript">
alert('$message');
window.location = '$url';
</script>
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
}
}
echo Utils::responseText("user exist",'../insertUser.php');
HEREDOCs are a way of doing a text block without using any quotes, beware of the note i put in comments... In this case it makes the Javascript string so much more simple when you don't have to manage quote usage.
Another suggestion for this class if it is to be a collection of static methods, you can make it where it can't be instantiated ( created using new class() ) Like this
<?php
class Utils {
private function __construct(){} //no instantion
private function __clone(){} //no cloning
This way you don't accidentally do $U = new Utils(); $U->responseText(..) It's a little thing but it will insure all the methods of this class stay static. It's just a design thing I like to do, on singletons and static classes
UPDATE your issue is you are using the + to concat in PHP where you should be using the . The + is good for Javascript not so much for PHP
And the way you have it with " double quotes concat is unnecessary, instead of
echo "alert('"+$message+"');\n";
Try
echo "alert('$message');\n";
If i understand you properly bind javascript to php.
<?php
$script = '<script type="text/javascript">';
$script .= 'function showAlert(){';
$script .= 'alert("Hello World.");';
$script .= '}';
$script .= '</script>';
echo $script;
?>
Than after page has loaded you can call it !
<script type="text/javascript">
window.onload = function () {
showAlert();
}
</script>
I am using Googles reCaptcha API for form validation.
I have opted to have the submit button show once the validation has been complete by using a little bit of JS.
<?php
if(isset($_POST['Login'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = '6LerNA0UAAAAAEReb9rS5JXjtvNSYlMjKiocUv_O';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true){
//show submit button
echo '<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="visible";
}
</script>';
}
else{ // stay hidden
'<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="hidden";
}
</script>';
}
}
?>
<div id='logDiv' style='visibility:hidden')
<?php
echo $form->add('Login',array('type' => 'submit'));
?>
</div>
Currently, the solution isn't working; when the Captcha is validated the div remains hidden.
Is this a result of a syntax error or have a made a logical error?
What is the bug in my code?
Are there any more robust solutions?
Why not simply use a php condition to show the div? I think your JS isn´t working because you never call myFunction().
Try something like this but it will become complex over time and amount of code:
if(isset($data->success) AND $data->success==true){
$showButton = true;
}
......
if($showButton) { ?>
<div id='logDiv' style='visibility:hidden'
<?php echo $form->add('Login',array('type' => 'submit'));
?> </div> <?php }
......
Or a simple Solution:
if(is_bool($data -> success) && $data -> success){
echo '<div id="logDiv">'.$form->add('Login',array('type' => 'submit')).'</div>';
}
Echo the HTML Elements only if validition was successful otherwise simply dont ouput any HTML for the Div.
Hope this Helps.
I am doing a basic jQuery ajax call on a PHP file and I can't seem to figure it out, why it isn't working. Any help is appreciated.
jQuery
<script>
$(document).ready(function(){
$('#approve').click(function(e){
e.preventDefault();
var email=$("email_address").text();
changeTable(email);
});
return false
});
function changeTable(email){
$.ajax({type:"post",
url:"DB_Update.php",
data:{email:email},
success:function(response){
alert(response);
}
});
}
</script>
PHP
$email=$_POST['email'];
updateTableApproval($email);
public function updateTableApproval($email){
$query_string="UPDATE users SET approved = b'1' WHERE email='$email'";
$result=mysqli_query($this->db->connect(),$query_string);
return $result;
}
PHP MAIN
echo "<td id='email_address'>".$email."</td>";
echo "<td id='approve'>"."<input type='radio' ".($row['approved']==1?'checked':'unchecked').">"."</td>;";
You are not returning data back from php function. Change one of this.
updateTableApproval($email); to echo updateTableApproval($email);
OR
return $result; to echo $result;
I want to make one javascript function, but I cannot call my function name right when i click on it(show_more_in_month_0/1/2).
this is my code
$i = 0;
foreach ($data as $row){
echo '<td><span class="glyphicon-plus show_more_in_mont_'.$i.'"></span><span class="glyphicon-minus_'.$i.'"></span></td>';
echo '<td>';
echo $row[0];
echo '</td><td>;
echo $row[1];
echo '</td><td>';
echo $row[2];
echo '</td><tr>';
$i ++;
}
And this is my script, i just want alert my class name after i call right function name
$(document).ready(function() {
$(".show_more_in_mont_'.$i.'.").click(function(){
alert(show_more_in_mont_'.$i.');
});
});
You are doing it wrong -- $i i suppose its your PHP variable ? well you shouldnt have those in your JS..
Just add as javascript one global class such "show-more-container" and use it to show whatever you want to show
$( document ).ready(function() {
$(".show-more-container").click( function() {
var elementId = $(this).data('id');
alert ('show_more_in_mont_'+elementId);
});
});
Now your html should look like
<div data-id="<?= $i ?>" class="show-more-container">
</div>
Hope this make sense to you :)
EDIT:
If you want to go far -- and call that as a function then do as follow:
window['my_fn_name_as_string'+appendId]()
for this to work the function should be on a Global scope -- on Body or Head and not inside Jquery! if you want to add it to jQuery then make sure you use:
$.function() {
window.my_fn_name_as_string_div = function() { }
}
EXAMPLE:
http://jsfiddle.net/7d23y99b/1/