Ajax JSON Not Returning - php

I have the following code in my main page, trying to pull AJAX JSON.
It simply has to show 10 extra products on each page scroll. and at the moment it only shows the loader Circle div which should remove after loading - but nothing is loading.
var handler = null;
var page = 1;
var isLoading = false;
var apiURL = 'ajax/api.php'
function onScroll(event) {
// Only check when we're not still waiting for data.
if(!isLoading) {
// Check if we're within 100 pixels of the bottom edge of the broser window.
var closeToBottom = ($(window).scrollTop() + $(window).height() >
$(document).height() - 100);
if(closeToBottom) {
loadData();
}
}
};
function loadData() {
isLoading = true;
$('#loaderCircle').show();
$.ajax({
url: apiURL,
dataType: 'jsonp',
data: {page: page}, // Page parameter to make sure we load new data
success: onLoadData
});
};
// Receives data from the API, creates HTML for images
function onLoadData(data) {
isLoading = false;
$('#loaderCircle').hide();
// Increment page index for future calls.
page++;
// Create HTML for the images.
var html = '';
var i=0, length=data.length, image;
for(; i<length; i++) {
image = data[i];
html += '<li>';
// Image tag
html += '<img src="products/200/'+p_id+'.jpg" ">';
// Image title.
html += '<p>'+p_name+'</p>';
html += '</li>';
}
// Add image HTML to the page.
$('#tiles').append(html);
};
And my PHP JSON call
<?php require_once('../inc/config.php');
$page = $_REQUEST['page'];
$items = '10';
$start = (($page * $items) - $items);
$end = ($page * $items);
$result = mysql_query("SELECT p_id, p_name FROM products ORDER BY p_id ASC LIMIT $start, $end");
$products = array();
while($product = mysql_fetch_array($result, MYSQL_ASSOC)) {
$products[] = ($product);
}
$output = json_encode($products);
echo $output;
?>
The JSON that the php displays is as follows (example data):
[{"p_id":"1","p_name":"ASOS Pleated Swing Mac"},{"p_id":"2","p_name":"ASOS Midi Belted Coat"},{"p_id":"3","p_name":"ASOS Zig Zag Coat"},{"p_id":"4","p_name":"Collarless Quilted Leather Biker with Ribbed Sleeve"},{"p_id":"6","p_name":"TFNC Dress with Wrap Front in Flocked Heart"},{"p_id":"7","p_name":"Striped Skater Dress"},
{"p_id":"8","p_name":"Metallic Wrap Dress"},{"p_id":"9","p_name":"Strapless Dress With Neon Belt"},{"p_id":"10","p_name":"Darling Floral Border Print Dress"},{"p_id":"11","p_name":"Dip Hem Chiffon Dress With Printed Top"}]
So overall it doesnt load the data into the html. Can someone please explain what I might have to do or what I might be doing wrong. (this is using the wookmark plugin - but shouldnt affect anything)

The problem is that you've set the jQuery AJAX dataType to jsonp, but your api.php is outputting JSON, not JSONP.
To solve this, either change the dataType to json:
$.ajax({
url: apiURL,
dataType: 'json',
data: {page: page}, // Page parameter to make sure we load new data
success: onLoadData
});
Or change your api.php file to output JSONP data:
$json = json_encode($products);
$output = isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json;

Related

Wordpress ajax call is returing the html of the page

I am getting the data from the sql table and storing the results inside the associative array after that i have encoded into json but the problem is that it is returning the html of the page along with the results
this is my php code
<?php
add_action('wp_ajax_nopriv_my_loadmore','my_loadmore');
add_action('wp_ajax_my_loadmore','my_loadmore');
function my_loadmore(){
global $wpdb;
$table_name="wpnn_tweets";
$paged=$_POST['page'];
$page=$paged*10;
$results = $wpdb->get_results("SELECT * FROM $table_name LIMIT 1 OFFSET $page");
$arr = array();
foreach($results as $row){
$arr['userScreen']=$row->userScreen;
$arr['userName']=$row->userName;
$arr['tweetCreated']=$row->tweetCreated;
$arr['tweetText']=$row->tweetText;
$arr['tweetRetweetCt']=$row->tweetRetweetCt;
$arr['tweetFavoriteCt']=$row->tweetFavoriteCt;
}
echo json_encode($arr);
wp_die();
}
?>
this is how i am retrieving the json in the front end
$ = jQuery;
function scroller() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$(this).off("scroll.ajax");
var page=parseInt($(this).data('page'));
var ajaxurl=$(this).data('url');
$.ajax({
url:ajaxurl,
type:"POST",
data:{
page:page,
action:"my_loadmore"
},
error:function(response){
console.log("error");
},
success:function(data){
for(i = 0; i < data.length; i++) {
console.log(data[i]);
}
}
});
}
}
$(window).on("scroll.ajax", scroller);
var ajaxurl = $(this).data('url');
This returns null unless you explicitly set it in your HTML. The easiest solution is to replace it with something like the following.
var ajaxurl = 'my-cool-endpoint';
This was not the solution to this particular problem, but I feel like it's a good thing to check for others coming to this page with the same problem. Replace wp_die() with die(). See the documentation for more details, but here is the relevant line.
A call to this function complements the die() PHP function. The difference is that HTML will be displayed to the user in the case of a typical web request.

