I want to insert while loop user data in jQuery array.
<?php
while($get_users_table_details = mysql_fetch_array($deatails)) {
if(empty($get_users_table_details["photo"])) { $pics = "photos/avatar.gif"; } else { $pics = "photos/".strip_tags($get_users_table_details["photo"]).""; }
?>
Script code between while loop
$(document).ready(function(){
$("#full").mention({
users: [{
name: '<?php echo $get_users_table_details['fullname'];?>',
username: '<?php echo $get_users_table_details['username'];?>',
image: '<?php echo $pics;?>'
}] });
});
</script>
end of script
}
end of while loop
The problem is that this shows the user details of only one user. However, I want all user details to be shown, as in this picture:
You should first build the array of users in php:
<?php
$users = []; // instatiate an empty array
while($get_users_table_details = mysql_fetch_array($deatails)) {
// build a user-array as needed later
$user = [];
$user['name'] = $get_users_table_details['fullname'];
$user['username'] = $get_users_table_details['username'];
if(empty($get_users_table_details["photo"])) {
$user['image'] = "photos/avatar.gif";
} else {
$user['image'] = "photos/".strip_tags($get_users_table_details["photo"]);
}
$users[] = $user; // add this user to the array of users
}
?>
Then pass (=echo) that to javascript via json_encode:
<script>
$(document).ready(function(){
$("#full").mention({
users: <?php echo json_encode($users); ?>
});
});
</script>
Please try this sample javascript code.
var users = <?php echo json_encode($get_users_table_details ) ?>;
$.each(users, function(key, value) {
console.log('stuff : ' + key + ", " + value);
// Do everything you want
});
Related
I am working on WordPress plugin. In plugin there is a check box, when a user checked the checkbox a value will be saved in database via ajax and when its unchecked the value will be deleted from database via ajax. So I create a checkbox and write an ajax code.
Here is my code:
HTML Code
<?php
$cart_items = get_cart_contents();
$cart_info = array();
foreach ($cart_items as $_data) {
$prod_id = $_data['id'];
$cart_info[] = array(
'prod_id' => $prod_id,
);
}
$_cart_sr = serialize($cart_info);
?>
<label class="label" for="purchase">
<?php _e('Purchase', 'product'); ?>
<input type="checkbox" id="purchase" />
</label>
<input type="hidden" class="cart_info" value='<?php echo $_cart_sr; ?>'>
Here is my Ajax and PHP Code:
add_action('wp_ajax_values_save', 'save_check_value');
add_action('wp_ajax_nopriv_values_save', 'save_check_value');
add_action('wp_ajax_values_delete', 'delete_check_value');
add_action('wp_ajax_nopriv_values_delete', 'delete_check_value');
add_action("wp_head", "edd_gift_email_ajax");
function edd_gift_email_ajax() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#purchase").click(function () {
if(jQuery(this).is(":checked")) {
var cart_info_save = jQuery('.cart_info').val();
var data_save = {
action: 'values_save',
cart_info_save: cart_info_save
}
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data_save, function (save_result) {
alert(save_result);
});
} else {
var cart_info_delete = jQuery('.cart_info').val();
var data_delete = {
action: 'values_delete',
cart_info_delete: cart_info_delete
}
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data_delete, function (delete_result) {
alert(delete_result);
});
}
});
});
</script>
<?php
}
And here is my save and delete query
function save_check_value() {
global $wpdb;
$info_save = stripcslashes($_REQUEST['cart_info_save']);
$cart_info_un_sr_save = unserialize($info_save);
foreach ($cart_info_un_sr_save as $user_gift_cart_save) {
$prod_user_id_save = $user_cart_save['prod_id'];
echo $prod_user_id_save . " _ Add This";
//update_post_meta($prod_user_id_save, 'this_product', '1');
}
}
function delete_check_value() {
global $wpdb;
$info_delete = stripcslashes($_REQUEST['cart_info_delete']);
$cart_info_un_sr_delete = unserialize($info_delete);
foreach ($cart_info_un_sr_delete as $user_cart_delete) {
$prod_user_id_delete = $user_cart_delete['prod_id'];
echo $prod_user_id_delete . " _ Delete This";
//delete_post_meta($prod_user_id_delete, 'this_product', '1');
}
}
So when I checked the check box the alert gives me this value 168 _ Add This (this is what I want) but when I unchecked the check box the alert gives me this value 0 (I want this value 168 _ Delete This).
I checked every thing but I got confused that why else condition not give me the right value.
Any suggestions.
Not directly a solution but I can't help thinking there is quite a lot of duplication of code which could be somewhat simplified.
The initial javascript function could be like:
<script type="text/javascript">
jQuery( document ).ready(function() {
jQuery("#purchase").click( function() {
var action=jQuery(this).is(":checked") ? 'save' : 'delete';
var cart_info=jQuery('.cart_info').val();
var data={
action:'value_'+action,
cart_info:cart_info
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function( result ) {
alert( result );
});
}
});
});
</script>
And rather than two distinct functions that share almost the same code you could do:
<?php
function check_value() {
global $wpdb;
$info = stripcslashes( $_REQUEST['cart_info'] );
$cart_info = unserialize( $info );
/* To find the `action` analyse the following */
exit( print_r( $cart_info ) );
foreach( $cart_info as $gift ) {
list( $junk, $action ) = explode( '_', $gift['action'] );
$product = $gift['prod_id'];
echo $product . " _ ".$action." this";
switch( $action ){
case 'save':
update_post_meta($product, 'this_product', '1');
break;
case 'delete':
delete_post_meta($product, 'this_product', '1');
break;
}
}
}
?>
The answer of #RamRaider is good but You can still reduce more code and might be it will work for you as well :)
Here's the jQuery:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#purchase").click( function() {
// Method variable will be using to define which
// function should trigger later in our PHP
var cart_method = jQuery(this).is(":checked") ? 'save' : 'delete';
var cart_info = jQuery('.cart_info').val();
var data = {
action: 'modify_cart',
cart_method: cart_method,
cart_info: cart_info
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function( result ) {
alert( result );
});
}
});
});
</script>
And then here is our PHP code:
<?php
function modify_cart_func() {
global $wpdb;
// Get method from our jQuery
$method = $_POST['cart_method'];
$info = stripcslashes( $_REQUEST['cart_info'] );
$cart_info = unserialize( $info );
foreach( $cart_info as $gift ) {
// If method is save
if ($method == 'save') {
update_post_meta($gift['product_id'], 'this_product', 1);
// If method is delete
} else if ($method == 'delete') {
delete_post_meta($gift['product_id'], 'this_product', 1);
}
}
}
?>
And finally your ajax call:
<?php
add_action('wp_ajax_modify_cart', 'modify_cart_func');
add_action('wp_ajax_nopriv_modify_cart', 'modify_cart_func');
?>
Hope that makes sense to you ;)
I am not sure if this causes the problem but if you are calling ajax when not logged in it tries to call wp-ajax with action email_values_delete not values_delete which i guess you are trying to call. Of course you might have that action as well for some other functionality.
If that is not the case change this
add_action('wp_ajax_nopriv_email_values_delete', 'delete_check_value');
To this
add_action('wp_ajax_nopriv_values_delete', 'delete_check_value');
You should also add wp_die(); in the end of each php function you are calling via wp-ajax.
Hope this helps.
Edit:
Sorry, it tries to call values_delete but since there is only email_values_delete (for non logged in users) defined I would guess ajax request might return something like 0.
i have an xml file in my server that i want to extract a list of IDs with php then convert the array to a JSON using json_encode() and put it in a $_SESSION variable, to make this clear my ideal JS function is:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = responseText;
});
}
//some other code
//return array; // this is an array i use later in js
}
in my getPL.php i have:
$videos_list = $theOne->parentNode->parentNode->getElementsByTagName('video');
for ($i = 0; $i < $videos_list->length; $i++) {
$a = $videos_list->item($i);
$id_out = $a->getElementsByTagName('id')->item(0)->nodeValue;
$array[$i] = $id_out;
}
$IDs = json_encode($array);
$_SESSION['IDs'] = $IDs;
echo $IDs;
break;
if i alert var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>; i get g8M8kxuaCWk,VWrBFt46J18
but when i alert the responseText i get ["g8M8kxuaCWk","VWrBFt46J18"]
all i want is to extract the IDs from the xml file and put them in a js array object
if there is anything need more tell me
i think you need the put quotes arround the php code in your JS like:
var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>';
ok i fixed it
so var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>'; would give me an array, which is what i actually want
but the alert(resposeText); was actually giving me a string so i did this JSON.parse(responseText);
thanks to who helped me get to this answer
after this in both cases if i alert(obj[0]); i get the first element so it is working
my ideal JS function becomes:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = JSON.parse(responseText); // this is the difference
});
}
return x;
}
Well what I want to do is to update image profile picture of the user with jquery from database but it does not pull out the source of image from db.please tell me where I'm wrong.
here is my code
include('../inc/config.inc.php');
$userSession = #$_SESSION["utente"];
$verificaPic = mysqli_query($db,"SELECT pic_profilo FROM users WHERE username='$userSession'");
$row_pic = mysqli_fetch_array($verificaPic, MYSQLI_ASSOC);
$pic = $row_pic["pic_profilo"];
if($row_pic["pic_profilo"] !== ""){
echo "<img src='$pic' class='img-polaroid'>";
}else{
echo '<img src="img/defaultuser.png" class="img-polaroid">';
}
and this is my jquery call
JQ(function($) {
setInterval(function() {
$.get("/ajax/DataProfilo.php",
function(data) {
$("#picprofilo").html(data); // 2pm
});
}, 100);//1000-1 sec
});
If I understand you correctly, then the code below is the DataProfilo.php script, correct? Please make the few minor changes in this code and show me what the result of the AJAX call is from the console. I also need to see the original HTML markup showing what #picprofilo is.
PHP
include('../inc/config.inc.php');
$userSession = #$_SESSION["utente"];
$q = "SELECT pic_profilo FROM users WHERE username='" . $userSession . "'"; // **add this line of code**
echo $q."\n";
$verificaPic = mysqli_query($db,$q); // **change this line of code!!**
$row_pic = mysqli_fetch_assoc($verificaPic);
$pic = $row_pic["pic_profilo"];
if (!empty($row_pic["pic_profilo"])) {
echo "<img src='$pic' class='img-polaroid'>";
} else {
echo "<img src='img/defaultuser.png' class='img-polaroid'>";
}
jQuery
JQ(function($) {
setInterval(function() {
$.get("/ajax/DataProfilo.php",
function(data) {
$("#picprofilo").html(data);
console.log(data);
});
}, 100);//1000-1 sec
});
how to retrieve much data in view (codeigniter) using while(). if I use foreach, I can't get the desired result. this is my code:
//my view home.php
$(document).ready(function(){
$('#check').click(function(event){
event.preventDefault();
var form_data = {
name: "xxxx"
};
$.ajax({
url: 'http://localhost:8000/jqjx/index.php/cont/getname',
type: 'POST',
async : false,
data: form_data,
dataType: 'html',
success: function(resp){
$('#content').html(resp);
}
});
return false;
});
});
//my controller cont.php
public function getname()
{
$data = array();
$namex = $this->input->post('name');
if($q = $this->my_model->detail_data($namex))
{
$data['data_detail'] = $q;
$this->load->view('tamp_page', $data);
}
}
my helper page (view) tamp_page.php
<?php
if(isset($data_detail))
{
foreach ($data_detailas $row) {
echo $row['name']."<br/>";
echo $row['birthday']."<br/>";
}
}
?>
if I use :
<?php
if(isset($data_detail))
{
echo $name_data['id_transactions'] . "<br/>";
echo $name_data['goods'] . "<br/>";
}
?>
it's still work but just for 1 data result. so how I can loop more much data.. thanks..
<?php
if(isset($data_detail))
{
foreach ($data_detail as $row)
{
echo $row['name']."<br/>"; //$row['name] was not properly closed. single quote(') was missing
echo $row['birthday']."<br/>";
}
}
?>
Just basic use of foreach:
if(isset($data_detail)){
foreach ($data_detailas as $row) {
echo $row['name'] . "<br/>";
echo $row['birthday'] . "<br/>";
}
}
I have been trying for days to get jquery autocomplete to work the way I need it to.
so far I have this which works fine:
<script>
$(function() {
var availableTags = [<?php
$taglist = Array();
foreach ($users as $user)
if ($user->getAttribute('first_name') == ''){
$taglist[] = '"'.$user->getUserName().'"';
}else{
$taglist[] = '"'.$user->getAttribute('first_name').' '.$user->getAttribute('last_name').'"';
}
echo join(',', $taglist);
?>];
$("#searchmem").autocomplete({
source: availableTags,
minLength: 2,
select: function(event, ui) {
$("#searchmem").val(ui.item.label);
$("#submit").click();
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='/files/avatars/1.jpg' />" + item.label + "</a>")
.appendTo(ul);
}
});
</script>
This will output the image /files/avatars/1.jpg next to the respective users username or full name.
The problem I'm having is trying to output the right users avatar. Each .jpg file corresponds with the username so I could have used $user->getUserID() in the src but this won't work because it's not inside the foreach $users as $user loop.
I have tried putting the whole autocomplete script inside the foreach which when tested did alert the right thing but autocomplete wouldn't work.
I have also tried creating two variables such as
availableTags1 = { label: .... $user->getUserName() etc... }
availableTags2 = { avatar: .... $user->getUserID() etc... }
availableTags = availableTags1 + availableTags2;
and
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src=' + item.avatar + ' />" + item.label + "</a>")
.appendTo(ul);
}
But again this didn't work. I'm completely lost! How can I get it to output the image alongside the relevant username? Help would be much appreciated.
In your case, you have to build an array like :
var availableTags = [
{label: '...', avatar: '...'},
{label: '...', avatar: '...'},
...
];
And use:
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.label + "</a>") // Note the additional double quotes
.appendTo(ul);
}
(see this example on jQuery UI for using custom data)
Then, for generating you array via PHP, you should use:
<?php
$taglist = Array();
foreach ($users as $user) {
$data = array();
if ($user->getAttribute('first_name') == ''){
$data["label"] = $user->getUserName();
} else {
$data["label"] = $user->getAttribute('first_name').' '.$user->getAttribute('last_name');
}
$data["avatar"] = $user->getUserID();
$taglist[] = $data;
}
?>
var availableTags = <?php echo json_encode($taglist); ?>;