Ajax script not loading anything and no requests being sent - php

This script is supposed to run a jQuery Ajax script every second, it is supposed to fetch all newer posts then put them on top of the original ones. But at the moment nothing is happening, it loads the initial posts but nothing else. Firebug console is reporting no errors, or no Ajax requests being sent at all. Can you see anything wrong with this script at all that could cause this? Thanks :)
Source code -
index.php(i left out css):
<?php
include('config.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Twitter Style load more results.</title>
<link href="frame.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(function () {
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg=" + ID,
cache: false,
success: function (html) {
$("ol#updates").prepend(html);
$("#more" + ID).remove();
}
});
} else {
}
return false;
};
});
</script>
</head>
<body>
<div id='container'>
<ol class="timeline" id="updates">
<?php
$sql=mysql_query("select * from updates ORDER BY item_id DESC LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['item_id'];
$message=$row['item_content'];
?>
<li>
<?php echo $message; ?>
</li>
<?php } ?>
</ol>
</div>
</body>
</html>
ajax_more.php -
<?php
include("config.php");
if(isset($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$result=mysql_query("select * from updates where item_id<'$lastmsg' order by item_id desc limit 9");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['item_id'];
$message=$row['item_content'];
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
?>
<?php
}
?>

Some of the code in the beginning looks wrong. This should work. It will call the oneSecondFunction every second:
$(document).ready(function() {
setInterval(oneSecondFunction, 1000);
function oneSecondFunction() {
//console.log('run oneSecondFunction');
var ID = $(this).attr("id");
if(ID) {
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({ type: "POST", url: "ajax_more.php", data: "lastmsg="+ ID, cache: false,
success: function(html){
$("ol#updates").prepend(html);
$("#more"+ID).remove();
}
});
} else {
} return false; };
});

i quoted out the section where it gets the id, because 'this' wasn't referring to anything.
<script type="text/javascript">
$(function() {
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
//var ID = $(this).attr("id");
var ID = '1';
if(ID){
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").prepend(html);
$("#more"+ID).remove();
}
});
}
return false;
}
</script>

Related

Auto Check If statement php

How i can check $enjaz_youm every second in the index page for my system
<?
if($enjaz_youm == 80) {
echo "<script>";
echo "alert('This is an alert from JavaScript!');";
echo "</script>";
}
?>
Thanks
You can try this.
<?php
if ($_POST['action']=='enjaz_youm') {
//do your checks here
if ($enjaz_youm==80) echo '1';
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var refreshId = setInterval( function()
{
var request = $.ajax({
url: "<?=$_SERVER['PHP_SELF']?>",
type: "POST",
data: {action : 'enjaz_youm'},
dataType: "html"
});
request.done(function(msg) {
if (msg=='1') {
alert("This is an alert from JavaScript!");
}
});
}, 1000);
});
</script>
</head>
<body>
</body>
</html>

Session preservation

I read all other question but nothing really helped.
I have one page with display and other php files supporting it but when I pass a POST and make a $_SESSION['view'] out of it with another POST request but not same one the $_SESSION['view'] is gone.
So in practic when user change view from four months (default) to one month and then click NEXT view gets back to four months.
Display Page
<?php
session_start();
$dateb = (new DateTime())->getTimestamp();
$_SESSION['usrdate'] = $dateb;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="site.css" type="text/css" rel="stylesheet">
<script>
$(document).ready(function () {
$("#four").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
view: "four"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
$("#one").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
view: "one"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
$("#next").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
toggle: "next"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
});
</script>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="nav"></div>
<div id="loginform"><?php
/*require "navigation.php";*/
if (!isset($_SESSION['id'])) {
include "logon.php";
} else {
echo "<a href='logoff.php'>Logout</a>";
}
?>
</div>
<div id="loadplace">
<?php
if (isset($_SESSION['id'])) {
include "switcher.php";
}
?>
</div>
<div id="tog"><button type="button" id="prev">Prev</button>
<button type="button" id="next">Next</button></div><br/><br/>
<div id="view"><button type="button" id="four">Four</button>
<button type="button" id="one">One</button></div>
</body>
</html>
Script
<?php
session_start();
$_SESSION['view'] = $_POST["view"];
$_SESSION['toggle']= $_POST["toggle"];
$tog = $_SESSION["toggle"];
if ($_SESSION['view'] == "four") {
include_once "four_m.php";
} elseif ($_SESSION['view'] == "one") {
include "calendar.php";
} elseif ($_SESSION['view'] == "week") {
include "week.php";
} elseif ($_SESSION['view'] == "day") {
include "day.php";
} else {
include "four_m.php";
}
?>

php function call with ajax