Access Each JSON Array Element onClick Using AJAX PDO PHP

I'm trying to access each element stored as a Base64 image/blob in a JSON array constructed from a MySQL query.
The idea is to click a button that goes through each element and displays the image.
I have gotten it to display the first image however when i click again, the next image doesn't show.
Any help will be much appreciated.
AJAX:
$(function () {
$('#getimg1').on('click', function () {
$.ajax({
type:'GET',
dataType: 'json',
url: 'http://testing/api/getimg',
success:function(getinfo){
$.each(getinfo, function(i, displayimg){
$('#HTMLBox').prop('src','data:image/png;base64,' + displayimg.XXX ---- //Here I'm suspecting something?);
});
}
});
});
});
PHP:
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result->img);
}
echo json_encode($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
I'm using just 2 images to test this.
Because the ajax call you make will return all of the image records, I think it would be more efficient to store that data in a variable and then just rotate through the images rather than making call to your php code with each click. Here's what I would suggest, if you're using just jQuery:
var images = [],
index = 0,
count = 0,
max = 0;
$.getJSON("http://testing/api/getimg", function(data) {
images = data;
count = images.length;
max = count - 1;
});
$('#getimg1').on('click', function() {
if (count === 0) {
return;
}
if (index === max) {
index = 0;
} else {
index++;
}
$('#HTMLBox').attr('src', 'data:image/png;base64,' + images[index]);
});
I must admit I didn't test it, but I believe it should work - if you could try and see how you get on.
So, if you wanted to do something really dirty, you could track how many images you've loaded via a hidden input. You can increment that upon your ajax success. Then, what you can do is pass to your PHP via your AJAX that value, and run something like:
SELECT * FROM images LIMIT 1 OFFSET $images_already_fetched
By passing an OFFSET declaration, you're telling it to skip that many rows.

Unable to navigate Dynamically created pages in DOM

After so many trials, I have finally managed to create pages dynamically using PHP, JSON and AJAX and load them into DOM. But the problem now is I'm unable to call/navigate those pages dynamically, but manually i.e gallery.html#page1 ...etc.
I seek guidance rather than burdening you, as I'm here to learn.
**PHP - photos.php **
$photos = array();
$i=0;
while ($row = mysqli_fetch_array($query)){
$img = $row["fn"];
$photos[] = $img;
$i++;
}
$count = count($photos);
echo json_encode(array('status' => 'success', 'count' => $count, 'items' => $photos));
JSON array
{
"status":"success",
"count":3,
"items":
[
"img1.jpg",
"img2.jpg",
"img3.jpg"
]
}
I use the below method to fetch and store ID of the desired gallery,
<input type="hidden" value="<?php echo $id; ?>" id="displayid" />
and then I call it back to use it in AJAX.
var ID = $('#displayid').val();
AJAX and JQM
$.ajax({
Type: "GET",
url: 'photos.php',
data: { display: ID }, // = $('#displayid').val();
dataType: "json",
contentType: "application/json",
success: function(data) {
var count = data.count;
var number = 0;
$.each(data.items, function(i,item) {
var newPage = $("<div data-role=page data-url=page" + number + "><div data-role=header><h1>Photo " + number + "</h1></div><div data-role=content><img src=" + item + " /></div></div");
newPage.appendTo( $.mobile.pageContainer );
number++;
if (number == count) { $.mobile.changePage( newPage ); }; // it goes to last page
I got this code from here thanks Gajotres to dynamically navigate between pages. It's within the same code.
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
}); // next button
}); // each loop
} // success
}); //ajax
I found your problem.
This part of code can't be used here like this:
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
});
This is the problem. First remove pagebeforeshow event binding, it can't be used here like that. Rest of the code is not going to do anything because currently there are any next page (next page is going to be generated during then next loop iteration), so remove this whole block.
Now, after the each block ends and all pages are generated (that is the main thing, all pages should exist at this point), add this code:
$('[data-role="page"]').each(function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$(this).find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'a'}).addClass('ui-btn-right').html('Next').button());
}
});
This is what will happen. Each loop will loop through every available page (we have them all by now) and in case it is not the last one it will add next button.
Here's a live example: http://jsfiddle.net/Gajotres/Xjkvq/
Ok in this example pages are already there, but point is the same. They need to exist (no matter if you add them dynamically or if they are preexisting) before you can add next buttons.
I hope this helps.

How to code like this kind of output?When I click a specific link it will show some form(not sure if it is form)

