Iframe or Ajax ? - ajax

at the moment I've got a simple bit of code to display messages on a site.
the page includes an iframe that self refreshes every 90 seconds, and the iframe displays the contents of a mysql table limited to the most recent (30) posts.
I've been reading up on ajax and it still confuses me, i've never got it working properly, and would like to know, for a small task like this, is it really worth it ?
<head>
<META HTTP-EQUIV="refresh" CONTENT="90; URL=">
</head>
<body>
<?
$newsarray = array();
$sql = "SELECT * FROM `news` ORDER BY `date` DESC LIMIT 30";
$result = mysql_query($sql);
if(mysql_error()) { print mysql_error(); } else {
while($stuff = mysql_fetch_assoc($result))
{ array_push($newsarray, $stuff); }
foreach($newsarray as $newsstory) { ?>
<div class="newsstory">
<h2><? echo $newsstory['headline']; ?></h2>
<div><? echo $newsstory['story']; ?></div>
<label>By <? echo $newsstory['user']; ?> on <? echo $newsstory['date']; ?></label>
</div>
<? } ?>
</body>

It would be as simple as adding the jQuery library to your exsiting page and adding the following code:
<div id="result"></div>
Manually Fetch Page
<script language="javascript">
function updatestuff() {
$.ajax({
url: 'mypage.php', // The source
cache: false, // Make sure results are not cached
success: function (data) {
$('#result').html(data); // Update data once retrieved
}
});
}
setInterval("updatestuff()",90000); // In Milliseconds
</script>
This would run the function updatestuff() every 90 seconds which would update the <div> with content fetched from mypage.php.

If you want something that automatically updates every 30seconds then definitely Ajax is the way to go.
Some say (myself include) that you'd be insane not to use jQuery to do this.

Related

AJAX example in magento

Hello everyone,
I am a newbie to Magento. I want to learn **ajax process in Magento.** Can anyone help me to understand ajax in Magento with one simple example?
Your help will be highly appreciated.
I give you a simple example for you. To work with basic jQuery Ajax in Magento you have work in phtml page and Controller.
Just add the script in phtml page:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".like-result").click(function() {
//alert(this.id);
var id = this.id;
//alert(custid);
jQuery(".notify-status").hide();
jQuery(".notify-loader").show();
jQuery.ajax({
type: "POST",
data: 'pid=' + id,
url:'http://192.168.2.3/subhranil-demo/blog/index/likecount',
success:function(response){
if (response) {
jQuery(".notify-loader").hide();
jQuery(".notify-status").show();
jQuery("#un"+id).html(response);
}
}
});
});
});
</script>
In the above script under jQuery.ajax you can also see type, data, url. type is used for sending process like POST or GET; in data, you will send information to the controller; in URL, you can declare the controller path. Here I have a 'blog' module and I write the public function under 'index' controller and I give the function name 'likecount'. Also here my base path is http://192.168.2.3/subhranil-demo/. So I add the link to URL as following structure: http://192.168.2.3/subhranil-demo/blog/index/likecount.
Now I go to 'IndexController.php' in my controller's folder of blog module and open it. Under the class I add the following function:
public function likecountAction()
{
$blogload = Mage::getModel('blog/blog')->load($_POST['pid']);
$newid = $blogload['like']+1;
$data = array('like'=> $newid);
$blogload->addData($data);
try {
$blogload->setId($_POST['pid'])->save();
echo $newid;
} catch (Exception $e){
echo $e->getMessage();
}
}
Here in the Blog Database, I have the fields like pid (as a primary key) and like. the function works like that when you click on 'like-result' class the like increase +1.
My div structure also like that:
<?php
$allCollection=Mage::getModel("blog/blog")->getCollection();
$allCollection->addFieldToFilter('status',1);
if ($allCollection->count() >= 1)
{
$news = array();
?>
<div class="blog clearfix">
<?php
foreach ($allCollection as $news)
{?>
<p class="like-result" id="<?php echo $news->getId(); ?>"> <?php echo $news->getLike(); ?> </p>
<a style="display: none;" class="notify-loader"><img src="http://www.sendhersomething.com/skin/frontend/megatron/default/images/ajax/notify-loader.gif"></a>
<a style="display: none;" class="notify-status"><img src="http://www.sendhersomething.com/skin/frontend/megatron/default/images/ajax/ststus.png"></a>
<?php } ?>
</div>
<?php } ?>
Try this!

