I want to reload my div names shoutbox:
echo '<div id="shoutbox"><ul>';
$results = $db->query($sql);
foreach ($db->query($sql) as $row) {
echo '<li>';
echo '<span class="date">'.date("d/m/Y H:i", strtotime($row['date_time'])).' </span>';
echo '<span class="name">'.$row['name'].' - </span>';
echo '<span class="message">'.$row['message'].'</span>';
echo '</li>';
}
echo '</div></ul>';
But i don't know how to do that with AJAX... sow the div has to reload when you klik the submit button and every 60 mili-seconds.
if someone can help me, it will be fine.
Michel is on the right track. You should get the data from php, and return json formatted data so that the client can update in javascript. Check out the jquery getJSON function: http://api.jquery.com/jquery.getjson/. Then you set that in a javascript "setInterval" function, like this:
setInterval(function(){
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "#shoutbox ul", {
html: items.join( "" )
}).appendTo( "body" );
});
}, 100);
This would reload the array of data every 100 miliseconds.
Related
I'm building a shopping page that list all the stores. I've created a sidebar with all the categories and a list with pagination. This list is generated by a wordpress function in my theme-functions.php, but when I click in any category, I'm redirected to another page (to http://<domain>/store from http://<domain>/category). So I created a JavaScript function to prevent the link action using preventDefault and get his href value and set it as variable to pass it to the function via Ajax.
My question is: there is a way to pass this variable and refresh the wordpress function on the same page to show this list?
Code below:
Wordpress theme-function.php
function storeSingle() {
$catUrl = $_POST['catUrl'];
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'lojas' ,
'posts_per_page' => 5,
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'category_name' => $catUrl
);
/* Added $paged variable */
$exec = new WP_Query($args);
if($exec->have_posts()):
echo '<ul class="single-store">';
while($exec->have_posts()):
$exec->the_post();
$categories = get_the_category($post->ID);
echo "<li class='store-box'>";
echo '<a href=" '. get_the_permalink() .' ">';
echo '<h1>';
echo the_title();
echo '</h1>';
echo "</a>";
echo '<div class="store-info-box">';
echo '<span>';
echo '<i class="fa fa-map-marker" aria-hidden="true"></i>';
echo the_field('localizacao');
echo '</span>';
echo '<span>';
echo $categories[0]->name;
echo '</span>';
echo '</div>';
echo "</li>";
endwhile;
echo '</ul>';
if (function_exists(custom_pagination)) {
custom_pagination($exec->max_num_pages,"",$paged);
}
endif;
}
add_action('wp_ajax_catUrl', 'catUrl');
add_action('wp_ajax_nopriv_catUrl', 'catUrl');
JavaScript function
$('.cat-item').on('click', 'a', function(e){
e.preventDefault();
var catUrl = this.href;
catUrl = catUrl.split('/');
$.ajax({
type: "POST",
url: 'http://localhost/asv/shopping/wp-admin/admin-ajax.php',
dataType: 'json',
data: {
action: catUrl,
catUrl: catUrl[5]
},
success: function(data){
response(data),
console.log('test' + data);
}
});
});
I've searched this a lot but I didn't find out how to use ajax in wordpress properly.
if you are getting results in you console.log('test' + data); seems like you just need to display this results back in your HTML container by replacing the current content with your ajax response.
I'm trying to get a single div on a php page to refresh every 5 seconds.
In HTML I have: EDIT: NEW SCRIPT FUNCTION
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'game.php',
success:function(data){
$("#read_chat").html(data);
}
});
}
setInterval(callAjax, 5000);
});
</script>
And the function (in a php block) I'm trying to refresh is:
echo" <div class='read_chat' >";
function get_messages($db){
//get messages
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
//display messages
foreach ($messages as $row) {
//display each message in row
if ( $row['character_name'] == NULL){
echo "<div class='left'>" . $row['user_name'] . ": </div>";
}
else {
echo "<div class='left'>" . $row['character_name'] . ": </div>";
}
echo "<div class='center'>" . $row['message'] . "</div>";
echo "<div class='right'>" . $row['time'] . "</div>";
}
}
echo "</div>";
The display of this is only the CSSed block without any content. If I just call get_messages($db) all the chat from the database loads. How do I make this div refresh automatically? Thanks!
EDIT:
The name of the file is "game.php" and the php function is "get_messages()".
For the record I looked at:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
and
Pass parameters in setInterval function
Javascript
setTimeout(function(){
$.ajax({url: "get_message.php", success: function(result){
var num_records = result.length,
i,
content;
for(i=0;i<num_records;i++){
if (result[i]['character_name'] !== null){
content += "<div class='left'>" + result[i]['character_name'] +": </div>";
}
else{
content += "<div class='left'>" + result[i]['user_name'] +": </div>";
}
content += "<div class='center'>" + result[i]['message'] + "</div><div class='right'>" + result[i]['time'] + "</div>";
}
$('.read_chat').html(content);
}});
}, 5000);
get_message.php
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
$response = array();
foreach ($messages as $row) {
$response[] = $row;
}
echo json_encode($response);
I'd suggest using jQuery $.load, see the example below:
setTimeout(function(){
$('.read_chat').load('get_message.php');
}, 5000);
You'll need to return nice html from the PHP script instead, but it's cleaner.
I try to make a query from database to get the list of users based on their country using php/mysql and jquery.
I have a mysql query that extracts the countries form database in a select options field. After this, i put a jquery code to automatically get the table with users based on the selected country. This is how jquery code looks like:
<script>
$( "#tara" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += "<table class='table table-bordered table-striped'>" +
"<thead><tr><th><p><?php echo _('Tara');?></p></th></tr></thead>" +
"<tbody>" +
"<?php
$variabilatara = 182;
$test = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") ?>" +
"<?php while($row=mysql_fetch_object($test))
{
echo "<tr>";
echo "<td><p>$row->nume</p></td>";
echo "</tr>";
}
?>" + $( this ).val() + " ";
});
$( "#testare" ).html( str );
})
.change();
</script>
My question is: How to put the $( this ).val() into php instead of $variabilatara, so it will looks something like: $variabilatara = $( this ).val(); and the sql query will modify on change of selected country. Thank you!
What you are trying to do is called AJAX. Sounds complicated, but it really isn't. See these examples for a simplistic explanation. Do not just look at them -- copy/paste to your server and make them work. Change the values. See how it works - really very simple.
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Your code is a bit difficult for me to follow, but should be refactored something like this. (I am unsure where strTara figures in the code, but I'm sure you will be able to figure it out from here).
javascript/jQuery:
var strTara = <?php echo _('Tara');?>
$( "#tara" ).change(function () {
selVal = $(this).val();
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'variabilatara=' + selVal,
success: function(data){
var tblHead = "
<table class='table table-bordered table-striped'>
<thead><tr><th><p>strTara</p></th></tr></thead><tbody>
";
$( "#testare" ).html( tblHead + data );
}
});
});
another_php_file.php: (your PHP AJAX processor file)
<?php
$var = $_POST['variabilatara'];
$out = '';
$result = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") or die(mysql_error());
while($row=mysql_fetch_object($result)){
$out .= "<tr>";
$out .= "<td><p>" .$row->nume. "</p></td>"; //<== fixed
$out .= "</tr>";
}
$out .= '</tbody></table>'; //<== fixed
echo $out;
?>
This script displaying the dynamic content for once thereafter its not working
Here is the code:
$(document).ready(function(){
$('.getmore').on('click',function(){
var last_id = $(this).attr('id');
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/getmore.php',
data: 'last_id='+last_id,
beforeSend: function(){
$('.getmore').html('<img src="../images/loader.gif" alt="Loading..." />');
},
success: function(data){
$('.getmore').remove();
$('#comments').append(data);
}
});
});
});
Here is the complete php code:
<?php
mysql_connect('localhost','root','') or die('Error... Couldnt connect..');
mysql_select_db('mydb') or die('Error... Couldnt select the Db..');
$records = mysql_query(' SELECT * FROM `compare_post_comments` WHERE `post_id`=37 limit 5 ');
if(mysql_num_rows($records)){
echo '<div id="ajax_comment">';
echo '<ul id="comments">';
while($data = #mysql_fetch_array($records) ){
echo '<li>'.$data['comments'].'</li>';
$last_record = $data['sno'];
}
echo '<li class="getmore" id="'.$last_record.'">Get More</li>';
echo '</ul>';
echo "<span id='cmmnts'></span>";
echo '</div>';
}
?>
getmore.php code
<?php
if( ( isset($_POST['last_id'])!=null ) && $_POST['last_id']!="" ){
$last_id = $_POST['last_id'];
//echo "::".$last_id;
$qry = " SELECT * FROM `compare_post_comments` WHERE `post_id`=37 and sno > ".$last_id." limit 5 ";
//echo "::".$qry;
$comments = mysql_query($qry) or die('Error..');
if( mysql_num_rows($comments) ){
while( $data = mysql_fetch_array($comments) ){
echo "<li>".$data['comments']."</li>";
$last_id=$data['sno'];
}
echo "<li class='getmore' id='".$last_id."'>Get More</li>";
}else{
echo "<li class='nomore'>No More</li>";
}
}else{
echo "<li class='nomore'>No More</li>";
}
?>
ajax call working for once, thereafter its not clickable.
I dont have much knowledge about ajax and javascript, explanation is appreciated.
Try the deferred syntax of on instead:
$(document).on('click', '.getmore', function...
This will survive DOM changes. This answer presumes that your loaded data contains an object with class="getmore", as you are removing it from the DOM on success. If not you need to remove the remove as suggested by NewInTheBusiness, but probably replace it with empty() instead to remove the loading progress.
Note I have recently found problems with the version of on that only takes the event and function. In jQuery 1.10.3 it seems to not be firing when it should.
It's because you remove the getmore class after success.
Remove this line of code:
$('.getmore').remove();
Check your firebug console for any error
Remove this line $('.getmore').remove();
Delegate the click event to the element's static parent or to the document.
Try,
$(document).on("click",'.getmore', function( event ) {
});
Just try live or bind in-place of "on" :
$('.getmore').live('click',function(){
}
or
$('.getmore').bind('click',function(){
}
Hi I have a simple ajax search that returns the results in a table. I can extract the XML and display it fine but what I cannot do is get the index number of the data (var Rows) .
When a user clicks the returned result I believe I would need this in order to retrieve all the data in order to use IE $("name:eq(1)",data).text();. Can anyone help me please and I hope this makes sense !!, thanks
My Jquery code is here
$(document).ready(function(){
$.ajax({
type: "GET",
url: "search_action.php?" + string ,
dataType: "xml",
success: disxml ,
});
})
}
function disxml(data){
dv = $('#crmbox')
$(data).find('list').each(function() {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
var rows = $(this).eq() ;
display = display + "(" + rows + ")" + " Name :" + name + " ID :" + cus_id + " <br>" ;
})
dv.html(r);
};
here is the php that generates my xml
echo '<results>' ;
while($row = mysql_fetch_array($result)) {
$name = $row['name'] ;
$major_id = $row['address1'] ;
echo '<list>' ;
echo '<name>';
echo $name;
echo '</name>';
echo '<mid>';
echo $major_id ;
echo '</mid>';
echo '</list>' ;
} ;
echo '</results>' ;
the extra tag is the close of an earlier function - no relevence to question
It sounds like you want the index you're currently at, in which case use the first parameter passed to the .each() callback, like this:
$(data).find('list').each(function(row) {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
//row is the index, starting at 0