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();
?>
Related
I want to return multiple records instead of just 1 row.
JSON now returns only 1 row and I guess I need to add a while loop but not sure the right way to code it.
.js
function getq() {
var q = $("#q").val();
$.post(
'getq.php',
{q: q},
function(data) {
console.log(data);
}, "json"
);
}
getq.php
$q = $_POST['q'];
include("connect.php");
$sql = ("SELECT xxx FROM yyy WHERE zzz = $q");
if ($results=mysqli_query($db,$sql)) {
$result = $results->fetch_assoc();
echo json_encode($result);
}
EDIT:
I created the same case as yours on my pc, I used this javascript:
$.post('getq.php', {q: q}, function(data) {
console.log(data);
}
);
And this php (getq.php) file:
<?php
// Create connection
$mysqli = new mysqli( "localhost", "user", "passw", "db");
$q = $_POST['q'];
if ($results = $mysqli->query("SELECT xxx FROM yyy WHERE zzz = $q", MYSQLI_USE_RESULT)) {
$result_set = mysqli_fetch_all($results,MYSQLI_ASSOC);
echo json_encode($result_set);
$results->close();
}
?>
source: W3Schools
I'm new in Ajax and JSON notation, so I'm trying to get data from differents tables of a Database, data like country names, state names, departament name, job position etc. and I've seen examples how through JSON can get data but just from a single table, can you give me a little help how can I do it with more than one table and keep it in an array.
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
Html file:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
If you want to have the results from multiple queries in one array you can add each result to a key. F.i. if you querying table table1 to tablen ...
// define the array that will contain all result sets
$array = [];
// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}
// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}
// return the results formatted as json
return json_encode($array);
In javascript you can access the results for table1 with data->table1.
Tip
Use mysqli instead of mysql. It is the improved version of mysql. Check the answers for this question for some background.
I have a dropdown list that is populated from a mySQL database using PHP. How do I preselect the first option in the dropdown bearing in mind that these values may not always be the same?
This is the code in my HTML:
function loadparameters(selobj, url, nameattr) {
$(selobj).empty();
$.getJSON(url, {}, function (data) {
$.each(data, function (i, obj) {
$(selobj).append($("</option><option>
</option>").val(obj[nameattr]).html(obj[nameattr]));
});
});
}
$(function () {
loadparameters($('select#parameterType').get(0),
'GetParameter.php?GetParameter=parameterType', 'parameterType');});
..and the PHP Script:
<?php
if(!empty($_GET['GetParameter']))
{
$list = $_GET['GetParameter'];
$qry='';
switch($list)
{
case 'parameterType':
{
$qry = "SELECT parameterType FROM Parameters";
break;
}
}
if(empty($qry)){ echo "invalid params! "; exit; }
$dbconn = mysql_connect('*******','*******','******')
or die("DB login failed!");
mysql_select_db('*****', $dbconn)
or die("Database does not exist! ".mysql_error($dbconn));
$result = mysql_query($qry,$dbconn)
or die("Query $qry failed! ".mysql_error($dbconn));
$rows = array();
while($rec = mysql_fetch_assoc($result))
{
$rows[] = $rec;
}
mysql_free_result($result);
mysql_close($dbconn);
echo json_encode($rows);
}
?>
The only thing that seems wrong in your code is this line
$(selobj).append($("</option><option></option>").val(obj[nameattr]).html(obj[nameattr]));
Why do you close close/open/close the option tag?
Shouldn't it be that way? (I've indented the code for readability)
$(selobj).append(
$("<option></option>") // only open/close tag
.html(obj[nameattr]) // this injects HTML
);
OR
$(selobj).append(
$("<option></option>") // only open/close tag
.text(obj[nameattr]) // this only injects text
);
If you fix this, then the first option should be preselected. The reason why it isn't preselected is because your browser might automatically fix this issue by itself with an empty option.
Also, I find the syntax below more readable:
var option = $("<option></option>").text(obj['nameattr']);
$(selobj).append(option);
I have to make a JSON ajax request and have an array in return.
i found this code on multiple other questions (edited to my problem):
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
var data = response.get_response;
for (i in data){
hej.push([i,data[i]]);
}
alert(hej[0]);
}
In the php part, i have a database from which i need the data i have have 5 columns pr. row. I only have one row, and i need all five columns in the array.
$sql = "SELECT * FROM 'table'
LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = Array();
while($row = mysql_fetch_array($result))
{
$storeArray[0]=$row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode($storeArray);
echo $json;
I know im doing something wrong, and i am new to programming. I need to be able to access all column values in my javascript after the call and use them in other functions, but i cant get it to return.
I would really appriciate help, with both the javascript and the php if there are errors in either.
It should be:
function ajax_search(){
$.getJSON('test2.php',function(response){
// response.column1
// response.column2
// response.column3
// for array push:
var hej = [];
$.each(response, function(key, val) {
hej.push(val);
});
alert(hej[0]); // it will alert column1
});
}
and MySQL:
$sql = "SELECT `column1`, `column2`, `column3`, `column4`, `column5` FROM `table` LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$json = json_encode($row);
echo $json;
Try this:
Javascript Code:
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
$.each(response.results, function(key, val) {
hej.push(val);
});
alert(hej[0]);
});
}
PHP Code:
<?php
$sql = "SELECT * FROM 'table' LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = array();
while($row = mysql_fetch_array($result)) {
$storeArray[0]= $row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode( array('results' => $storeArray ) );
echo $json;
?>
Hope this helps.
Why use response.get_response?
var hej[];
function ajax_search(){
$.getJSON('test.php',function(data){
$.each(data, function (i,item) {
hej.push([i,item]);
}
alert(hej[0]);
}
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");
?>