using AJAX to check for database updates and notify

I need an ajax script to ckeck if there is an entry of data in the database and show notification on the page for each entry .I want the notification to be shown to every user viewing that page .
I tried the following but it is not giving needed output:
main.html
<html>
<head>
<script type='text/javascript' src='ajx.js'></script>
</head>
</html>
pop.php
<?php
try{
$con=mysql_connect("localhost:3306", "root", "") or die(mysql_error()) ;
$q = mysql_query("SELECT `user`.`name`,`user`.`page` FROM `people`.`user` ORDER BY `user`.`index` DESC",$con);
if(!$q)
{
throw new Exception('Uncaught Exception occurred');
}
}
catch(Exception $e)
{
Echo "";
}
$results = mysql_fetch_assoc($q);
echo json_encode($results);
?>
ajx.js
$.ajax({
url: "pop.php",
dataType: "json",
success: function(json){
var dataArray = JSON.decode(json);
dataArray.each(function(entry){
alert(entry.name);
}
}
});
I am not getting result when i load main.html .I think some statement is needed to print the result.
which specific aspect of that script would you like clarification on writing? do you have a specific question in regards to where you might be having problems?
You could use something like this:
PHP File: (get_notifications.php)
$q = /*your query to database*/
$query = mysql_query($q, $dbConnect);
$results = mysql_fetch_assoc($query);
echo json_encode($results);
Javascript File:
$.ajax({
url: "get_notifications.php",
dataType: "json",
success: function(json){
var dataArray = JSON.decode(json);
dataArray.each(function(entry){
alert(entry.valueName);
}
}
});
In the javascript file "valueName" refers to the data key that you would like to output. For example if you "SELECT name FROM people", and you want to output their name it would be entry.name. You can also replace the alert with an append or something to put the data in a div or on the page.
Let me know if you need any further clarification on any of these parts. This should be able to give you a pretty good start. Hope it helps.
Clarification:
The file your page loads should only contain your layout and HTML as well as the script tag to include your js.
Then your php for the ajax call should be in a separate file that is called by the Ajax, not included on the page that is being loaded. Hope that makes sense.
I looked over your code and made a few modifications. This is the exact code I used that worked on my system with a test database that I used: (you will need to tweak it to your system environment)
main.html:
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type='text/javascript' src='ajx.js'></script>
</head>
<body>
Your body content in here...
</body>
</html>
pop.php:
<?php
include __DIR__.'/include/Configurations.php';
include __DIR__.'/include/DatabaseConnect.php';
global $databaseConnection;
try{
$q = mysql_query("SELECT name, page FROM users", $databaseConnection);
if(!$q)
{
throw new Exception('Uncaught Exception occurred');
}
}
catch(Exception $e)
{
Echo "";
}
$results = Array();
$i = 0;
while ($row = mysql_fetch_assoc($q))
{
$results[$i] = $row;
$i++;
}
echo json_encode($results);
?>
ajx.js:
$(document).ready(function(){
$.ajax({
url: "pop.php",
dataType: "json",
success: function(json){
var i;
for(i=0; i<json.length; i++)
{
alert(json[i].name);
}
}
});
});
When you integrate it into your actual project you can just replace the alert() function with whatever logic and output methods you want in order to get the content properly on the page. Let me know how this goes for you or if there is anything else I can help with.

CodeIgniter Ajax form - submitting form

I'm new to stackoverflow and to CodeIgniter and I'm currently experimenting on some simple code examples I have found on the Internet in order to get a start. The one I'm working on right now is a form which uses CI and Ajax (jQuery) along with saving the inputs of the form in a database and then display the most recent of them on the same page as the form.
If I confused you it's the 4.7 application example from here. The initial source code lies here but I have modified it in order to work with the latest release of CI and I quote all my MVC files just below.
Controller:
<?php
class Message extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Message_model');
}
function view()
{
//get data from database
$data['messages'] = $this->Message_model->get();
if ( $this->input->is_ajax_request() ) // load inline view for call from ajax
$this->load->view('messages_list', $data);
else // load the default view
$this->load->view('default', $data);
}
//when we pres the submit button from the form
function add()
{
if ($_POST && $_POST['message'] != NULL)
{
$message['message'] = $this->security->xss_clean($_POST['message']);
$this->Message_model->add($message);
}
else
{
redirect('message/view');
}
}
}
?>
Model:
<?php
class Message_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function add($data)
{
$this->db->insert('messages', $data);
}
function get($limit=5, $offset=0)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $offset);
return $this->db->get('messages')->result();
}
}
?>
Views
default.php:
<!-- called using message/view -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<?php echo base_url('js/jquery-1.8.1.min.js'); ?>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
</script>
</head>
<body>
<?php echo form_open("message/add"); ?>
<input type="text" name="message" id="message">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
<div id="content"></div>
</body>
</html>
messages_list.php:
<!-- called from ajax call -->
<ol>
<?php foreach ($messages as $cur): ?>
<li><?php echo $cur->message; ?></li>
<?php endforeach; ?>
</ol>
The problem mainly lies in the 1st of the views (default.php). That is, if I omit the e.preventDefault(); line from the javascript code then the form loads a different page (message/add as the form action parameter implies) which is a blank page, also cancelling the ajax behavior of my application that way.
On the other hand, if I actually add this line then the add method of my message controller isn' t called, thus not adding what I've typed into the database.
Finally, I tried the following js code instead of the other above:
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
but that way it seems as the $.post() crashes because nothing is executed in the function which is supposed to run on a successful post() call.
Any help appreciated and sorry for the big post. :)
You are correct that you must call e.PreventDefault();, but you must also deal with the response from the callback function, which you are not. The callback takes a few arguments but the first one is what you're interested in, it is the response from your server. I've denoted it as r below:
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function(r) {
//do something with r... log it for example.
console.log(r);
});
});
});
I've also removed $.("#content").load(...);. This would actually perform another AJAX request when the first one is complete.
Now, inspecting your controller...please refrain from using $_POST. CodeIgniter provides you with $this->input->post() as part of the Input Library. If you turn on Global XSS filtering in config/config.php you won't have to xss clean it either. You can clean on a post-by-post basis by using $this->input->post('name', true);
I recommend this instead:
function add(){
$m = $this->input->post('message', true);
if($m){
$this->Message_model->add($m);
}
}
The problem doesn't lie with the CI, its the JS that is wrong,
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("<?php echo base_url(); ?>/message/view");
$('#message').val('');
});
});
});
The e.preventDefault() is used to stop the default behaviour of the submit button (which will take you to message/add), which we don't want. You are correct in adding the URl paramter to the $.post() function later, but in the callback function, the .load loads the URL that is passed to it into the #content, so without passing any url, of course there won't be anything to load.

