I'm having big trouble with the ajax function inside the jquery library. I am a complete beginner to jQuery, ajax and php, but I am working on this school project, which is supposed to be a game (kind of), where the page creates a 10x10 table, fills it with numbers and automatically picks one of the cells, and then the user gets to guess which cell it is.
Under the table, there is a textarea, in which I am supposed to output the progress of the game; for instance, "Wrong guess! Number of guesses: 1; Distance to the correct cell: 3", etc...
The problem is in implementation; I have two .php files, one being the main site on which the game is played, and the other one being the statistic part (just mathemathics and stuff).
Without further ado, here are my codes:
The code of the main .php file in which the game is played:
<script>
$(document).ready(function()
{
$("#tablezz td").click(function()
{
var column_num = parseInt( $(this).index() );
var row_num = parseInt( $(this).parent().index() );
var dat = { column: column_num, row: row_num };
$.ajax({
type: "GET",
data: dat,
url: "preveri.php",//this is the name of the mathemathical .php file
success: function(data){
$("#imamonkey").prepend(data);
}
})
});
});
</script>
</head>
<body>
<?php
echo "<table id='tablezz' border='1'>";
$counter=1;
for($i=0; $i<10; $i++){
echo"<tr>";
for($j=0; $j<10; $j++){
echo "<td> $counter </td>" ;
$counter=$counter+1;
}
}
echo"</tr>";
echo "</table>";
session_start();
$_SESSION["rightx"] = rand(1,10);
$_SESSION["righty"] = rand(1,10);
echo"<br>
<br>
<textarea id='imamonkey' rows='30' cols='46'></textarea>";
?>
</body>
And the code of the other, mathemathical .php file;
<?php
$distance=sqrt((($_GET["column"] - $_SESSION["rightx"]) * ($_GET["column"] - $_SESSION["rightx"])) + (($_GET["row"] - $_SESSION["righty"]) * ($_GET["row"] - $_SESSION["righty"])));
if(isset($_SESSION["tries"])) {
$_SESSION["tries"]=$_SESSION["tries"]+1;
}
else {
$_SESSION["tries"]=1;
}
if($_SESSION["rightx"]==$_GET["column"] && $_SESSION["righty"]==$_GET["row"]) {
echo "Gooes guess. This took you $_SESSION['tries'] tries."
}
else {
echo "Bad call! The distance to the right cell is: $distance . So far you've tried $_SESSION['tries'] times.";
}
?>
The only trouble in this is, that my ajax function is apparently not working properly. When I click on a <td> cell to test it, it inserts blank stuff into the textarea. I must've done something wrong with the data and dat, but I am completely clueless what it would be. How do I make it insert the echos from the other .php file for example?
Any help is MUCH appreciated as I am completely clueless what I am doing wrong. Thanks in advance, BG
In your AJAX call you're trying to prepend data to a textarea:
$("#imamonkey").prepend(data);
This means that the data is placed before the textarea in the DOM (you may actually be able to see the data if you look at the updated information in your browser's console). What you want to do is place the data in the textarea:
$("#imamonkey").val(data);
In your PHP file you need to add session_start(); to the beginning of the file and any file in which you expect to use session data such as your HTML file.
You have below errors in your code :
Session must start in the beginning.
Fixed for syntax error.
Also session must start in second page.
Try below script:
<?php
session_start();
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#tablezz td").click(function()
{
var column_num = parseInt( $(this).index() );
var row_num = parseInt( $(this).parent().index() );
var dat = { column: column_num, row: row_num };
$.ajax({
type: "GET",
data: dat,
url: "preveri.php",//this is the name of the mathemathical .php file
success: function(data){
$("#imamonkey").prepend(data);
}
})
});
});
</script>
</head>
<body>
<?php
echo "<table id='tablezz' border='1'>";
$counter=1;
for($i=0; $i<10; $i++){
echo"<tr>";
for($j=0; $j<10; $j++){
echo "<td> $counter </td>" ;
$counter=$counter+1;
}
}
echo"</tr>";
echo "</table>";
$_SESSION["rightx"] = rand(1,10);
$_SESSION["righty"] = rand(1,10);
echo"<br>
<br>
<textarea id='imamonkey' rows='30' cols='46'></textarea>";
?>
</body>
</html>
And second page :
<?php
session_start();
$distance=sqrt((($_GET["column"] - $_SESSION["rightx"]) * ($_GET["column"] - $_SESSION["rightx"])) + (($_GET["row"] - $_SESSION["righty"]) * ($_GET["row"] - $_SESSION["righty"])));
if(isset($_SESSION["tries"])) {
$_SESSION["tries"]=$_SESSION["tries"]+1;
}
else {
$_SESSION["tries"]=1;
}
if($_SESSION["rightx"]==$_GET["column"] && $_SESSION["righty"]==$_GET["row"]) {
echo "Gooes guess. This took you ".$_SESSION['tries']." tries." ;
}
else {
echo "Bad call! The distance to the right cell is: ".$distance." . So far you've tried ".$_SESSION['tries']." times.";
}
?>
Related
i have this code, now i want to send this $_SESSION['roll_id'] variable to another page menu.php where ajax function is written. how i send this variable to another ajax page for set data.
this is login.php page.
if($row["Login_Id"]==$username and $row["Login_Pass"]==$password)
{
echo "<h2 align='center'>" ."Login Sucessfull welcome" ." " .$row["Login_Id"]
."</h2>" ;
$_SESSION['roll_id']=$row['Roll_Id'];
//echo "ID" .$_SESSION['roll_id']; (give roll id)
header("Location: menu.php");
}
else
{
echo "<h2 align='center'>" ."Login Failed" ."</h2>";
}
this is menu.php page where whole functionality is written. i want to send rollid from this page to submenu.php where i can use this roll id in sql query.
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = '<?php json_encode($session); ?>';
$.ajax
({
type:'post',
url:'submenu.php',
data:{"roll_id":rollid},
success:function(response)
{
//console.log(response);
var menuArray= JSON.parse(response);
var html ="";
$.each( menuArray, function( key, value )
{
html += "<li><a href=''>" + value.Menu_Name + "</a>";
if(value.subMenu.length > 0)
{
console.log(JSON.stringify(value.subMenu));
html += "<ul>";
$.each( value.subMenu, function( key, subValue )
{
html += "<li><a href=''>" + subValue.text + "</a></li>";
});
html += "</ul>";
}
html += "</li>";
});
console.log(html);
if(response!="")
{
$("#main_menu").html(html);
}
}
});
});
this is submenu.php page
<?php
session_start();
include('config.php');
$roll_id = $_POST['roll_id'];
$q="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,b.Menu_Level,
b.MainMenu_ID, b.Menu_Order, b.Account_id,b.is_deleted from roll_menu AS a
join menu AS b on a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id;
$menu = mysqli_query($conn, $q);
$mainMenu = array();
foreach($menu as $x=>$value)
{
if($value['MainMenu_ID']==0)
$mainMenu[]=$value;
}
$menuData= array();
foreach($mainMenu as $y=>$value1)
{
$subMenu= array();
$m=$mainMenu[$y]['Menu_Id'];
$q1="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,
b.Menu_Level, b.MainMenu_ID, b.Menu_Order, b.Account_id,
b.is_deleted from roll_menu AS a join menu AS b on
a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id."and b.MainMenu_ID=$m";
$menu1 = mysqli_query($conn, $q1);
while($row=mysqli_fetch_array($menu1))
{
if($row["MainMenu_ID"]==$m)
{
$subMenu[]=array("text"=>$row["Menu_Name"]);
}
}
$value1["subMenu"] = $subMenu;
$menuData[] = $value1;
}
$menuDataJSON = json_encode($menuData);
echo $menuDataJSON;
now i attach the full code of submenu.php page.
Try like this may its helpful for you
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = "<?php echo $session; ?>"; //change here
alert(rollid)
$.ajax
({
type:'post',
url:'submenu.php',
data:{roll_id:rollid}, // change alse here
/*success: function (data) {
alert(data);
}*/
You echoed the <h2 ... on successful login and then used the header function to redirect. This will cause a warning `Warning: Cannot modify header information - headers already sent by” and redirection might not work.
As for AJAX, you need to echo the roll_id like this:
var rollid = '<?php echo json_encode($session); ?>';
I woudl also like to point out that since rollid is a single value, you dont really need to json_encode it.
1st : You missed to echo the variable .
2nd : if it's not a array no need json_encode
3rd : Before header function you will not echo any browser out put like html or echoing something will cause Warning: Cannot modify header information - headers already sent so take care about that .
4th : Try to put exit(); function after header function
header(....);
exit();
Js :
var rollid = '<?php echo $session; ?>';
just start_session() at top of page and try like this
var rollid = "<?php echo $_SESSION['roll_id']; ?>";
This question already has an answer here:
Function doesn't work after appending new element
(1 answer)
Closed 5 years ago.
Extremely new to JavaScript, jquery and ajax and am having difficulties with a very basic set of scripts to load more data from a database on button clicks.
The first time I click load more, it works. But the 2nd clicks do not pass the values and does nothing.
Here is the main script that loads data once and includes the jquery, ajax stuff.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1, #btn2").click(function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
$("#btn1").hide();
$("#div1").append(response);
}
}
});
});
});
</script>
</head>
<?php
// main.php contains db connection
include('main.php');
$rowsperpage = 2;
$q = "SELECT col1, col2 from mytableORDER BY col1 LIMIT $rowsperpage OFFSET 0";
$r = pg_exec($dbconnect, $q);
echo "<div id='div1' style='margin:10px;'>";
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
echo "<button id='btn1' value=2>Load More</button>";
echo "</div>";
?>
And here is the script fetched more data to display.
<?php
include('../config.php');
include('functions.php');
$rowsperpage = 2;
if(isset($_POST['page'])) {
$paged=$_POST['page'];
} else {
$paged = 1;
}
if($paged > 1) {
$rowoffset = $rowsperpage * ($paged -1);
$limit = " LIMIT $rowsperpage OFFSET $rowoffset";
} else {
$limit = " LIMIT $rowsperpage OFFSET 0 ";
}
$q = "select subindustryid, subindustry from sub_industries ORDER BY subindustry $limit";
$r = pg_exec($dbconnect, $q);
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
?>
The problem is the the 2nd button is displayed and nothing happens when it gets clicked.
Thank for your time!
The problem is the event binding. Change this line-
$("#btn1, #btn2").click(function() {
to this line
$("#div1").on("click","#btn1, #btn2",function(){
Also your php returns a button with id btn1 and not btn2
Read about jQuery Event bindings here: https://learn.jquery.com/events/handling-events/ and http://learn.jquery.com/events/event-delegation/
Actually id identifiers should be unique- this is general convention. You have load more button with id="#btn1" and hiding old button appearing new button from the response text form ajax by hiding and appending- but you can manage such with out sending button in response text-
Have following changes on your html page
value should be quoted <button id="btn1" value="2">Load More ... </button>
Make use of dedicated function calling in jQuery like- $(document).on('event','dom_identifiers',callbackfunction(){})
In ajax don't need to hide current button which is clicked, instead of hiding the button just add new records fetched before the load more button by using before() function of jQuery
For next page you can increase the value of current button
$(document).ready(function(){
// dedicated function calling
$(document).on('click','#btn1',function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
// increase the value load more
$("#btn1").val(parseInt($("#btn1").val())+1);
// add response data just before the loadmore button
$("#btn1").before(response);
}
}
});
});
});
button should be like
echo "<button id='btn1' value="2">Load More</button>";
Now in fetching php page please remove these two lines-
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
what my goal is to use AJAX to call my php function:
function getAns($mysqli)
{
$stmt = $mysqli->prepare('
SELECT `user_id`,`user_name`, `user_ans`
FROM `tbl_user`
WHERE `user_ans` != ""');
$stmt->execute();
$stmt->bind_result($id, $user, $ans);
$O ="";
$x = 1;
$O.="<table><form action=\"#\" method=\"POST\">";
while($stmt->fetch())
{
if($x%2)
{
$O.= "<tr>
<td>".$user."</td><td>".$ans."</td><td><input id=".$id." type=\"submit\" name=\"pts\" href=\"#\" value=\"+\"></td>
</tr>";
$x++;
}
else
{
$O.= "<tr>
<td>".$user."</td><td>".$ans."</td><td><input id=".$id." type=\"submit\" name=\"pts\" href=\"#\" value=\"+\"></td>
</tr>";
$x++;
}
}
$O.= "</form></table>";
// close statement
$stmt->close();
return $O;
}
at a set time interval,say every 5 seconds, using AJAX/jQuery. I am trying to have an answer section, which is in a div, auto grab things from my database and echo them onto the page.
My HTMLthat i was trying to have them put into looks like this:
<div id="ans" class="box3"><!--PHP Students answers -->
<form id="ans" action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<?php echo getAns($mysqli);?>
</form>
</div>
I understand a little bit how it works but I don't understand the code it takes to get there. I am new to JavaScript/jQuery/AJAX but I am trying to use more of it in my code, so if anyone could elaborate it would be much appreciated, thanks!
with this function you can run ajax after every 5 minutes.
You just need to pass user id value in ID variable, which will fetch all answer of that user after every 5 minutes.
And run your sql query in get_data.php file.
$(document).ready(function(){
var timer, delay = 300000; //5 minutes counted in milliseconds.
var ID = $( "td :submit" ).val();
var info = 'userID=' + ID ;
timer = setInterval(function(){
$.ajax({
url: "get_data.php",
type: "POST",
data: info,
success:function(data){
$("#ans").html(data);
}
});
}, delay);
});
You can use ajax to call a php file that includes your php code it will execute it in the server then it will returns the result back to you
$.ajax({
url:"your_php_file_path.php",
success: function(result){
//result is a variable that stores the value sent back from your php
// in your case $O
}
});
You can put this code in a js function, finally you will have to include Jquery library so you can use ajax
Here I have shown 4 files I am using to edit rows of table by taking data from the database.
First file is DataAdministration.php. when loading this file #Loading_Page7 should be shown and after clicking on #EditForms I need to show #Loading_Page8 div. At the moment when it is displaying for the first time I need to load DisplayData.php inside to #Loading_Page8 div. To support that I have used Update.js file. After loading DisplayData.php I need to edit a selected row by clicking on the edit link. Then the editable input box needed to be display in the relevant FormName column. Instead of writing them in the same file I need to use separate files like I have used here. But after clicking on edit link ajax request is not sent to the UpdateData.php file.
I'm working with this for many days but couldn't fix it yet. This is quite a long question. But please someone be kind enough to show my mistake.
<html>
<head>
<script type='text/javascript' src='Update.js'></script>
<script src="jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
$("#Loading_Page8").hide();
$("#EditForms").click(function(){
$("#Loading_Page7").hide();
$("#Loading_Page8").show();
ABC();
C();
return false;
});
});
</script>
</head>
<body>
<div id="Loading_Page7" >
<div id="EditForms" class="AddUser">
<li><span>Edit/Delete Forms</span> </li>
</div>
</div>
<div id="Loading_Page8">
<div class="User" style="color:#0B173B">Forms_Available_to_Collect_Pubic_Health_Information </div>
<div id="DisplayFormDetails" style="position:absolute; top:100px; width:1000px;">
</div>
</div>
</body>
</html>
This is the Update.js file
function ABC(){
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "DisplayData.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#DisplayFormDetails").html(response);
//alert(response);
}
});
C();
}
function C() {
$(".FormEdit").click(function(){
var B=$(this).attr('id');//ID comming is FormEdit3. And now B==4
var NumericValue=B.replace("FormEdit","");
$.ajax({
type:"POST",
url:"UpdateData.php",
data:{ NumericValue : NumericValue },
success:function(data){
$("#FormName"+NumericValue).html(data);
},
error: function (err){
alert(err.responseText)
}
});
});
}
This is DisplayData.php
<?php
include 'connectionPHP.php';
$result=mysqli_query($con,"SELECT * FROM Form");
echo "<table border='1' >
<tr style='background-color:#D0A9F5;' height='40px;'>
<th width='100px;'>Form ID</th>
<th width='420px;'>Form Name</th>
<th width='70px;'>Edit</th>
</tr>";
$i=1;
while($row = mysqli_fetch_array($result)) {
$w=$row['Form_ID'];
echo "<tr height='25px;'>";
echo "<td name='FormID' id='FormID ".$i."' align=center>$row[Form_ID] </td>";
echo "<td name='FormName' id='FormName".$i."' align=left>$row[Form_Name]</td>";
echo "<td class='FormEdit' id='FormEdit".$i."' align=center><a href='' align=left>Edit</a></td>";
echo "</tr>";
$i++;
}
echo "</table>";
?>
And Finally UpdateData.php file.
<?php
include 'connectionPHP.php';
if(isset($_POST['NumericValue'])) {
$uid = $_POST['NumericValue'];
echo $uid;
$query ="SELECT * FROM Form WHERE Form_ID='$uid' ";
$FetchResults=mysqli_query($con,$query);
while($row=mysqli_fetch_array($FetchResults)) {
$FormName=$row['Form_Name'];
echo '<input type="text" value="$FormName"></input>';
}
}
?>
The call to UpdateData.php in inside a click handler which sits inside the function C(){..}. Just calling C() on click of #EditForms will not suffice.
Also, I don't think .FormEdit is being used anywhere.
EDIT:
function C() {
var NumericValue = $("#DisplayFormDetails table tr").length;
$.ajax({
type: "POST",
url: "UpdateData.php",
data: {
"NumericValue": NumericValue
},
success: function (data) {
$("#FormName" + NumericValue).html(data);
},
error: function (err) {
alert(err.responseText)
}
});
}
I have this ajax_update script that updates file.php every 60 seconds..
Now file.php outputs this after updated a table:
<div id='message' style="display: none;">
<span>Hey, <b><? echo $userid; ?></b>, You've got +1 points, you now have <u>
<? echo $n["points"]; ?></u></span>
X
</div>
<script>
$("#message").fadeIn("slow");
</script>
Why will this only work in FF, i mean appear, but not in IE..
What I am trying to do is that after file.php have updated a field in the database(points), there will come up a message like stackoverflow at the top(just like when you earn a badge) saying that you have received 1 point.
This works perfectly in FF but in IE, the message is not showing at all?
Maybe another way to do this? Or a fix, solution?
I tried to put the little JS script in the index.php and remove the ajax update thing, and it works fine in IE.
function addpoints() {
var userid = document.getElementById('user_id_points');
var postFile = 'addpoints.php?userid='+ userid.value;
$.post(postFile, function(data){
$("#message").fadeIn("slow");
$("#points").html(data);
setTimeout(addpoints, 62000);
});
}
function closeNotice() {
$("#message").fadeOut("slow");
}
my ajax script^
<?php
include "tilslut.php";
$userid = $_GET["userid"];
$s = mysql_query("SELECT points, lastpoint FROM member_profile WHERE user_id = '".$userid."'");
$n = mysql_fetch_array($s);
$tid = time();
mysql_query("UPDATE member_profile set points = points+1, lastpoint=$tid WHERE lastpoint<=$tid-60 AND user_id = '".$userid."'");
if(isset($userid)) {
$e = mysql_query("SELECT points FROM member_profile WHERE user_id = '".$userid."'");
$f = mysql_fetch_array($e);
echo $n["points"];
}elseif (mysql_affected_rows() == 1) {
$s = mysql_query("SELECT points FROM member_profile WHERE user_id = '".$userid."'");
$n = mysql_fetch_array($s);
?>
If you receive this text, no problem with php
<div id="message" onclick="closeNotice()">this works
</div>
<?
}else{
?>
This doesnt work at all
<?
}
?>
my php coding, with the
In your ajax update script, call this after the results are in:
$("#message").fadeIn("slow");
Scripts coming back as part of the request are unreliable, putting the logic in your ajax result function is a better approach in this case.
Try this for your ajax call:
function addpoints() {
var postFile = 'addpoints.php?userid='+ $('#user_id_points').val();
$.post(postFile, function(data){
$("#points").html(data).find("#message").fadeIn("slow")
setTimeout(addpoints, 62000);
});
}
Solved this by adding a
header('Content-type: text/html; charset=utf-8');
in the top in addpoints.php