Hi guys :) I'm quite new in the programming world, so I really need your help. I tryed to get data from some database tables and unfortunately something goes wrong in my $.getJson() function . If i run the php file it works , and so that with the functions from script.js . My html is also ok so i suppose it is the $get.JSON fault. I don't know so many javascript , so i put all my hopes into you :*
html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax - PHP</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script src="script.js">
</script>
</body>
</html>
script.js file :
$('document').ready( function() {
done();
}
);
function done() {
setTimeout(function() {
updates();
done();
}
, 200 );
}
function updates(){
$.getJSON( "read.php", function (data){
$.each(data.array, function () {
$("body").append("<li>Titlu: "+this['title']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array1, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Category_Id: "+this['category_id']+"</li>
<li>Titlu: "+this['title']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array2, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Titlu: "+this['title']+"</li>
<li>Latitudine: "+this['location_latitude']+"</li>
<li>Longitudine:"+this['location_longitude']+"</li>
<li>Numar de telefon: "+this['phone_number']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array3, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Interest_point_id:"+this['interest_point_id']+"</li>
<li>Pret: "+this['price']+"</li>
<li>Data: "+this['event1_time']+"</li>");
}
);
}
);
}
And finally the read.php file (Here it shows me what i expect , so i think everything is all right) :
<?php
include_once ('db.php');
$query= "SELECT * FROM category";
$query1= "SELECT * FROM sub_category";
$query2= "SELECT * FROM interest_point";
$query3= "SELECT * FROM event1";
global $connect;
$result = mysqli_query($connect,$query);
$result1 = mysqli_query($connect,$query1);
$result2 = mysqli_query($connect,$query2);
$result3 = mysqli_query($connect,$query3);
$array = array();
$array1 = array();
$array2 = array();
$array3 = array();
while($row=mysqli_fetch_array($result))
array_push($array , array( 'id' => $row[0],
'title' => $row[1],
'describtion' => $row[2]
));
while($row1=mysqli_fetch_array($result1))
array_push($array1 , array( 'id' => $row1[0],
'category_id' => $row1[1],
'title' => $row1[2],
'describtion' => $row1[3]
));
while($row2=mysqli_fetch_array($result2))
array_push($array2 , array('id' => $row2[0],
'title' => $row2[1],
'location_latitude' => $row2[2],
'location_longitude'=> $row2[3],
'phone_number' => $row2[4],
'describtion' => $row2[5]
));
while($row3=mysqli_fetch_array($result3))
array_push($array3 , array(
'id' => $row3[0],
'interest_point_id'=> $row3[1],
'price' => $row3[2],
'event1_time' => $row3[3]
));
echo json_encode(array("array"=>$array)).'<br>'.'<br>';
echo json_encode(array("array1"=>$array1)).'<br>'.'<br>';
echo json_encode(array("array2"=>$array2)).'<br>'.'<br>';
echo json_encode(array("array3"=>$array3)).'<br>'.'<br>';
?>
You can only echo once when sending json and there can only be one php array containing all the data. You can't print anything outside of this such as the <br> tags
try changing
echo json_encode(array("array"=>$array)).'<br>'.'<br>';
echo json_encode(array("array1"=>$array1)).'<br>'.'<br>';
echo json_encode(array("array2"=>$array2)).'<br>'.'<br>';
echo json_encode(array("array3"=>$array3)).'<br>'.'<br>';
To
$output = array(
"array1"=>$array1,
"array2"=>$array2,
"array3"=>$array3
);
echo json_encode($output);
Also note that <li> is an invalid child of <body>. Use <div> or insert into a <ul>
Related
I have a PHP code that creates a JSON data from wordpress posts in the database.
I load this JSON on my html page using AJAX.
The above works fine.
Now I need to add a "Load More" button so everytime its pressed, we load another 10 posts and append/add them to the ones that were already loaded WITHOUT having to delete the old ones and re-adding them.
So this my AJAX code for loading more:
var i = 0;
$(document).on("click", ".loadMoreBtn", function () {
$.ajax({
url: 'https://some-domain.com/index.php?t=' + mainCat + '&page=' + i + '',
dataType: 'json',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
if (!$.trim(data)) {
}
else {
}
$.each(data, function (pi, item) {
var id = item.id;
var img = item.img;
var title = item.title;
var date_added = item.date_added;
var item = '' + title + '';
$('.myDiv').before(item);
i++;
});
},
error: function () {
//error handling////
}
});
});
And this is my PHP code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
$t = $_GET['t'];
$page = $_GET['page'];
$posts = get_posts(array(
'posts_per_page' => $page, //add -1 if you want to show all posts
'post_type' => 'post',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $t //pass your term name here
)
))
);
$output= array();
foreach( $posts as $post ) {
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$mysqldate = $post->post_date;
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'F d Y', $phpdate );
// Pluck the id and title attributes
$output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'date_added' => $mysqldate, 'img' =>$feat_image );
}
echo json_encode( $output );
When I click on the 'Load More' button, it acts strangely! it basiclaly adds the old data and multiplies the same ones and adds/loads some new ones as well.
I know I am missing something in my PHP code but I couldn't figure out what.
Could someone please advice on this issue?
Thanks in advance.
The error is in your wordpress query. "posts_per_page" set how many posts will be loaded. Set that as how many post should be loaded like 12 or something.
The parameter your want to set as your $page parameter is "paged".
Eg. $query = new WP_Query( array( 'paged' => 6 ) ); // page number 6
https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
You could also use WP API instead of rolling your own
I'm a JavaScript Programmer and has a project with PHP.
I'm having trouble with working JSON with PHP.
This is my JSON
{
"orders":[
{
"name":"#1002"
},
{
"name":"#1001"
}
]
}
I need to get each name and echo them, I tried the following code $myarray = json_decode($order, true) but it returns me this error.
Warning: json_decode() expects parameter 1 to be string, array given in
How can i convert the json from array to string? or am i doing it wrong.
config.php
<?php
$con = mysql_connect('localhost','root','');
mysql_select_db('db_school',$con);
$sql = "SELECT * FROM userlogin";
$result = mysql_query($sql,$con);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] =array(
'id'=>$row['id'],
'username'=>$row['username'],
'userpass'=>$row['userpass'],
);
}
echo json_encode(array('data'=>$data));
?>
view.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="tbl" border="1">
<thead><tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
</tr></thead>
<tbody></tbody>
</table>
<script type="text/javascript">
$.ajax({
url: 'config.php',
}).done(function(res) {
var res_data = JSON.parse(res),table='';
$.each(res_data.data,function(index, el) {
console.log(el.id,' ', el.username,' ',el.userpass);
table+='<tr>';
table+='<td>'+el.id+'</td>';
table+='<td>'+el.username+'</td>';
table+='<td>'+el.userpass+'</td>';
table+='</tr>';
});
$('#tbl').html(table);
});
</script>
Demo:
Simply save the json response on a variable. And then do json_decode
$orders = '{
"orders":[
{
"name":"#1002"
},
{
"name":"#1001"
}
]
}';
$myarray = json_decode($orders, true);
Now performing print_r will yield result like
echo '<pre>';
print_r($myarray);
Result
Array
(
[orders] => Array
(
[0] => Array
(
[name] => #1002
)
[1] => Array
(
[name] => #1001
)
)
)
EDIT :
In order to get only name values simply run a foreach
$result = [];
foreach($myarray['orders'] as $value) {
$result[] = $value['name'];
}
Now printing $result you will get
Array
(
[0] => #1002
[1] => #1001
)
I'm really struggling to find a way to create pagination with ajax for my Wordpress posts. The solutions that I have found do not work.
To be more informative about this here is a link that has bullets at the bottom for pagination. Once these are clicked I want the effect of the site to load the new posts without triggering a page refresh.
http://maxlynn.co.uk/natural-interaction/category/all/
My question is, is there any good tutorials out there that you may have had success with for this type of effect.
Let me know if you need more information.
****** UPDATE ******
function kriesi_pagination($pages = '', $range = 2) {
$showitems = ($range * 2)+1;
global $paged;
if (empty($paged)) $paged = 1;
if ($pages == '') {
global $wp_query;
$pages = $wp_query->max_num_pages;
if (!$pages) {
$pages = 1;
}
}
if (1 != $pages) {
echo "<div class='pagination'><div class='pagination-container'>";
if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>«</a>";
if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹</a>";
for ($i=1; $i <= $pages; $i++) {
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
{
echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>";
}
}
if ($paged < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>›</a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>»</a>";
echo "</div>\n</div>\n";
}
}
This is my PHP that I'm using, how would I use this php to create an ajax request so that the page doesn't reload?
What you need to do is to prevent default on the pagination links, and send an AJAX request to get the posts. Wordpress works in this way for AJAX: you send all your requests to wp-admin/admin-ajax.php with an action parameter that will identify the request in order to catch it in functions.php using wp_ajax_nopriv_my_action and wp_ajax_my_action hooks.
So basically you will do this in your template file:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.pagination a').click(function(e) {
e.preventDefault(); // don't trigger page reload
if($(this).hasClass('active')) {
return; // don't do anything if click on current page
}
$.post(
'<?php echo admin_url('admin-ajax.php'); ?>', // get admin-ajax.php url
{
action: 'ajax_pagination',
page: parseInt($(this).attr('data-page')), // get page number for "data-page" attribute
posts_per_page: <?php echo get_option('posts_per_page'); ?>
},
function(data) {
$('#content-posts').html(data); // replace posts with new one
}
});
});
});
</script>
You'll have to change classes names / attributes etc depending of your template.
And on the functions.php side:
function my_ajax_navigation() {
$requested_page = intval($_POST['page']);
$posts_per_page = intval($_POST['posts_per_page']) - 1;
$posts = get_posts(array(
'posts_per_page' => $posts_per_page,
'offset' => $page * $posts_per_page
));
foreach ($posts as $post) {
setup_postdata( $post );
// DISPLAY POST HERE
// good thing to do would be to include your post template
}
exit;
}
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_navigation' );
add_action( 'wp_ajax_nopriv_ajax_paginationr', 'my_ajax_navigation' );
The thing is to query the posts of the page requested (so we calculate the offset from the page number and the posts per page option), and display them with the template you use for single posts.
You may want to manipulate the browser history too, for that you should check on the History API.
filter.js file
$('#post-category').change(function(){
category = $(this).find('.selected').text();
postType = $('#search-form-type').val();
post_filter();
});
function post_filter(paged){
$.ajax(
{
url:ajaxUrl,
type:"POST",
data: {action:"get_post_category","category":category,'search':search, 'postType':postType, 'paged': paged},
success: function(response) {
$('#blog-post-cover').html(response);
}
});
}
$('#blog-wrapper').on('click','#pagination a',function(e){
e.preventDefault();
if ($(this).hasClass('prev')||$(this).hasClass('next')) {
paginateNum = $(this).find('.prev-next').data('attr');
post_filter(paginateNum);
}
else{
paginateNum = $(this).text();
post_filter(paginateNum);
}
$("html, body").animate({ scrollTop: 0 }, "slow");
});
postType = $('#search-form-type').val();
post_filter(1);
function.php file
add_action( 'wp_ajax_nopriv_get_post_category', 'post_category' );
add_action( 'wp_ajax_get_post_category', 'post_category' );
function post_category() {
$post_type = $_POST['postType'];
$category = $_POST['category'];
$search = $_POST['search'];
$paged = ($_POST['paged'])? $_POST['paged'] : 1;
if($post_type==="resource-center"):
$taxonomy ="resource-center-taxonomy";
else:
$taxonomy ="category";
endif;
if($category):
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $category,
),
),
'posts_per_page' => 5,
'order' => 'ASC',
's' => $search,
'paged' => $paged
);
else:
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => 5,
'order' => 'ASC',
's' => $search,
'paged' => $paged
);
endif;
$posts = new WP_Query($args);?>
<?php if ( $posts->have_posts() ) :?>
<?php while ($posts->have_posts()) : $posts->the_post(); ?>
<?php echo $post->post_title; ?>
<?php endwhile;?>
<?php
$nextpage = $paged+1;
$prevouspage = $paged-1;
$total = $posts->max_num_pages;
$pagination_args = array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => $total,
'current' => $paged,
'show_all' => false,
'end_size' => 1,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('<span class="prev-next" data-attr="'.$prevouspage.'">«</span>'),
'next_text' => __('<span class="prev-next" data-attr="'.$nextpage.'">»</span>'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<div id='pagination' class='pagination'>";
echo $paginate_links;
echo "</div>";
}?>
<?php wp_reset_query(); ?>
<?php else:?>
<div class="no-post-cover">
<div class="container">
<h1 class="has-no-post-list">Posts Not Found</h1>
</div>
</div>
<?php endif;?>
<?php die(1);
}
I've made a form with two select fields. The first field is populated with the parents of a custom taxonomy. The second field is populated with the children of each one. I used AJAX to do that but does not seem to work. Nothing happens on change.
Below is my PHP code:
function products_selection()
{
$args = array(
'post_type' => 'seller',
'taxonomy' => 'category',
'hide_empty' => 0,
'exclude' => 1,1078,1079
);
$products = get_categories( $args );
if ( $products ) {
echo '<select id="products-select">';
echo '<option selected="" disabled="" value="0"><span>Προϊόντα</span></option>';
foreach ($products as $product) {
echo '<option class="product-name" id="'. $product->term_id .'">'. $product->name .'</option>';
}
echo '</select>';
}
}
function nomoi()
{
$args = array(
'post_type' => 'seller',
'taxonomy' => 'nomos',
'hide_empty'=> 0,
'parent' => 0
);
$categories = get_categories( $args );
if ( $categories ) {
echo '<select id="nomoi-select">';
echo '<option selected="0" value="-1"><span>Νομοί</span></option>';
foreach ( $categories as $category ) {
$id = $category->term_id;
$name = $category->name;
$taxonomy = $category->taxonomy;
echo '<option class="nomos" id="'. $id .'">'. $name .'</option>';
}
echo '</select>';
}
echo '<select id="town-select">';
echo '<option selected="" disabled="" value="0"><span>Πόλεις</span></option>';
echo '</select>';
}
function my_ajax() {
if(isset($_POST['main_catid']))
{
$args = array(
'order_by' => 'name',
'hide_empty' => 0,
'exclude' => 1,
'taxonomy' => 'nomos',
'name' => 'town-select',
'hierarchical' => 1,
'show_option_none' => 'Πόλεις',
'selected' => -1,
'child_of' => $_POST['main_catid'],
'echo' => 1
);
$categories = get_categories( $args );
foreach ( $categories as $cat ) {
$cat_name = $cat->name;
$id = $cat->cat_ID;
echo '<option class="town" id="'. $category->id .'">'. $category->name .'</option>';
}
die();
} // end if
}
My script:
jQuery(document).ready(function() {
// Avoid conflicts
$ = jQuery;
$('#nomoi-select').change(function() {
$mainCat = $('#nomoi-select option:selected').attr('id');
console.log('$mainCat: ' + $mainCat);
// call ajax
$("#town-select").empty();
$.ajax
(
{
url:'index.php',
type:'POST',
// Use an object literal
data: {
"action" : "my_ajax()",
"main_catid" : $mainCat
},
success:function( results )
{
// alert(results);
alert('Successfully called');
$("#town-select").append( results );
},
error:function( exception )
{
alert('Exception: ' + exception);
}
}
);
});
});
And the function to register my script:
function my_scripts() {
wp_enqueue_script( 'header-form', get_template_directory_uri() . '/js/headerform.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
Since you are working with WordPress, I suspect you could be having jQuery conflict issues. To confirm this, you can try changing all instances of $ to jQuery and see if you get the same errors.
Also - if you are running this script from a .js file, the PHP wont evaluate, but keeping the URL relative should still work fine.
I have made a few changes to the script which you can try:
jQuery(document).ready(function() {
// Avoid conflicts
$ = jQuery;
$('#main_cat').change(function() {
$mainCat = $('#main_cat option:selected').val();
// call ajax
$("#sub_cat").empty();
$.ajax
(
{
url:"/wp-admin/admin-ajax.php",
type:'POST',
// Use an object literal
data: {
"action" : "my_ajax",
"main_catid" : $mainCat
},
success:function( results )
{
// alert(results);
$("#sub_cat").removeAttr("disabled").append( results );
}
}
);
});
});
From the fiddle you provided, simply adding console.log('$mainCat: ' + $mainCat); (see this modified fiddle) ensures that the change event fires as expected.
Beyond that we get a 404 not found error, which is pretty normal in the current state of the fiddle example.
So it is certain that your issue comes from something with the Ajax called script or its returned data.
You only said that "Nothing happens on change", without any precision. In fact you should now use Firebug or similar to look at error messages, which may be, either:
an URL generation error: in this case you should get a 404 not found error too
an error in the server script you're invoking: in this case you should get a 500 server error error
a bad (malformed) return from the server: in this case you should get a JS error
Also note that:
it cannot be an empty return from the server, or your #sub_cat element would have already lost its disabled attribute before a JS error happens
at the opposite (even if unlikely) it also might be an Ajax error: so to be sure you should add an error: or always: member to the $.ajax() argument
I would like to create a like button using PHP, MySQL and jQuery, but seems there's an error, i don't know where is it, can you help ?
I have two pages [index.php & callback.php]
INDEX
$k = 1; //POST ID
$nip = 24; //USER ID
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.like', function(){
if($(this).attr('title')=='Like'){
$.post('callback.php',{k:$(this).attr('id'),action:'like'},function(){
$(this).text('Unlike');
$(this).attr('title','Unlike');
});
}else{
if($(this).attr('title')=='Unlike'){
$.post('callback.php',{k:$(this).attr('id'),action:'unlike'},function(){
$(this).text('Like');
$(this).attr('title','Like');
});
}
}
});
});
</script>
</head>
<body>
<?php
$query=$db->prepare("SELECT * FROM activity WHERE nip = :nip AND value = :value");
$query->execute(array(
':nip' => $meNip,
':value' => $k
)
);
$all = $query->rowCount();
if($query->rowCount()==1){
echo 'Unlike <b>'.$all.'</b>';
}else{
echo 'Like <b>'.$all.'</b>';
}
?>
</body>
</html>
CALLBACK
$nip= //COOKIE
$k= $_POST['k'];
$action=$_POST['action'];
if (!empty($k)) {
$checkAd=$db->prepare("SELECT * FROM ad WHERE id = :id");
$checkAd->execute(array(
':id' => $k
)
);
$checkingAd=$checkAd->fetchAll(PDO::FETCH_ASSOC);
foreach ($checkingAd as $row) {
//LIKE
if ($action=='like'){
$callback=$db->prepare("SELECT * FROM activity WHERE nip = :nip AND value = :value");
$callback->execute(array(
':nip' => $meNip,
':value' => $k
)
);
$matches=$callback->rowCount();
if($matches==0){
$callback=$db->prepare("UPDATE ad SET likes = :likes WHERE id = :id");
$callback->execute(array(
':likes' => $row['likes']+1,
':id' => $k
)
);
$callback=$db->prepare("INSERT INTO activity (nip, value) VALUES(:nip, :value)");
$callback->execute(array(
':nip' => $meNip,
':value' => $k
)
);
}
}elseif ($action=='unlike'){ //UNLIKE
$callback=$db->prepare("SELECT * FROM activity WHERE nip = :nip AND value = :value");
$callback->execute(array(
':nip' => $meNip,
':value' => $k
)
);
$matches=$callback->rowCount();
if($matches==1){
$callback=$db->prepare("UPDATE ad SET likes = :likes WHERE id = :id");
$callback->execute(array(
':likes' => $row['likes']-1,
':id' => $k
)
);
$callback=$db->prepare("DELETE FROM activity WHERE nip = :nip AND value = :value");
$callback->execute(array(
':nip' => $meNip,
':value' => $k
)
);
}
}
}
}
?>
I tested the callback.php file, (address bar using GET) it's working fine, can you check the INDEX, i think, i miss something, a dot ?
Thanks for your help
Your reference to $(this) in $.post is incorrect. You probably assumed $(this) will be the .like element, but that's not the case. this in a $.post would return something similar:
Object { readyState=1, getResponseHeader=function(), getAllResponseHeaders=function(), more...}
Object { url="callback.php", type="POST", isLocal=false, more...}
The code below should change the text accordingly.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.like', function(){
var $this = $(this);
var likes_count = $('.likes_count');
if($(this).attr('title')=='Like'){
$.post('callback.php',{k:$(this).attr('id'),action:'like'},function(){
$this.text('Unlike');
$this.attr('title','Unlike');
var likes = parseInt(likes_count.text())+1;
likes_count.text(likes);
});
}else{
if($(this).attr('title')=='Unlike'){
$.post('callback.php',{k:$(this).attr('id'),action:'unlike'},function(){
$this.text('Like');
$this.attr('title','Like');
var likes = parseInt(likes_count.text())-1;
likes_count.text(likes);
});
}
}
});
});
</script>