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.
Related
I'm trying to move some AJAX code from a standalone file into a function in my controller and can't seem to get it to display the JSON data in the autocomplete function in the view. I've verified that the function does return JSON encoded data by visiting the function URL directly.
Here's my JavaScript from the head of my view:
<script type="text/javascript">
$(document).ready(function(){
var ac_config = {
source: <?php echo base_url() . 'admin/lookup_tmdb_movie_titles'; ?>
select: function(event, ui){
$("#title").val(ui.item.title);
$("#year").val(ui.item.year);
$("#imdb_link").val(ui.item.imdb_link);
},
minLength:2,
position: {
my: "left top",
at: "left bottom",
collision: "none",
of: "#title.ui-autocomplete-input.ui-autocomplete-loading"
}
};
$("#title").autocomplete(ac_config);
});
</script>
Here's the function in the admin controller (I'm just using hard-coded test data until I get this working correctly):
function lookup_tmdb_movie_titles()
{
$term = 'test';
// TEST DATA
$title['title'] = 'test';
$title['label'] = 'test (2012)';
$title['value'] = 'test';
$title['year'] = '2012';
$title['imdb_link'] = 'testlink';
$matches[] = $title;
// convert into JSON format and output
$matches = array_slice($matches, 0, 5);
$this->output->set_output( json_encode($matches) );
}
I've also tried outputting the JSON the following two ways, all of which work if I go to the function directly via the URL, but none of which work in the view itself.
print json_encode($matches);
and
$data['json'] = json_encode($matches);
$this->load->view('admin/json_view', $data);
I've looked at a lot of posts on StackOverflow and via Google (hence the different output methods above) but nothing has seemed to solve the issue yet.
first you should try this:
source: "<?php echo site_url(admin/lookup_tmdb_movie_titles); ?>"
then this could be:
function lookup_tmdb_movie_titles()
{
$term = 'test';
// TEST DATA
$title['title'] = 'test';
$title['label'] = 'test (2012)';
$title['value'] = 'test';
$title['year'] = '2012';
$title['imdb_link'] = 'testlink';
$matches[] = $title;
// convert into JSON format and output
$matches = array_slice($matches, 0, 5);
var_dump($matches); //comment this if everythings ok
// echo json_encode($matches); ->uncomment this if everythings ok
}
then open firebug launch the ajax request and check the response in console.
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.
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>
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.
I appreciate any and all help. I am a beginner with little jQuery/AJAX experience and I have been going crazy trying to figure out why I can't figure this out.
I'm writing a Facebook page application that has the user grant permissions and upload a video to the page. All of this works fine and dandy. This is not so much a Facebook API related issue as it is an ajax issue (at least I think).
Basically, I am trying to gain control of the page IN SOME WAY after the user uploads a video. I am using the [malsup jQuery Form Plugin][1] to have the resulting page (which is a page on Facebook displaying returned JSON values) load in a hidden iframe.
I am able to get ajaxStart to fire, and I've tested this by having it change the background color or print an alert message when I click "Upload". However, when the upload completes (and it does complete successfully), NOTHING ELSE HAPPENS. The returned JSON values load in the hidden iframe and the page sits there. I have tried getting ajaxComplete, ajaxStop and ajaxSuccess to fire, but none of them do for whatever reason.
So overall, here is what I am trying to accomplish:
- I want to redirect the user or make some hidden content appear after the file upload completes. I don't even care if there's errors. I just need SOMETHING to happen.
- I am using the jQuery Form Plugin because I am not unfortunately not advanced enough to figure out how to use that value and do something with it, but if anyone can steer me in the right direction, that would be appreciated.
And finally, here is my code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
iframeTarget: '#output2',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
// bind form using 'ajaxForm'
$('#theform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
</script>
<script type="text/javascript">
jQuery().ready(function(){
$('body').ajaxStart(function() {
$(this).css("background-color","red");
});
$('body').ajaxSend(function() {
$(this).css("background-color","blue");
});
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
$('body').ajaxStop(function() {
$(this).css("background-color","purple");
});
});
</script>
</head>
<body>
<?php
$app_id = "xxxxxxx";
$app_secret = "xxxxx";
$my_url = "xxxxxx";
$video_title = "xxxxxxxxx";
$video_desc = "xxxxxxxxx";
$page_id = "xxxxxxxx";
$code = $_REQUEST["code"];
if(empty($code)) {
// Get permission from the user to publish to their page.
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&display=popup&scope=email,publish_stream,manage_pages";
$current_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($current_url != $dialog_url)
{
echo('<script>window.location ="' . $dialog_url . '";</script>');
}
} else {
// Get access token for the user, so we can GET /me/accounts
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
$accounts_url = "https://graph.facebook.com/me/accounts?" . $access_token;
$response = file_get_contents($accounts_url);
// Parse the return value and get the array of accounts we have
// access to. This is returned in the data[] array.
$resp_obj = json_decode($response,true);
$accounts = $resp_obj['data'];
// Find the access token for the page to which we want to post the video.
foreach($accounts as $account) {
if($account['id'] == $page_id) {
$access_token = $account['access_token'];
break;
}
}
// Using the page access token from above, create the POST action
// that our form will use to upload the video.
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&access_token=". $access_token;
// Create a simple form
echo '<form action=" '.$post_url.' " method="POST" enctype="multipart/form-data" id="theform">';
echo 'Please choose a file:';
echo '<input name="file" type="file">';
echo '<input type="submit" value="Upload" id="button-upload" />';
echo '</form>';
}
?>
<iframe id="output2" name="output2"></iframe>
</body></html>
Thank you for your help!!
It seams you are getting an Ajax Error. I don't see any error handler in your code. Could you try to add an error handler as follows
<script>
$(document).ready(function(){
$(document).ajaxError(function(e, jqxhr, settings, exception) {
alert(exception);
})
})
</script>
I have played around with file uploads, and there are a complicated beast because of all the security that browsers have for protecting users file systems and whatnot.
On to your problem, I think that there is a good chance that your AjaxForm jQuery plugin doesn't connect properly to the global Ajax state for Jquery. Even if it did, I would say that tapping into the global Ajax state is a bad design. If you add any other ajax requests to this page, then your ajaxComplete, ajaxStop, etc. functions are going to start getting called.
Your better approach is to use the callbacks provided by the AjaxForm plugin. Lets focus on this first part of your code.
Does this work?
success: showResponse // post-submit callback
...
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
If so, could you replace this:
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
With this:
function showResponse(responseText, statusText, xhr, $form) {
$(this).css("background-color","green");
}
I believe that using the success: callback is the intended use of the AjaxForm plugin.
The jquery ajaxSend or ajaxStart throws some kind of an error and the document does not execute ajaxComplete. I tried to fix the bug for quite a while and was only able to find a workaround:
function hideAjaxIndicator() {
$('#ajax-indicator').hide();
}
$(document).ready(function () {
setTimeout(hideAjaxIndicator, 1000);
});
You can add this to .js file.