JSON callback function only works with a text file - php

Does any one know why the call back only works with a text file
PHP
<?php include("alan.php"); ?>
<?php
$rows=array();
mysql_select_db('news') or die(mysql_error());
//echo "Connected to Database";<?php
$result = mysql_query("SELECT * FROM photos")
or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_assoc( $result )) {
$rows[]=$row;
}
echo json_encode($rows);
?>
This outputs:
[{"name":"photo1.jpg","id":"1"},{"name":"photo2.jpg","id":"2"},{"name":"photo3.jpg","id":"3"},{"name":"photo4.jpg","id":"4"}]
JavaScript:
$(document).ready(function() {
$('#photos').click(function(){
$.getJSON('photo_get.php',function(data){ /**Changing this to a text file works ????**/
$.each(data, function(key, val) {
alert("Data" + val.name);
});
});
});
});

have you tried setting the content type in the php page?
<?php
header("Content-Type: application/json");
?>

Related

return tables rows in json and print

I am trying to return ajax response in json, but when I print it in log it gives null even tables has rows,
my php code is:
if(isset($_GET['proid'])){
$projid = $_GET['proid'];
include(db.php);
$res = mysqli_query($con, "SELECT * FROM data WHERE project_id LIKE '%$projid%'");
while($row = mysqli_fetch_assoc($res))
{
$dataarray[] = $row;
}
echo json_encode($dataarray);
}
ajax :
$.ajax({
url : 'getRecStudy.php',
type : 'GET',
data : {proid:study},
success : function(data) {
$('#tbody').empty();
$("#tbody").append(data);
console.log(data);
}
});
whats wrong?
I find no issue in your code except varibales. You need to debug the code in php file
if(isset($_GET['proid'])){
echo $_GET['proid'] . " is proid";
$projid = $_GET['proid'];
include(db.php);
echo "db connected";
$res = mysqli_query($con, "SELECT * FROM data WHERE project_id LIKE '%$projid%'");
echo "result fetched";
while($row = mysqli_fetch_assoc($res))
{
$dataarray[] = $row;
echo "inside while";
}
echo json_encode($dataarray);
print_r($dataarray);
exit;
}
after all this hit http://yourdomain.com/yourfile.php?proid=correctvalue
You will get the bug.
use parseJSON method in success function like this
var obj = jQuery.parseJSON( data );
alert( obj.name ); // For example name is a key

Jquery post causes apache to hang

I'm filling in element values in YUI panel (DOMInserted) via jquery
This is the php
<?php
$con = mysql_connect('sql', 'admin', '123');
mysql_select_db('sql');
$data_parent_type0 = mysql_real_escape_string($_POST['data_parent_type0']);
$result = mysql_query('SELECT id,name FROM email_templates WHERE description = "'.$data_parent_type0.'" AND deleted = 0');
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>' . "\n";
}
mysql_close($con);
?>
This is the JQUERY
$(document).bind('DOMNodeInserted', '#composeHeaderTable0', function(event) {
$("#data_parent_type0").click(function() {
var data_parent_type0 = $('#data_parent_type0').val();
//alert(data_parent_type0);
$.post("dbcall.php", { data_parent_type0: data_parent_type0},
function(result){
//alert(result);
$("#email_template0").html(result);
});
});
});
It works but causes Apache to hang.

Get Data from Mysql instead XML?

hey i have this javascript for a bubble up... this script gets InfoID and InfoData tags from an xml file...
<script type="text/javascript">
$(document).ready( function ( ) {
// Get the XML data from your file
$.get('scores.xml', function( data ) {
// Because we've given jQuery the XML datatype, we can jump straight to finding the element.
$(data).find('Game').each( function ( ) {
// The current object now holds a single "GAME" - find the elements we need
var game_id = $(this).find('InfoID').text( );
var game_info = $(this).find('InfoData').text( );
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
}); // end of each
}, 'xml'); // The 'xml' tells jQuery to expect XML back from the request
});
</script>
i need to make this script get data from Database table instead of xml.
i have the same InfoID and InfoData rows in a table in my database...
i use this php script to get data from db:
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
<?php echo $row['Header'].""; ?>
<?php echo $row['Row'].""; ?>
<?php echo $row['Date'].""; ?>
<?php echo $row['Time'].""; ?>
<?php echo $row['AwayTeam'].""; ?>
<?php echo $row['Score'].""; ?>
<?php echo $row['HomeTeam'].""; ?>
<?php echo $row['Other'].""; ?>
<?php echo $row['InfoID'].""; ?>
<?php echo $row['InfoData'].""; ?>
<?php } mysql_close(); ?>
any idea how i can do that? so i can remove my xml file and use database :)
Thanks in advance.
You could use an ajax post with a seperate callback function and return json data from your php script.
Give this a shot:
// try this for your javascript
<script type="text/javascript">
$(document).ready( function ( ) {
function getGameInfo() {
$.post("path/to/phpScript.php",
// this is the success callback
function (json) {
// this calls the function with the returned data
parseReturnedData(json);
});
return false;
};
// process json data to set your game_id and game_info vars
function parseReturnedData(data) {
var obj = jQuery.parseJSON(data);
var game_id = obj.InfoID;
var game_info = obj.InfoData;
}
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
</script>
// try this for your php file
<?php
// declare vars
$response = array();
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
$response['Header'] = $Header;
$response['Row'] = $Row;
$response['Date'] = $Date;
$response['Time'] = $Time;
$response['AwayTeam'] = $AwayTeam;
$response['Score'] = $Score;
$response['HomeTeam'] = $HomeTeam;
$response['Other'] = $Other;
$response['InfoID'] = $InfoID;
$response['InfoData'] = $InfoData;
}
echo json_encode($response);
mysql_close();
?>

workout with the php returned array to jquery

my this php code is working for the $.ajax call which is below this code
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
$imgurl=array();
//$i=0;
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl[]=$row['imgurl'];
}
}
echo $imgurl;
jquery code
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#main-content').html(data);
}
});
});
});
it outputs just Array written at the #main-content div how to work with that array which are basically image paths
Why you create array from mysql result ? your code can be simpler like this:
<?php
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
if(mysql_num_rows($result) > 0)
{
//Fetch rows
while($row = mysql_fetch_array($result))
{
echo $row['imgurl'];
}
}
?>
Try you page from the browser directly. Using JSON can help here:
echo json_encode($imgurl);
and using getJSON instead of plain ajax:
$.getJSON('thegamer.php', {send_text:text}, function(data) { … });

Getting Null value with JSON from MySQL, how to retrive data from MySQL to JSON correctly?

I'm using following code but cannot return data from MySQL.
This is the output:
<script type="text/javascript">
var somethings= [null,null,null];
</script>
It does have three post, but I couldn't get the title(message) output.
EDIT: this is the code I'm using:
<?php
$session = mysql_connect('localhost','name','pass');
mysql_select_db('dbname', $session);
$result= mysql_query('SELECT * FROM posts', $session);
$somethings= array();
while ($row= mysql_fetch_assoc($result)) {
$somethings[]= $row['something'];
}
?>
<script type="text/javascript">
var somethings= <?php echo json_encode($somethings); ?>;
</script>
This is the table:
message
Try iPhone post!
Welcome to Yo~ :)
好快!
Why did you use $row['something'] in the loop body? You don't need this.
Try such code:
$somethings = array();
while ($row = mysql_fetch_assoc($result)) {
$somethings[] = $row;
}

Categories