parsing dojo tundra dijits in ajax response

I am having massive problems re-parsing my dojo elements in an ajax response in Zend framework. I have a simple validationTextBox and a submit button. When the index page is first rendered, all the dojo/dijit tundra styles/attributes etc are parsed correctly. However, when I have an ajax call that rebuilds the dojo form and posts it back to the Index View. The form if posted back ok but the tundra styles are no longer working. I have tried so many different things but have spent many hours getting nowhere. I thank anyone in advance who attempts to assist. I have added the simplest example to this post to explain.
layout.phtml
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo $this->doctype();
?>
<html>
<head>
<meta content="text/html; charset=UTF-8" />
<script>
function showForm()
{
dojo.xhrGet( {
url: "../public/index.php?ajax=true",
// The load function is called on successful response from server
// It inserts the response to the HTML div “put_here” placeholder
handleAs:"text",
sync:true,
load: function(response, ioArgs)
{ dojo.byId("welcome").innerHTML = response;
return response;
},
// The error function displays error message if server does not
// respond right
error: function(response, ioArgs)
{
console.error("HTTP status code: ", ioArgs.xhr.status);
return response;
}
});
// dojo.parser.parse(dojo.byId("welcome"));
}
</script>
<?php
echo $this->headTitle();
echo $this->headStyle();
echo $this->headScript();
echo $this->dojo()->setDjConfigOption('parseOnLoad', true);
echo $this->dojo()->addStyleSheetModule('dijit.themes.tundra');
echo $this->dojo();
?>
</head>
<body class='tundra'>
<div id='ajaxcontent'>
<?php echo $this->layout()->content; ?>
</div>
</body>
indexController.php
<?php
//require_once '../public/js/custom.js';
class IndexController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('index', 'html')
->initContext();
}
public function indexAction()
{
$form = new Zend_Dojo_Form('dojoForm', array('dojotype'=> 'dijit.layout.ContentPane'));
$element = new Zend_Dojo_Form_Element_ValidationTextBox('TestBoxName',
array(
'id' => 'TextBoxId',
'required' => true
)
);
$button = new Zend_Dojo_Form_Element_Button('TestButton',
array(
'value'=> 'Button',
'onclick' => 'showForm()'
));
$form->addElements(array($element,$button));
$this->view->form = $form;
}
}
View index.phtml
<div id="welcome" >
<?php
echo $this->form;
?>
Try to run your page through the http://validator.w3.org/ - it is probably the DOCTYPE, and issues with non-closed tags?
The line with addStyleSheetModule simply adds a css file, the class set on your <body> asserts, that all nodes below body 'inherits' the theme (CSS selectors). Selectors however is highly depending on wellconstructed DOM (hence the validation)
But the main issue here seems to be that the dijit classes are not set - probably because data-dojo-type's are not initialized. There are two approaches
1.1 In layout.phtml
function showForm() { dijit.byId('welcome').set('href', '../public/index.php?ajax=true'); }
1.2 In index.phtml
Create a contentpane (which defaults to parseOnLoad) in your <div id='welcome'..
<div id="welcome" data-dojo-type="dijit.layout.ContentPane">
2.0 call parser manually
load: function(response, ioArgs)
{ var domnode = dojo.byId("welcome");
domnode.innerHTML = response;
dojo.parser.parse(domnode);
return response;
}

