Can Galleria be used with ajax data? - php

I really need some help here!
I have a page with images in groups of 1, 2, or 3. I click on an image and the class gets sent to some jquery ajax stuff to get the id(mysql) then this gets sent to a php file to build the html for the images to display on a div in my page. This bit works OK, but I'm trying to use the galleria plugin to show the image that haave been sent, but it just act like galleria is not there! If I hardcode some images in the dive. galleria works as it should!
here is my project.js file
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
});
});
This is my showproducts.php file
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be the string that you will return into the shownews div
$returnHtml = '';
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct the html to return
while($row = mysql_fetch_array($r)) {
$returnHtml .= "<img src='{$row['filename']}' />";
$returnHtml .= "<img src='{$row['filename1']}' />";
$returnHtml .= "<img src='{$row['filename2']}' />";
}
}
// display the html (you actually return it this way)
echo $returnHtml;
?>
This is how I'm calling galleria on the div
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
$('#shownews').galleria();
Can anyone help me out?
Thanks

try this one
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.ajax({url:'../inc/showprojects.php',
type:'POST' ,
method,async:false ,
data:{project: projectvalue},
success:function(data) {
$('#shownews').html(data);
}});
Galleria.run('#shownews');
});

I think, you need to call Galleria.run after recieve data from php
EDIT: ugly way - destroy gallery, if already running before inserting new images into div
if($('#shownews').data('galleria')){$('#shownews').data('galleria').destroy()} //destroy, if allready running
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
Galleria.run('#shownews');
});
and remove $('#shownews').galleria();
EDIT 2: use Galleria's .load api to load new data
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue},
function(data) {
$('#shownews').data('galleria').load(data);
},"json"
);
});
PHP
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be data array that you will return into galleria
$returnData = array();
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct datat object to return
while($row = mysql_fetch_array($r)) {
$returnData[] = array('image'=>$row['filename']);
$returnData[] = array('image'=>$row['filename1']);
$returnData[] = array('image'=>$row['filename2']);
}
}
// return JSON
echo json_encode($returnData);
?>
Galleria init:
(Gallery will be empty until you will load data into it)
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
Galleria.run('#shownews');

Try loading galleria after the ajax request has successfully completed. By doing this jquery waits until ShowNews has been rendered and then runs galleria.
$.ajax(
{
type: "POST",
url:'../inc/showprojects.php',
data:{project: projectvalue},
success: function(data)
{
$('#shownews').html(data);
},
complete: function()
{
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
$('#shownews').galleria();
}
});
I use this method whenever i gather the image data from a remote source. Hope this helps!

I tried this answer and other answers on the web and nothing worked. Then I moved galleria-1.3.5.min.js to the parent page and it worked. What an amazingly simple solution!

Related

Display notification only once - PHP - Codeigniter - JS

There is an ajax function, which displays a notification on the home page, however, every time I enter thehome page, or refresh the F5 page, the notification is displayed again.
How to fix this?
Is there any way to do this, using js jquery or PHP?
Below the code I have:
Controller
public function get_message()
{
$notification= array();
$notification['message'] = 'message test';
$notification['type'] = 1;
echo json_encode($notification);
}
Javascript
/*** variable ***/
var enum_toastr_type = {
success: 1,
info: 2,
warning: 3,
error: 4
}
/*** PageLoad start ***/
$(document).ready(function() {
toastr.options = {
closeButton: true,
positionClass: 'toast-bottom-right',
timeOut: '20000'
}
get_message_ajax();
});
/*** PageLoad end ***/
function show_message_toastr(mensagens) {
$(mensagens).each(function() {
switch (this.tipo) {
case enum_toastr_type.info:
toastr.info(this.message);
break;
case enum_toastr_type.success:
toastr.success(this.message);
break;
case enum_toastr_type.warning:
toastr.warning(this.message);
break;
case enum_toastr_type.error:
toastr.error(this.message);
break;
}
});
}
/*** Ajax start ***/
function get_message_ajax() {
$.ajax({
type: 'GET',
async: false,
contentType: 'application/json; charset=utf-8',
url: "helper/get_message",
success: (function(data) {
//console.log(data);
_obj = JSON.parse(data);
show_message_toastr(_obj);
}),
error: (function(erro) {
handle_ajax_error(erro);
})
});
}
/*** Ajax end ***/
For doing this you will need to set cookies in the browser to track if user has visited this page already. This would also prevent this on page reloads. You can use local storage to store any data in the browser.
// on page load check if user has not already visited this page
var visited = localStorage.getItem('visited');
if(!visited) {
// call your ajax function which displays message
get_message_ajax();
// lets set visited to true so when user loads page next time then get_message_ajax() does not gets called
localStorage.setItem('visited', true);
}
If you need something like; what if user logs out of the system, then you can clear the local storage on logout. Maybe you can add click listner on logout button and can clear local storage.
localStorage.clear(); // this will clear all website data in localStorage
// or you can update visited key;
localStorage.setItem('visited', false);
Or if you want something more advance like even user does not logs out and still you want to show message lets say if user visits after 1 day. Then you can store timestamp with key and parse it back when checking if user visited.
var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));
When accessing the key you can do something like this;
var object = JSON.parse(localStorage.getItem("key")),
dateString = object.timestamp,
now = new Date().getTime().toString();
// here you can compare two time strings and decide to show message.
For different implementation and ideas on how to manipulate time here is some help;
https://developer.mozilla.org/en-US/docs/Web/API/Storage
When do items in HTML5 local storage expire?

