Unable to retrieve json data using jquery - php

i am a newbie and am stuck at retrieving json data.
following is my index.php :
<script type="text/javascript" src="jquery-1.3.2.min_2.js">
$("document").ready(function() {
$.getJSON("data.php",function(jsondata){
$("#content").html(jsondata[0].content);
});
});
</script>
</head>
<body>
<div id="content"></div>
<div class="lg"></div>
</body>
in my data.php i am using the standard way of encoding and sending the data:
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$row = mysql_fetch_row($result);
$jsonserver[$i] = $row;
}
echo json_encode($jsonserver);
header('Content-type: application/json');
mysql_free_result($result);
// close connection
mysql_close($con);
i am using mysql database.
when i open localhost/data.php the json data is shown on the browser.
but in case if i open localhost/index.php i donot get any desired output.
Please explain.
Thanks!

you need to put all headers before any 'echo's on the page
so:
header('Content-type: application/json');
echo json_encode($jsonserver);

Hey,
u didn't close script tag properly
try
<script type="text/javascript" src="jquery-1.3.2.min_2.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$.getJSON("data.php",function(jsondata){
$("#content").html(jsondata[0].content);
});
});
</script>

Related

PHP autocomplete

I trying to fine tune an autocomplete text box. What I have here works (albeit a bit messy). But I would like to display the values available when clicking into the text box, then filter down as you type. Also, is there a simpler way to code this?
<?php
session_start();
if(isset($_SESSION['myusername'])) {
$User = $_SESSION['myusername'];}
$db1 = realpath('C:\AccessBackEnds\CETracker\CETracker.accdb');
$conn1 = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$db1",'','') or die ("Unable to connect to server");
?>
<link rel="stylesheet" href="../datepicker/jquery-ui2.css" />
<script src="../datepicker/jquery-1.9.1.js"></script>
<script src="../datepicker/jquery-ui.js"></script>
<script>
$(function() {
var availableTasks = [
<?php
$info0 = "SELECT DISTINCT TaskName FROM CT:MyTasks WHERE UserName = '$User'";
$rs0=odbc_exec($conn1,$info0);
while($row = odbc_fetch_array($rs0)) {
$TaskName = "" . $row['TaskName'] . "";
echo '"';
echo $TaskName;
echo '", ';
}
?>""];
$( "#Tasks" ).autocomplete({
source: availableTasks
});
});
</script>
<div class="ui-widget">
<label for="Tasks">Tasks: </label>
<input name="tasks" id="Tasks" style="width: 400px">
</div>
I think you could enhance the readibility of your script if your split it in two files:
A frontend file, that one has HTML and JS code
A backend file, which has PHP code that generate JSON code.
The frontend file can call the backend file by a json invocation, take into account that the "Autocomplete" widget of jQuery UI has this functionlity built-in. Have a look here in "Remote JSONP Source".
Also PHP can easily generate JSON data by json_encode function.

PHP/JQUERY- Can't return data from a query