How to code this? when I hover my name It pop outs like a form but I think its not a form
I want exactly the same like this because I want to happen in my page when I hover my name it has a value of id and send it via ajax to the php then the php script queries the id and return its other details then the other details will display like in the image I already have a function and a php code the only I need is how to do like this image
code for js function:
function searchWarriors() {
var id = $("#name").val();
$.ajax({
url: "retrieve_result.php",
type:"GET",
datatype:"json",
data: {id: id},
success: function(data) {
var toAppend = '';
if(typeof data === "object"){
for(var i=0;i<data.length;i++){
var warrior = data[i];
toAppend += '<ul class="ul">';
toAppend += '<li>'+data[i]['loc']+'</li>';
toAppend += '<li>'+data[i]['email']+'</li>';
toAppend += '<li>'+data[i]['sex']+'</li>';
toAppend += '</ul>';
}
$(".ul").remove();
$("#details").append(toAppend);
}
}
});
return false;
}
Code for my PHP:
<?php
header("Content-Type: application/json");
include 'functions/class.php';
$db = new DB();
$result = $db->getDetails($_GET['id']);
$details = array();
foreach($result as $values){
$details[] = $names;
}
echo json_encode($details);
?>
Code for my html to call function
<?php
foreach($result as $id){
//I don't know if this is right
echo'<a id="name" href="myphpcode.php"?id='.$id['user_id'].'>'.$id['name'].'</a>';
}
?>
<div id="details">
</div>
Easiest way to do this is to normally create exactly how you want the pop-up to look in a php script, then use jQuery and call the script with $("#Popup-id").load(script-url.php?getvar=1). The div element will need a high z-index in order to show on top of the screen.

Creating a comments page selection using AJAX data

I decided to go AJAX route for the heck of it, mainly to learn it, and to see how it worked. I want to add a page selection for comments that exceed, say, 10 posts.
I am using Codeigniter, and will post what I have so far:
Controller:
public function updatefilters()
{
$this->blurb_model->create_session_filter($_POST['filters']);
$this->blurb_model->get_threads($_POST['pagenum']);
}
Model:
public function get_threads($page = 0)
{
$NEEDPAGEHERE = $page
[fetch threads]
[return threads / count / etc]
}
So my goal is to display the number of pages to the user. This part is done. I have a submit button displayed for each page based on the total count of items returned in the "get_threads" model (code is omitted for relevance sake).
Here is my AJAX/javascript
Focus lies on the updatefilter function. I use the returned thread list to construct HTML and post it within the div. This works fine.
The problem is that I want to reuse the updatefilters() function when the user clicks on a page button...but its not working. I want to pass the value of the submit button into the updatefilter(pagenum) so that it then goes to the controller -> method, and I can do the math, but it does not work.
Javascript:
function updatefilters(pagenum){
// get the selected filters
var html;
var i = 0;
if (!pagenum)
{
pagenum = 0
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
async: false,
url: 'welcome/updatefilters',
dataType: 'json',
data: { filters: filters, pagenum: pagenum },
success: function(data){
var html = "";
html += "<div id=board>"
html += "<div class='board' id='table'>"
html += "<div id='row'>header here</div>"
var pages = Math.ceil(data['num_threads']/10);
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' id='page"+i+"' value='"+i+"' onclick='updatefilters(this.value);' /></li>"
}
htmlpage += "<div>"
htmlpage += "</ul>";
htmlpage += "</br></br></br>";
html += htmlpage;
for (i=0 ; i < data['threads'].length ; i++)
{
html += "<div id=row>";
html += " <div id='author' style='background: url("+data['threads'][i].location + ") no-repeat; background-position: center;'><p>"+data['threads'][i].username + "</p></div>";
html += " <div id='arrow'></div>";
html += " <div id='subject' title='"+ data['threads'][i].body +"'>";
html += " "+ data['threads'][i].subject +"<p>Created: "+data['threads'][i].posttime+"</p></div>";
html += " <div id='info'>";
html += " <div id='replies'>" + data['threads'][i].replies_num + "</div>";
html += " <div id='lastpost'>"+ data['threads'][i].lastreply+"</div>";
html += " </div>";
html += "</div>";
}
html += "</div></div>";
$('#board').html(html);
}
});
}
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
getactivesession();
function getactivesession(ev, ui){
var i = 0;
var actfilter, strfilter;
var strfilterarray = new Array();
$.ajaxSetup({cache: false})
$.ajax({
type: "POST",
async: false,
url: 'welcome/getactivesession',
dataType: 'json',
success: function (data){
strfilter = JSON.stringify(data)
strfilterarray = strfilter.split(',')
for (i=0 ; i < strfilterarray.length ; i++) {
strfilter = strfilterarray[i]
strfilter = strfilter.replace(/[\[\]'"]+/g,'');
var strfilterdash = strfilter.replace(/\s+/g, '-')
actfilter = '#'+ strfilterdash
$(actfilter).addClass('ui-selected')
}
updatefilters();
}
});
}
});
This would be an INCREDIBLE learning experience for myself, and a huge help if someone can spot the problem and explain it in an easily understood manner. I am extremely new with javascript and programming in general (which might explain the ugliness of the code).
Thanks!
Modify your selected event callback.
$("#selectable").selectable({
// Here is the event callback signature for reference
selected: function(event, ui) {
updatefilters();
}
});
You were passing an unexpected first parameter to updatefilters function.

Categories