Compare user value to database and show result through ajax jquery

Guys m working on my first live project and i am stuck at a point, where i need help with ajax jquery. i can do this with PHP but i wanna do this with ajax.
Here if user enter a product code ,so i want to compare this product code value into my database and show product name in my other form ,which will open after user input value:
Here in first field i want product name:
Here in my table you can see product code and product name:
ok so here is my html code in last option when user enter product code
Here is jquery i am sending user data to 8transectiondata.php to compare
And this is php file and i want $data['product_name']; to show
Here's a generic answer.
JS FILE:
$(document).ready(function () {
$('#myButtonId').on('click', function () {
var code = $('#myCodeInputId').val();
if (code !== '') { // checking if input is not empty
$.ajax({
url: './my/php/file.php', // php file that communicate with your DB
method: 'GET', // it could be 'POST' too
data: {code: code},
// code that will be used to find your product name
// you can call it in your php file by "$_GET['code']" if you specified GET method
dataType: 'json' // it could be 'text' too in this case
})
.done(function (response) { // on success
$('#myProductNameInput').val(response.product_name);
})
.fail(function (response) { // on error
// Handle error
});
}
});
});
PHP FILE:
// I assumed you use pdo method to communicate with your DB
try {
$dbh = new PDO('mysql:dbname=myDbName;host=myHost;charset=utf8', 'myLogin', 'myPassword');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
exit('ERROR: ' . $e->getMessage());
}
$sql = "SELECT `product_name` FROM `products` WHERE `product_code` = :code";
$result = $dbh->prepare($sql);
$result->bindValue('code', $_GET['code'], PDO::PARAM_INT);
$result->execute();
if($result->rowCount()) { // if you got a row from your DB
$row = $result->fetchObject();
echo json_encode($row, JSON_UNESCAPED_UNICODE); // as we use json method in ajax you've got to output your data this way
// if we use text method in ajax, we simply echo $row
}
else {
// handle no result case
}
I know what you want to do, but without specific code the best I can do is give you a generalized answer.
When a user fills out a field, you want to post that field to the server, look up a product and return some stuff.
The basics are going to look like this.
$(document).ready( function(){
//rolling timeout
var timeout;
$('#field').on('keyup', function(e){
if(timeout) clearTimeout(timeout);
timeout = setTimeout( function(){
var data = {
"field" : $('#field').val()
};
$.post( '{url}', data, function(response){
if(response.debug) console.log(response.debug);
if(response.success){
//open other form
$('{otherFormProductField}').val(response.product);
}
}); //end post
},450); //end timeout
});//end onKeyup
}); //end onReady
Then in PHP, you have to process the request. Pull the field from the $_POST array, look it up in the Database. Then build a response array and send it back to the client as JSON. I like to build responses in a structure something like this.
{
success : "message", //or error : "message"
debug : "",
item : ""
}
Then in PHP I will do this.
ob_start();
..code..
$response['debug'] = ob_get_clean();
header("Content-type:application/json");
echo json_encode($response);
This way, you can still print out debug info (in side the output buffer calls ) when developing it and don't have to worry about it messing up the Json or the header call.
-note- Use a timeout, that you reset on each key press (a rolling timeout). What it does is reset the previous timeout each time the key is released. That way it only sends the request once the user quits typing (instead of sending request on every keypress). I have found 450 milliseconds to be about the perfect value for this. Not too long not too short. Basically once they stop typing for 450ms it will trigger the $.post