I'm doing a project for an exam. I'm stuck with that and I hope someone of you could help me (I'm italian, so sorry for my bad english!).
I have to query an existing database stored in phpmyadmin with a PHP script. Then, the query result need to be parsed with a jquery script and printed to an HTML page.
Here is the PHP script:
<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Errore di connessione: ' . mysql_error());
}
mysql_select_db("progetto_lpw", $con);
$sql="SELECT denominazione FROM farmacia";
$result = mysql_query($sql) or die(mysql_error());
$num=mysql_numrows($result);
while($row = mysql_fetch_array($result)){
print json_encode($row['denominazione']);
print "<br />";
}
?>
I've already tested the PHP script calling it via browser and it works.
Then, I parse the result with this jquery script (the use of this combination is a requirement of the project):
$("#button").click(function(){
$.getJSON('json.php', function(data) {
$.each(data, function(index,value){
$("#xx").append("<p>"+value+"</p>")
})
})
})
Here is the problem: when I open the HTML page and I click the button on firefox, consolle says "no element found" referring to PHP script.
"xx" is the id of the div in which elements are printed.
Where is the error?
Thanks to everyone.
Replace below code
while ($row = mysql_fetch_array($result)) {
print json_encode($row['denominazione']);
print "<br />";
}
With below code and try
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row['denominazione'];
}
header('Content-type: application/json');
echo json_encode($rows);
HTML
<button id="button">Fetch JSON</button>
<div id="xx"></div>
JS
$("#button").click(function() {
$.getJSON('json.php', function(data) {
$.each(data, function(index, value) {
$("#xx").append("<p>" + value + "</p>")
});
});
});
Response from json.php should be in below format
["AGGERI","ALCHEMICA 1961"]
The reason your code isn't working is that it's producing output like this:
"foo"<br />
"bar"<br />
That's not valid JSON. To be valid, you have to not have the HTML <br /> in there (this is JSON, not HTML), and you have to have commas between the elements you want to return.
json_encode will handle formatting the array correctly for you.
jsFiddle Demo with post request to send and get json output
'print' works differently then 'echo'. At least i am sending JSON packages with echo from php.
Can you replace it ?
// in php
echo json_encode($row['denominazione']);
// in jquery script, best to place "<br />" tag here
$("#xx").append("<p>"+value+"</p><br />")

Parsing php values to javascript Uncaught ReferenceError [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript echo’d by PHP doesn’t run
In the following code I am parsing values from a php table into a javascript function, however I am getting an Uncaught ReferenceError: "the php text" is not defined (anonymous function)
<html>
<script type="text/javascript">
function draw(name ) {
alert(name);
}
</script>
<body>
<canvas id="mycanvas" width=800 height=400></canvas>
</body>
</html>
<?php
$query = 'SELECT * FROM graph_table';
$result = mysql_query($query);
while($val = mysql_fetch_array($result)) {
$name = $val['test_name'];
echo '<script type="text/javascript"> draw('.$name .'); </script>';
}
?>
You need to add quote's between draw since you're passing text to it. draw(\''.$name.'\'); will make your problem go away.
Try this
<script type="text/javascript">
<?php
$query = 'SELECT * FROM graph_table';
$result = mysql_query($query);
while($val = mysql_fetch_array($result)) {
$name = $val['test_name'];
echo "draw('$name');";
}
?>
</script>
Try the php script inside . Mainly you should add js script just before .

Pass a php var to jQuery Function

How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.

Retrieve data from mysql by php to create flot graph

Hi i am trying to retrieve data from mysql database to create flot graph
can anyone walk me through this procedure or give me an idea of what to do
thanks
You probably want something like this. I haven't used flot but I looked at the example here.
<?php
//create array of pairs of x and y values
$dataset1 = array();
while ($row = mysql_fetch_assoc()) { //or whatever
$dataset1[] = array( $row['xvalue'], $row['yvalue'] );
}
?>
<script type="text/javascript">
//put array into javascript variable
var dataset1 = <?php echo json_encode($dataset1); ?>;
//plot
$(function () {
$.plot($("#placeholder"), [ dataset1 ]);
});
</script>
Adding upon the example from #Tom Haigh:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Flot Examples</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<?php
$server = "localhost";
$user="user";
$password="password";
$database = "some_database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
query = "SELECT x_axis_values, y_axis_values FROM some_table";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['x_axis_value'],$row['y_axis_value']);
}
?>
<script type="text/javascript">
$(function () {
var dataset1 = <?php echo json_encode($dataset1); ?>;
$.plot($("#placeholder"), [ dataset1 ]);
});
</script>
</body>
</html>
as #Tom Haigh say work well, but you need to add another code to work well, I was using the example, but I discover in the source code it add to the result quotes " so to avoid this just add the: intval to the array, example:
<?php
$query = "SELECT valx, valy FROM chart";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$d2[] = array (intval($row['valx']),intval($row['valy']));
}
?>
This depends largely on your environment and requirements. There's lots of free tools out there you can use. One example is Flot that lets you use jQuery to build graphs. There's link to documentation on the Google Code page.

Categories