Appending proper links to JSON - php

I am trying to make a little application which lists some pics and text from database on index page, and when I click on specific title it takes me to details page where I can find that picture with title and text.
I have made query which lists everything on index page but I can't figure out how exactly should I target the details page, because when I click on the post ID it takes me to details page but it pulls all the other posts with it.
Could someone help me?
My index page:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.ajax({
url:"",
type : "POST",
dataType : "json",
data : "param=no",
success : function (html) {
var DOM = jQuery('#DOM');
console.log(html);
jQuery.each(html, function(key, value){
console.log(value);
DOM.append("<li><h3><a href='details.php?post_id="+value.post_id+"'</h3> "+value.post_title+"</a></h3>
<p>"+value.post_author+"</p>
<img src='admin/news_images/"+value.post_image+"' width='100' height='100'</li>");
});
},
error : function (e){
alert(e);
}
});
});
</script>
This is my fetchdata.php:
<?php
header ('Access-Control-Allow-Origin:*');
$con= mysqli_connect ("localhost","root","","mycms");
$query= mysqli_query ($con, "select * from posts ");
$arr = array ();
while ($r = mysqli_fetch_object($query)) {
array_push($arr, array("post_id" => $r->post_id, "post_title" => $r->post_title, "post_author" => $r->post_author,
"post_image" => $r->post_image));
}
print_r(json_encode($arr));
?>

print_r(json_encode($arr)); will not get you a valid json string. print_r() makes your variable human readable and is mainly useful for debugging.
You need:
echo json_encode($arr);

Related

webpage content not updated through json function(data)

I am trying to update a webpage on the fly after inserting some data in the db and returning a json object to no avail.
Let's say I have
<div id="try1"> try(<span id="votes1">0</span>)</div>
When loeaded the page displays the current number of votes, (0) at the moment.
then I have a button
<button onclick="vote(1);">+</button>
that calls this function:
function vote(votes_id)
{
var div = 'try' +votes_id;
var url = 'vote.php?id=' +votes_id;
var destination = '#votes' +votes_id;
$.getJSON( url, function(data) {
$(destination).html (data.votes);
});
}
my vote.php returns this json or after correctly updating the db or, at least that is what I think
{"votes":"1"}
However my webpage doesn't get updated from 0 to 1,
I use $data = json_encode($data);
the result of which as var_dump is:
string '{"votes":"1"}'
and
{"votes":"1"}
as echo $data.
What am I possibly missing?
That's because you are putting he success callback in the wrong place.
Use:
function vote(votes_id)
{
var div = 'try' +votes_id;
var url = 'vote.php?id=' +votes_id;
var destination = '#votes' +votes_id;
$.getJSON( url, {}, function(data) {
$(destination).html (data.votes);
});
}

fetch data from mysql then display via JSON

I want to fetch data from mysql, and echo it by a json_encode. then my JQUERY will catch JSON via $.getJSON and append the result into my <ul>.
im trying to figure out why the data being captured by JQUERY is not printing on my index.php
this is my index.php
<html>
<?php
include_once('connect.php');
$sql = "SELECT * FROM data";
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($query))
array_push($result,
array(
'name' => $row[1],
'msg' => $row[2]));
echo json_encode(array("key" => $result));
?>
<body>
<ul>
//insert fetch data here
</ul>
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/custom.js"></script>
</body>
</html>
and here is my JQUERY
function my_function() {
$.getJSON("index.php", function(data) {
$.each(data.key, function(){
$("ul").append("<li>Name: "+this['name']+"</li>"
"<li>message: "+this['msg']+ "</li>");
});
});
}
You don't need to fetch your data via JSON as you're echo-ing the JSON on the same page.
you could do something like this:
<ul id="jsonData" data-json-data="<?php echo json_encode($result;)?>"
And in your js file:
var myData = $('#jsonData').data('json-data');
first: check your index.php output by itself to see if it's displaying valid json. ¿Are there invalid UTF8 characters? In that case json_encode's output is null.
second: I'd use plain ajax method hinting json as dataType:
jQuery.ajax({
url: 'index.php',
dataType: 'json'
}).done(function(data) {
for (i=1;i<data.length;i++) {
datarow=data[i];
$("ul").append("<li>Name: "+datarow.name+"</li>");
$("ul").append("<li>message: "+datarow.msg+ "</li>");
}
});
third: don't use the same script to generate the json and to display it, it makes no sense to decouple view from app if you do it all in the front. In that case you might as well use plain php to generate it all, as the previous answer told. (#Abdoul Sy)

Autocomplete in jQgrid with JSON data returned by a Php page