I am trying to call a php function when an HTML button is clicked.i have done some searching and found that its impossible to do this directly and i should use ajax.
so this is my attempt so far which is not working.this is my test.php and the function is also in this page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.NextPage').on('click', function() {
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
alert(response);
}
});
});
});
</script>
</head>
<body>
<button type="button" class="NextPage">go to nextpage</button>
<?php
if (isset($_POST['x'])) {
if ($_POST['x'] == 1) {
$data = function1();
echo json_encode($data);
exit;
}
}
function function1() {
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>
get the value of the x from ajax call.
$x = $_POST['x'];
then use it.
EDIT
First you have to check weather your variable is set or not..
if(isset($_POST[x]))
{
$x = $_POST['x'];
}
try this
I've practically used your code and got it working. Your PHP is just fine, as for your AJAX call, it must have success or done to benefit the returned data.
The code for reference is here
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<link rel="shortcut icon" sizes="196x196" href="">
<link rel="stylesheet" type="text/css" href="" />
</head>
<body>
<div id="abc"></div>
<button type="submit" class="NextPage">go to nextpage</button>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
JavaScript
$(document).ready(function() {
$('.NextPage').click(function() {
$.ajax({
type:'post',
url:'service.php',
data:{x:1}
}).done(function(data) {
$("#abc").text(data);
});
});
});
PHP
<?php
$x = $_POST['x'];
if ($x == 1) {
function1();
}
function function1() {
echo "This is function 1";
}
function function2() {
echo "This is function 2";
}
First off, you need to set your button to type="button", then, make an AJAX request, then the missing part on your code is the backend part which processes the request. Then the backend responds to that call. After that you can just do what you please on that response. Consider this example:
<?php
// this part handles the AJAX request
if(isset($_POST['x'])) {
if($_POST['x'] == 1) {
$data = function1();
// a call has made, then give a response
echo json_encode($data);
exit;
}
}
function function1() {
// do some processing
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>
<!-- make its type "button" -->
<button type="button" class="NextPage">go to nextpage</button>
<div id="notification"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.NextPage').click(function(){
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
$('#notification').html('Your ajax call has been successful<br/> and this is a notification').css({background: 'yellow'});
}
});
});
});
</script>
What makes you think it is impossible to call a php function directly. This is exactly what is done in CodeIgniter PHP MVC framework. You can call a php function with arguments inside a php class directly in CodeIgniter and that is actually what is done always.

Ajax load via jquery, content not shown

hi i have a html file which use ajax for loading contents from other html files in the same server. for some reason it does not work?? i have no clue as i am new to ajax.
here is the index.html(default home page)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<script type="text/javascript" src="../jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head><body><div id="rounded">
<img src="img/top_bg.gif" alt="top" /><div id="main" class="container">
<h1>ajax example</h1>
<h2>ajax jquery</h2>
<ul id="navigation">
<li>Page_1</li>
<li>Page2</li>
<li>Page_3</li>
<li>Page_4</li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
<div class="clear"></div>
<div id="pageContent">
it is a test</div>
</div><div class="clear"></div>
<img src="img/bottom_bg.gif" alt="bottom" /></div>
</body>
</html>
script.js(for adding hash in the url and enable back button and also loading content)
ar default_content = "";
$(document).ready(function () {
checkURL();
$('ul li a').click(function (e) {
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()", 250);
});
var lasturl = "";
function checkURL(hash) {
if (!hash) hash = window.location.hash;
if (hash != lasturl) {
lasturl = hash;
if (hash == "")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url) {
var datastring = url.replace('#', '');
$('#loading').css('visibility', 'visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'datastring=' + datastring,
dataType: "html",
async: false,
success: function (msg) {
if (parseInt(msg) != 0) {
$('#content').html(msg);
$('#loading').css('visibility', 'hidden');
}
}
});
}
and load_page.php
<?php
$url = $_REQUEST['datastring'];
echo $url;
if(file_exists(''.$url.'.html')){
echo file_get_contents(''.$url.'.html');
}
else{
echo 'There is no such page!';
}
?>
need help! as you can see when the ajax calls the "pagecontent" div loads the content from the requested page, but nothing happens here! what am i doing wrong?
Looks like you have "#content' in the ajax response handler... should be '#pageContent' to match the div id. That is:
success: function (msg) {
if (parseInt(msg) != 0) {
$('#pageContent').html(msg);
$('#loading').css('visibility', 'hidden');
}
}

I am trying to update part of my HTML every second and fetching data from database into that Div

I am trying to update part of my HTML every second and fetching data from database into that Div but the code is not working. :( Please help. The first section of code is html page where update function is called and ajax call is made on check_status.php and check_status.php fetches the data from php file from database
<html>
<head>
<title>Reloading testing</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
</script>
</head>
<body>
<h1>Refresh part of the page</h1>
<div id="status">
</div>
</body>
</html>
This is check_status.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("manchesterunited", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM players LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
</body>
</html>
}
You have a syntax error related to parentheses. Try this:
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}); // properly end the ajax() invocation
}
You should be able to fix syntax problems yourself with the help of errors reported on the javascript console.

Categories