AJAX for successful php :: delete checked table list :: using hyperlink NOT input

Project Focus: Delete Multi-checked table list from form.
Specs:
1.) Delete actioned by using <a href> hyperlink (NOT <input type="submit"
2.) I'd like to action this with AJAX, including confirm & error/success responses.
Status of Delete Action: I've finally got my code working to delete multi-checkboxes. See the successful PHP Code Snippet below.
Note: the successful $_POST coding is currently being handled in the same page by using <input type="submit" name="delete>".
I've tried to get it to work, but no luck. Could someone please have a look through the coding & script to see if you can spot any errors?
My thoughts (but uncertain):
1) the ajax var formData is written wrong to achieve getting both $delete = $_POST['delete']; and $chkbx = $_POST['chkbx'];
2) Instead of .click for <a href"#" id="#btn_del" should maybe try for using .post
Form
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="recordsForm" id="recordsForm">
Button
UPDATED (for spec#1) updated the href to href="deleteRecord.php"
<li class="button" id="toolbar-del">
<a href="#" title="Delete" id="btn_del">
<span class="icon-16-delete dead"></span>
Delete
</a>
</li>
PHP Code Snippet:
This code is currently included at the bottom of the form. Later, I would like to move it as a function to a separate actions.php page that will include additional button actions (edit, duplicate, archive, etc). For now, I'll be happy to just move it to deleteRecord.php page & call it with this AJAX.
<?
// Check if DELETE button active, start this
$delete = $_POST['delete'];
$chkbx = $_POST['chkbx'];
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $chkbx[$i];
$sql = "DELETE FROM ".ID_TABLE." WHERE unit_id='".$del_id."'";
$result = mysqli_query($dbc,$sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=records_manager.php\">";
}else{
echo "Error: No luck";
}
}
mysqli_close($dbc);
?>
ajaxDELETE
// ajaxDelete.js
$(document).ready(function() {
// When TRASH button is clicked...
$('#btn_del').click(function(event) {
e.preventDefault(); // stop the form submitting the normal way
// and refreshing the page
// Get the form data // there are many ways to get this data using jQuery
// ---------------------------------- // (you can use the class or id also)
var formData = {
'chkbx' : $('input[name=chkbx]').val(),
'count' : $count[0]
// Process the form
// ================
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use
url : 'deleteRecord.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the .done(),
// promise callback
.done(function(data) {
window.console.log(data); // log data to the console so we can see
// Handle ERRORS
if ( ! data.success) {
if (data.errors.chkbx) {
$('.Records_Found').addClass('has-error');
$('.Records_Found').append('<div class="help-block">'+ data.errors.chkbx + '</div>');
}
} // end if ERRORS
else {
$('.Records_Found').append('<div class="alert alert-success" id="valid_success">'+ data.message + '</div>');
// After form submission,
// redirect a user to another page
window.location = 'records_manager.php';
}
})
.fail(function(data) { // promise callback
window.console.log(data); }); // show any errors in console
// NOTE: it's best to remove for production
event.preventDefault(); // stop the form from submitting the normal way
// and refreshing the page
}); // end submit button
}); // end document ready
deleteRecord.php
<?php
// FUNCTION to DELETE
// ===========================
// :checked existing unit data
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if ( empty($_POST['chkbx'])) // if empty, populate error
$errors['chkbx'] = 'No items have been checked yet.';
// ERROR! Return a response
if ( ! empty($errors)) {
$data['success'] = false; // any errors = return a success boolean of FALSE
$data['errors'] = $errors; // return those errors
} else {
// NO ERROR... Carry on // Process the form data
require_once('config.php'); // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.'.$dbc);
// Check if DELETE
$delete = $_POST['delete'];
$chkbx = $_POST['chkbx'];
$count = $_POST['count'];
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $chkbx[$i];
$sql = "DELETE FROM ".ID_TABLE." WHERE unit_id='".$del_id."'";
$result = mysqli_query($dbc,$sql);
}
// if successful redirect
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=records_manager.php\">";
}else{
echo "Error: No luck";
}
}
mysqli_close($dbc); // close DB connection
}
$data['success'] = true; // show a message of success
$data['message'] = 'Success!'; // and provide a true success variable
}
echo json_encode($data); // return all our data to an AJAX call
} // end else NO ERRORS, process form
?>
Digging through loads of bookmarks, I'd found an example of what I was hoping to achieve. After fiddling with snippets of codes, I've finally gotten the ajax to work as I'd hoped to achieve for this step of the project.
To hopefully assist others in their search for this, below, I've provided all coding for both ajax/jq/js & php that worked flawlessly in my tests.
How this code works
The button (a hyperlink outside of the form, NOT an input button) is linked to the deletedRecord.php, but the script overrides the link with e.preventDefault()
JQ is used to build the array of checked row IDs & send them to deletedRecord.php via AJAX
deleteRecord.php explodes the array, counts the total number of checked IDs, and finally loops through the query to delete each.
Upon successful completion, a response of 1 is echo'd back to trigger the success action
Hope this helps someone out there. If anyone sees any other faults I might've missed, please feel free to share for the greater good. Cheers.
ajaxDelete.js
Notes:
1.) Updated the image (button) href to href="deleteRecord.php"
2.) Researched & found a better approach that reduced the count to only the checked (I thought this would be more effective (faster) in case the table grew to a large number of rows.
$(document).ready(function() {
$('#btn_del').click(function(e) {
e.preventDefault();
page = $(this).attr("href");
ids = new Array()
a = 0;
$(".chk:checked").each(function(){
ids[a] = $(this).val();
a++;
})
// alert(ids);
if (confirm("Are you sure you want to delete these courses?")) {
$.ajax({
url : page,
type : "POST",
data : "id="+ids,
dataType : 'json',
success : function(res) {
if ( res == 1 ) {
$(".chk:checked").each(function() {
$(this).parent().parent().remove();
}) // end if then remove table row
} // end if res ==1
} // end success response function
}) // end ajax
} // end confirmed
return false;
}); // end button click function
}); // end doc ready
deleteRecord.php
<?php
require_once('config.php'); // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.'.$dbc);
$del_id = explode(",",$_POST['id']);
$count = count($del_id);
if (count($count) > 0) {
foreach ($del_id as $id) {
$sql = "DELETE FROM ".ID_TABLE."
WHERE unit_id='" . $id . "'";
$result = mysqli_query($dbc,$sql)
or die(mysqli_error($dbc));
} // end for each as
mysqli_close($dbc); // close MySQL
echo json_encode(1); // Return json res == 1
// this is used for the SUCCESS action
} // end if count > 0
?>

Ajax, JQuery & PHP - Passing PHP variable to JQuery

I have a page that allows users to upload multiple files and preview them without refreshing the page using jquery. In php I generate a unique file_id for each filename which I would then like to pass back in to JQuery and use it to load up the preview image etc.
I hope I have explained myself clearly.
Thanks for any pointers!
The PHP code:
// php code to upload file and generate unique file id. then...
if (move_uploaded_file($main_image, $file)) {
echo "success";
echo $file_id; // <--- I WANT TO PASS THIS VARIABLE BACK IN TO JQUERY
} else {
echo "error";
}
The J Query Code:
$(function(){
var btnUpload=$('#upload_main');
var mestatus=$('#mestatus');
var button=$('#button');
var files=$('#main_file');
new AjaxUpload(btnUpload, {
action: 'classified-ads/upload-classified-image.php?filenumber=1',
name: 'file1',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif|'')$/.test(ext))){
// extension is not allowed
mestatus.text('Only JPG, PNG or GIF files are allowed');
return false;
}
mestatus.html('<img src="extras/ajaxuploader/progress_bar.gif" height="30" width="340">');
button.html('Loading...');
$('#upload_main').removeClass('hover').addClass('upload_button_loading');
},
onComplete: function(file, response){
//On completion clear the status
mestatus.text('Photo Uploaded Sucessfully!');
button.html('Change Photo');
$('#upload_main').removeClass('upload_button_loading').addClass('upload_button');
//On completion clear the status
files.html('');
//Add uploaded file to list
if(response==="success"){
var file2 = file.replace(/\s/g, "_");
var file_id= file_id;
$('<div></div>').appendTo('#main_file').css('background-image', "url(/ht/classified-ads/temp_images/prev1_<?php echo $parsed_user;?>_"+file_id+")").addClass('main_success');
$("#image1_temp").val("main1_<?php echo $parsed_user;?>_"+file_id+"");
$("#thumbnail_temp").val("thumbnail_<?php echo $parsed_user;?>_"+file_id+"");
} else{
$('<li></li>').appendTo('#main_file').text(file).addClass('error');
}
}
});
});
In your PHP:
$response = array('result' => 'success', 'file_id' => $file_id);
echo json_encode($response);
In your jQuery:
var obj = $.parseJSON(response);
You would then check whether the response was a success with if (obj.result == 'success') and you'd get your file_id with obj.file_id
The simplest way is to do this allowing for MULTIPLE values to be returned:
// Make a variable to hold data to send back and keep track of your separator
$data = '';
$separator = 1;
// Put this in a loop, your loop will depend on how many file uploads you have
// I did not do the loop for you
if (move_uploaded_file($main_image, $file)) {
// echo "success"; Take this out
if ($separater==1){
$data .= $file_id;
} else {
$data .= ','.$file_id;
}
$separater++;
}
// Now outside the loop echo the results back
echo $data;
With this info echoed back you can manipulate it with Javascript (Jquery). Just use something like spli(','); which gives you an array of the file names you needed.
If you only want one value to come back, meaning you only have one file id to send back foregt everything about the loop and the PHP would be this:
if (move_uploaded_file($main_image, $file)) {
// echo "success"; Take this out
$data = $file_id;
// Now echo the results back
// Its been a while since I've done this but there may be times its ok to use return
echo $data;
} else {
// Handel error here
echo "error";
}
Now based off your code this echoed information should be picked up and processed here:
onComplete: function(file, response){ ... }
Instead of looking for "Success" you need to change your code to look for a file id or something like error instead (which is easier) like so:
if(response!=="error"){
// Now you can use your variable "response" here since it contains the file id
} else {
// Handle the error
}
The reason I gave you a long explanation about getting multiple values back is because that is more common as you start making more advanced forms and it wouldn't hurt to use now. This way you can allow multiple file uploads for example. What I do for example when using AJAX is echo back something like this:
1::value,value,value
Now I just split that into arrays first by :: and then by , this line for example says No Error Happened (1 which as we know is also TRUE) and here is your data: value,value,value which you can now use for things in your Jquery or just print to the document.
You should look at the Jquery AJAX page for in depth examples and explanations, it explains the trouble you ran into getting results back. Look at .done .success .complete especially.