AJAX Div Refresh with PHP

I am trying to refresh some elements on my page every so often. I know theres a million topics on here about that and I have tried to get mine working, but here is what I need to refresh..
This is the code that gets generated when the page loads:
<div id="galleria">
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 100; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
?>
</div>
I would like to automatically refresh this every 10 seconds but not reload the page. I have read up on ajax and it seems this is possible but I cannot seem to get it to work.
All this is doing is showing the galleria div, and loading the 100 images inside the div. Then the galleria script takes over and displays it nicely. Will AJAX work better or JQuery?
Thank you for your help!
"Will AJAX work better or jQuery?" -- AJAX is a technique, jQuery is a library. As it turns out, jQuery has an excellent API for AJAX.
Let's call this bit of PHP "galleria.php". On original page load, it is inserted into the parent PHP page using good ol' <?php include('galleria.php')?>. Now the end user is seeing the full initialized page.
To update it, you have a number of AJAX options available, but the easiest is to include jQuery on your page and then you can use .load() in a script:
var updateGallery = setInterval(function() {
$('#someDiv').load('galleria.php');
}, 10000);
There's room for tweaking... maybe galleria.php doesn't include the <div id="galleria">, which is set on the page. In which case you would load right into #galleria instead of #someDiv and save yourself an unnecessary container. Maybe you cache the $('#someDiv') object by declaring it in a different scope so that it can be re-used. But this is the general gist.
Use setInterval function with ajax call.
http://jquery-howto.blogspot.com/2009/04/ajax-update-content-every-x-seconds.html
As I wrote here you can fill a div with a jQuery ajax call.
<html>
<head>
<script type="text/javascript">
function refresh_gallery(){
$.ajax({
type: "POST",
url: "generate_gallery.php", // your PHP generating ONLY the inner DIV code
data: "showimages=100",
success: function(html){
$("#output").html(html);
}
});
}
$(function() {
refresh_gallery(); //first initialize
setTimeout(refresh_gallery(),10000); // refresh every 10 secs
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

Resources