I was trying to implement autocomplete for a textbox which is generated by jQgrid. A Php page would return JSON data. Here's what I was able to do so far: (Please help)
function autocomplete_element(value, options) {
var $ac = $('<input type="text"/>');
$ac.val(value);
$ac.autocomplete({
source: function(request, response) {
$.getJSON("autocomplete.php", { q: request.term }, response);
}
});
return $ac;
}
function autocomplete_value(elem, op, value) {
if (op == "set") {
$(elem).val(value);
}
return $(elem).val();
}
$(function(){
$("#list").jqGrid({
url:'process1.php',
datatype: 'xml',
mtype: 'GET',
colNames:['Column Name'],
colModel :[
{name:'columnid', index:'columnid', width:50, edittype:'custom',
editoptions: {
custom_element : autocomplete_element,
custom_value : autocomplete_value
}
}
]
........
........
////////////////////////////////////////////////
/// THE PHP PAGE ////
////////////////////////////////////////////////
/*
autocomplete.php
*/
<?php
require_once("../dbconfig.php");
$term = trim(strip_tags($_REQUEST['q']));//retrieve the search term that autocomplete sends
$qstring = "SELECT description as value, id FROM test WHERE name LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['id']=(int)$row['id'];
$row['value']=htmlentities(stripslashes($row['value']));
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
?>
When I use data such as ["blah","hello","howdy"] in source of $ac.autocomplete, the thing seems to work nicely. But I have around 2000 rows of data to search from. The jQgrid form is working correctly and I am being able to add & edit data. Also, I have tested the php page which displays proper JSON data when I point a browser at it. I am only struck with autocomplete with data returned from the php page since I am not much comfortable with jQuery. Please help.
Try adding exit() after the last echo in php code. I hope this will fix.

Ajax/jQuery Comment System

Building a comment system with Ajax and JQuery and I want the div the comments are in to reload after a comment is added. It posts just fine. This is what I have so far.
The function getComments queries the database and generates the html
$.ajax({
type: "POST",
url: "post_comment.php",
data: dataString,
cache: false,
success: function(html){
????????? What should go here... it is a div with id#commentBody
}
<div id="commentBody">
<ul>
<?php
$q = "SELECT * FROM comment WHERE parent_id = 0 AND idpost = $postID";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)):
getComments($row,$postID,$custID);
endwhile;
?>
</ul>
</div>
Since you're regenerating the entire div I would use replaceWith.
$('#commentBody').replaceWith(html);
When you post it, you should return the data you want from your server side script. Then you can use the .html() jQuery function to update your div.
So, like:
$('#commentBody').html(html);
You could also return just the latest comment (optionally as a JSON object) and then just use the .append() method to add it to your #commentBody.
I would create a JSON object which has a status property and a data property. When the status is -1 (or whatever) there was an error adding the comment and you could put a message in the data property. When the status is 0, it was successful and the latest comment information would be available available in the data property.
Example
PHP
//Check postback variables, add comment and retrieve
// comment information (such as ID) if necessary
if (postedsuccessfully) {
$ary = array("status" => 0,
"data" => array("id" => $commentidvar,
"user" => $commentuser,
"text" => $comment)
);
echo json_encode($ary);
} else {
$ary = array("status" => -1,
"data" => "There was a problem adding your comment.");
echo json_encode($ary);
}
JavaScript
success: function(json){
if (json.status == 0) {
$mydiv = $('<div>');//construct your comment div using json.data.id,
//json.data.user, and json.data.text
$('#commentBody').append($mydiv);
} else {
alert(json.data);
}
}

Cannot populate form with ajax and populate jquery plugin

I'm trying to populate a form with jquery's populate plugin, but using $.ajax
The idea is to retrieve data from my database according to the id in the links (ex of link: get_result_edit.php?id=34), reformulate it to json, return it to my page and fill up the form up with the populate plugin. But somehow i cannot get it to work. Any ideas:
here's the code:
$('a').click(function(){
$('#updatediv').hide('slow');
$.ajax({
type: "GET",
url: "get_result_edit.php",
success: function(data)
{
var $response=$(data);
$('#form1').populate($response);
}
});
$('#updatediv').fadeIn('slow');
return false;
whilst the php file states as follow:
<?php
$conn = new mysqli('localhost', 'XXXX', 'XXXXX', 'XXXXX');
#$query = 'Select * FROM news WHERE id ="'.$_GET['id'].'"';
$stmt = $conn->query($query) or die ($mysql->error());
if ($stmt)
{
$results = $stmt->fetch_object(); // get database data
$json = json_encode($results); // convert to JSON format
echo $json;
}
?>
Now first thing is that the mysql returns a null in this way: is there something wrong with he declaration of the sql statement in the $_GET part? Second is that even if i put a specific record to bring up, populate doesn't populate.
Update:
I changed the populate library with the one called "PHP jQuery helper functions" and the difference is that finally it says something. finally i get an error saying NO SUCH ELEMENT AS
i wen into the library to have a look and up comes the following function
function populateFormElement(form, name, value)
{
// check that the named element exists in the form
var name = name; // handle non-php naming
var element = form[name];
if(element == undefined)
{
debug('No such element as ' + name);
return false;
}
// debug options
if(options.debug)
{
_populate.elements.push(element);
}
}
Now looking at it one can see that it should print out also the name, but its not printing it out. so i'm guessing that retrieving the name form the json is not working correctly.
Link is at http://www.ocdmonline.org/michael/edit_news.php with username: Testing and pass:test123
Any ideas?
First you must set the dataType option for the .ajax call to json:
$.ajax({dataType: 'json', ...
and then in your success function the "data" parameter will already be a object so you just use it, no need to do anything with it (I don't know why you are converting it into a jQuery object in your code).
edit:
$( 'a' ).click ( function () {
$( '#updatediv' ).hide ( 'slow' );
$.ajax ( {
type: "GET",
url: "get_result_edit.php",
success: function ( data ) {
$( '#form1' ).populate ( data );
},
dataType: 'json'
} );
$( '#updatediv' ).fadeIn ( 'slow' );
return false;
}
also consider using $.getJSON instead of $.ajax so you don't have to bother with the dataType
Try imPagePopulate (another jquery plugin). It may be easier to use:
http://grasshopperpebbles.com/ajax/jquery-plugin-impagepopulate/

Categories