sending javascript variable (from knockout.js) to php and return result

How can I go about accomplishing the following behavior.
upon getting an input from a knockout.js form send the variable to a page to be handled. The page uses PHP
The PHP page receives the input from the knockout.js form and runs some calculations and then returns the result
The variable is then received back on the original page and is then displayed via knockout
For example, say I have the following
//knockout_form.js
self.addItem = function() {
var itemNum = self.newItem; //variable received from knockout form
var returnedVariable = ???? **send itemNum to processing.php which will then return it**
self.itemNumbers.push(new ItemEntry(retunredVariable, "$20.00")); //
}
I know that jQuery/Ajax can be used to post to processing.php, but how do I return the calculated data from processing.php back to the javascript page?
edit below. The data appears to be sent to processing.php (shows up in the network tab) but the alert isn't showing.
// Operations
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum),function(data) {
alert(data); //this does not appear
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
}
}
Here's the php
//$result = $_GET['itemNum'];
$result = "test"; //set it just to be sure it's working
echo json_encode(array("result" => $result));
Knockout doesn't have any special way of doing ajax calls itself, typically you would use jQuery. See http://knockoutjs.com/documentation/json-data.html.
So something like:
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum,function(data) {
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
});
}
This assume that your PHP script is outputting valid JSON. Something like:
<?php
$result = doCalculations($_GET['itemNum']);
echo json_encode(array("result" => $result));
?>
This is untested, but you get the idea.

Categories