function showUser(str) {
if (str=="") {
document.getElementById("content").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","paginas.php?q="+str,true);
xmlhttp.send();
}
I got this script from a website, it goes with this
<?php
$q = htmlspecialchars($_GET['q']);
$con = mysqli_connect('localhost','root',NULL,'ttrpg');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM content WHERE Pagina = '".$q."' ORDER BY ID ASC";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo '<div class="container">';
echo $row['Text'];
echo "</div>";
}
echo "</table>";
mysqli_close($con);
?>
I also used this:
<body onload="showUser('Home')">
I didn't change the function's name because there's no need for that
The problem I'm having is that when I load the page, there's nothing showing up inside the div.
When I press a link with for example onclick="showUser('Apple')" the text inside the div DOES change, but to the text from Home, this text doesn't ever go away, except when I reload the page
If you want to load a script on page load you can use
<script>
showUser('Home');
</script>
just before
</body> or </html> /* it will also work at the end of all html codes.*/
If you want to just print the query you executed in ajax file then you can simply use
echo $sql="SELECT * FROM content WHERE Pagina = '".$q."' ORDER BY ID ASC";
you can also see the whole ajax headers, parameters sent and response using firefox's firebug or chrome 's developer tools using inspect element then going to nework it will show ajax request and response.
Additionally you can use print_r($_REQUEST) in your ajax php file.
EDITS: I have written code to work for your needs using ajax. This will call home pages content once the page loads from fetching record from table content. If you click on about button then it will fetch content of about page from content table.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="" content="">
<style>.msg{ color:#ff0000;}
#contentloader{ background-color:#fff; border:1px solid #333; padding:10px; }
</style>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function ajaxContentLoad(page){
q = {
'page':page,
}
$.ajax({
type:'post',
data:q,
url:'ajaxData.php',
beforeSend: function(){
$("#msg").text("sending request to server...");
},
complete:function (){
$("#msg").text("request received and loaded");
},
success:function(result, textStatus, jqXHR) {
$("#contentloader").html(result);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
})
}
$().ready(function(e){
ajaxContentLoad('Home');
})
</script>
<body>
<div style="padding: 20px; margin:20px auto; width:80%; background: #eee">
<button id="btn1" value="Home" onclick="ajaxContentLoad('Home');">Home</button>
<button id="btn1" value="About" onclick="ajaxContentLoad('About');">About</button>
<p id="msg" class="msg"></p>
<div id="contentloader">
Content on page load
</div>
</div>
</body>
</html>
and here is ajaxData.php file
<?php
$q = htmlspecialchars($_REQUEST['page']);
$con = mysqli_connect('localhost','root',admin,'demo');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"demo");
$sql="SELECT * FROM tbl_content WHERE page = '".$q."' ORDER BY ID ASC";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo '<div class="container">';
echo $row['content'];
echo "</div>";
}
mysqli_close($con);
Related
thanks for reading this,
I'm making a website. I have a popup box that asks if you are 18 years or older. Once you click "yes", the forum I'm making appears. When you click the reply button, for some unknown reason, the popup box reappears.
Why is that?
this is the php file.
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Umich Chan</title>
<link rel="stylesheet" type="text/css" href="index.css">
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="index.js">
</script>
</head>
<body>
<div id="confirmage">
<h2 style="text-align:center;">Are you older than 18 years old?</h2>
<button id="close" style="display:block;margin-left:auto;margin-right:auto;margin-bottom:5px;">Yes</button>
<button id="linknoclose" style="display:block;margin:auto;">No</button>
</div>
<div id="fadeina" style="opacity:0;">
<p>
</p>
Post Anonymously Now<br>
<br>
<?php
// Connect to server and select database.
$con = mysqli_connect("$host", "$username", "$password", "$db_name") or die ("cannot connect");
$result = mysqli_query($con, "SELECT * FROM Table_forum ORDER BY `key` DESC");//
// Start looping table row
while($rows = mysqli_fetch_array($result)){
$key=$rows['key'];
$name=$rows['name'];
$input=$rows['input'];
echo "<div class='answerbox'>";
echo '<font color="blue">' .$name. '</font>';
echo "<br />";
echo "$input.";
echo "<a class='reply' href=''>Reply</a>";
echo "</div>";
echo "<div class='replybox'><textarea></textarea></div>";
/*
echo "<div class='commentbox'>";
$namecomment = mysqli_query($con, "SELECT namea FROM `postcomments` WHERE keya = '1'");//
echo ".$name.";
$inputcomment = mysqli_query($con, "SELECT input FROM `postcomments` WHERE keya = '" .mysql_real_escape_string .$key."'");//
echo ".$inputcomment.";
echo "</div>";
*/
}
mysql_close();
?>
</div>
</body>
</html>
This the js file.
$(document).ready(function() {
$(".replybox").hide();
$(".reply").css("color","blue");
$("#fadeina").hide();
$(".reply").click(function(){
$(".replybox").show();
});
$("#close").click(function(){
$("#confirmage").remove();
});
$("#close").click(function(){
$("#confirmage").empty();
});
$("#close").click(function(){
$("#fadeina").fadeTo('slow',1);
});
$("#linknoclose").click(function(){
history.back();
return false;
});
});
The popup box reappears because your Reply link has an empty href:
"<a class='reply' href=''>Reply</a>";
As Stated in RFC 2396: A URI reference that does not contain a URI is
a reference to the current document. In other words, an empty URI
reference within a document is interpreted as a reference to the start
of that document
try using href="javascript:;".
Unlike the <button> elements, the "reply" anchor needs e.preventDefault() (or return false) to inhibit its natural hyperlink behaviour, which will cause the page to reload.
The code will also simplify quite significantly.
$(document).ready(function() {
$(".replybox, #fadeina").hide();
$(".reply").css("color","blue").on('click', function(e) {
e.preventDefault(); //<<<<<<<<
$(".replybox").show();
});
$("#close").on('click', function() {
$("#confirmage").remove();
$("#fadeina").fadeTo('slow', 1);
});
$("#linknoclose").on('click', function() {
history.back();
});
});
First i access to
www.mysite.com/index.php?order_by=id asc
i want to sent $name AND $_GET[order_by] to autoload_process.php , How can i do ?
.
.
.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Auto Loading Records</title>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<?php
include("connect.php");
$items_per_group = 5;
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);
$results = $mysqli->query("SELECT COUNT(*) as t_records FROM product_details");
$total_records = $results->fetch_object();
$total_groups = ceil($total_records->t_records/$items_per_group);
$results->close();
?>
<script type="text/javascript">
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = <?php echo $total_groups; ?>; //total record group(s)
$('#results').load("autoload_process.php", {'group_no':track_load}, function() {track_load++;}); //load first group
$(window).scroll(function() { //detect page scroll
if($(window).scrollTop() + $(window).height() == $(document).height()) //user scrolled to bottom of the page?
{
if(track_load <= total_groups && loading==false) //there's more data to load
{
loading = true; //prevent further ajax loading
$('.animation_image').show(); //show loading image
//load data from the server using a HTTP POST request
$.post('autoload_process.php',{'group_no': track_load}, function(data){
$("#results").append(data); //append received data into the element
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
track_load++; //loaded group increment
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
$('.animation_image').hide(); //hide loading image
loading = false;
});
}
}
});
});
</script>
<style>
body,td,th {font-family: Georgia, Times New Roman, Times, serif;font-size: 15px;}
.animation_image {background: #F9FFFF;border: 1px solid #E1FFFF;padding: 10px;width: 500px;margin-right: auto;margin-left: auto;}
#results{width: 500px;margin-right: auto;margin-left: auto;}
#resultst ol{margin: 0px;padding: 0px;}
#results li{margin-top: 20px;border-top: 1px dotted #E1FFFF;padding-top: 20px;}
</style>
</head>
<body>
<ol id="results">
</ol>
<div class="animation_image" style="display:none" align="center"><img src="ajax-loader2.gif"></div>
</body>
</html>
autoload_process.php
<?php
include("connect.php");
$items_per_group = 5;
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);
if($_POST)
{
//sanitize post value
$group_number = filter_var($_POST["group_no"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if group number is not valid
if(!is_numeric($group_number)){
header('HTTP/1.1 500 Invalid number!');
exit();
}
//get current starting point of records
$position = ($group_number * $items_per_group);
//Limit our results within a specified range.
$results = $mysqli->query("SELECT * FROM product_details WHERE seller = '$name' ORDER BY $_GET[order_by] LIMIT $position, $items_per_group");
if ($results) {
//output results from database
while($obj = $results->fetch_object())
{
echo '<li id="item_'.$obj->id.'">'.$obj->id.' - <strong>'.$obj->seller.'</strong></span> — <span class="page_message">'.$obj->description.'</span></li>';
}
}
unset($obj);
$mysqli->close();
}
?>
First save the url parameter value to a hidden input box like this
<input type="hidden" id="orderby" value="<?php echo $_GET['orderby']; ?>"/>
and session varaible like
<input type="hidden" id="name" value="<?php echo $_SESSION['Username']; ?>"/>
then pass the value in $.POST like this
var orderby = $("#orderby").val();
var name = $("#name").val();
$.post('autoload_process.php',{'group_no': track_load, 'order_by':orderby, 'name':name} , function(data){
The second parameter of $.post is "data". You can send your variables as an object.
For example: { 'group_no': track_load, name: 'John Smith', order_by: 'id asc' }
am want to create a text box like google search text box...
What i have tried is When entered a character, using AJAX the words starting with that word will be displayed in a div its working fine but i want that it should work exactly like google search box.. Now the arrow keys are not working only by clicking the text will be selected
MY CODE
<style>
#resultDiv {
width:154px;
position:absolute;
left:121px;
top:30px;
}
p {
padding:0px;
margin:0px;
}
#resultDiv p:hover {
background-color:#999;
}
</style>
<script type="text/javascript">
$(document).ready(function(e) {
$('#resultDiv p').live('click',function(){
var value = $(this).text();
$('#word').val(value);
});
});
</script>
</head>
<body>
<form action="" method="post">
<label>Enter Your Word </label><input type="text" id="word"/>
<div id="resultDiv"></div>
</form>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
$('#word').keyup(function(e) {
$.ajax({
type: "POST",
url: "googleDropSearch.php",
data: "word="+this.value,
success: function(msg){
$('#resultDiv').html(msg);
$('#resultDiv').css('border-left','1px solid #ccc').css('border-right','1px solid #ccc').css('border-bottom','1px solid #ccc');
}
});
});
});
</script>
</body>
</html>
ACTION PAGE
<?php
$connection = mysql_connect('localhost','root','') or die("ERROR".mysql_error());
$connection = mysql_select_db('ajax',$connection) or die("ERROR".mysql_error());
if(!empty($_POST)):
if(isset($_POST['word']) && $_POST['word'] != ''):
/****************
Sanitize the data
***************/
$key =$_POST['word'];
$query = mysql_query("SELECT county FROM fl_counties WHERE county LIKE '$key%';");
$rows = mysql_num_rows($query);
if($rows != 0):
while($result = mysql_fetch_array($query)):
echo "<p>".$result[0]."</p>";
endwhile;
endif;//rows > 0
endif;//county not sent
endif;
?>
There is one useful plugin available in jquery.
Jquery Autocomplete
There is simple demo available you just have to pass an array to it.
Hope this would work for you.
sorry if the title is a little.. vague i couldnt pin it down.
So i am developing a friend request system which works i guess similar in concept to facebook. So you get a request and it lists them without a page reload.
However i get the div 'refreshing' or so i think i cant test the php which is where i have a problem, i will post the relevent code and files below.
It may look a little long winded but it shouldnt be too bad in reality. My php code should keep executing the query which is looking at the database in the updateFriendBox.php however it doesnt seem to be doing this. My code may be messy as well so I apologise.
myaccount.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function refreshDiv()
{
$.get('updateFriendBox.php', function(data){$('#refresh').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, 5000);
});
function box(x){
if($('#'+x).is(":hidden")){
$('#'+x).slideDown(200);
} else {
$('#'+x).hide();
}
}
</script>
<?php
$addBox = '<div style="display:inline; padding:5px;">
Show/Hide Friend Requests
</div>';
// a bit further down in the code where its all called:
<? echo $addBox; ?></span>
<div class="friendSlide" id="fRequ" style="height:240px; overflow:auto;">Your friend requests: <br />
<div id="refresh"> <?php // this is where the refresh call is ?>
</div>
</center>
</div>
</div>
</div>
updateFriendBox.php:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function acceptFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "acceptFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
function denyFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "denyFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
</script>
</head>
<body>
<?php
include 'dbc.php';
$sql = "SELECT * FROM friendRecu WHERE mem2='" . $_SESSION['user_id'] . "' ORDER BY id ASC LIMIT 10";
$query = mysql_query($sql)or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1) {
echo "No friend requests";
} else {
while($row = mysql_fetch_array($query)){
$requestID = $row['id'];
$req = $row['mem1'];
$sqlName = mysql_query("SELECT full_name FROM users WHERE id='$req'");
while($row = mysql_fetch_array($sqlName)){
$requesterName = $row['full_name'];
}
echo '<hr /><table width="100%", cellpadding="5"><tr><td width="17%" align="left"><div style="overflow:hidden; height:50px; color:white;"></div></td> <td width="83%">' . $requesterName . ' added you as a friend
<span id="req' . $requestID . '">
Accept
||
Deny
</span></td></tr>
</table>';
}
}
?>
I think you are having a problem because your updateFriendBox.php is returning too much. Remove all that inline JS code, place it in an include file, and include it from myaccount.php. You also shouldn't have <head> and <body> sections in your updateFriendBox.php file.
The ajax call here doesn't create a whole new page, you're getting additional HTML to add to the original page.
So the only thing you should have there is your SQL query, the loop, and your HTML output for each data row.
Goal:
Create a Q&A Script (using PHP, JavaScript and jQuery) that enables users to ask questions and submit answers to said questions.
If the user submitted a new answer, that answer would be inserted into the database and the div containing the answers would be refreshed automatically to include/view that newly submitted answer.
Problem:
After submitting the answer, the submission process is not working.
Here is my code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="JavaScript">
$(document).ready(function ()
{
/*Function # 4:
Hide the AnswerForm and show Answers where the div will be automatically refreshed upon answer submission. <>>>> REVIEW!!! */
function addAnswer(i,qID)
{
//alert("newanswer-q"+i);
//$("newanswer-q"+i).style.display("none");
//$("Answers-q"+i).style.display("block");
changeDiv("Answers-q"+i, "block");
//step # 1: define posted data to insert into database
var name = $("input#name").val();;
var answer = $("input#answer").val();;
alert(name+","+answer);
//step # 2: submit form to be processed by CHANGE.PHP to insert into DB
$.ajax({
type:"POST",
url:"change.php",
data: "questionID="+qID+"&count="+i+"&name="+name+"&answer="+answer,
success: function(data)
{
if(data==0)
{
alert("YEEEEEEEEEESSSS!!!!!! :DDDDDD");
$("#Answer-q"+i).html("Finally!");
}
else
{
$("#Answer-q"+i).html("?!?!");
}
}
});
//Step # 3: refresh Answers div
//changeDiv('Answers-q'+i, 'block');
$("#Answers-q"+i).load("printAnswers.php");
}//end addAnswer
$("#refreshAnswers").click(function(evt){
$("#refreshAnswers").load("printAnswers.php");
evt.preventDefault();
});
}
</script>
<style type="text/css">
.answers
{
background-color: red;
position: relative;
display: block;
left: 1in;
}
.answerform
{
background-color: yellow;
position: relative;
display: block;
left: 1in;
}
.error
{
color: red;
display:none;
}
</style>
</head>
<body>
<?php
mysql_connect("#", "#", "#") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$q1 = "SELECT *
FROM questions";
$allQ = mysql_query($q1);
while($q = mysql_fetch_array($allQ))
{
$i = $q['qID'];
echo '<div id="questions" style="background-color: blue;">';
echo 'Question: '.$q['Question'].'<br><br>';
echo 'posted by '.$q['userName'].'<br><br>';
echo 'posted on '.$q['addDate'].'<br><br>';
echo '</div>';?>
<input type="button" id="viewAnswers" name="viewAnswers" value="View Answers" onClick="changeDiv('Answers-q<?=$i?>', 'block');">
<input type="button" id="addAnswer" name="addAnswer" value="Answer Question" onClick="changeDiv('newanswer-q<?=$i?>', 'block');">
<div id="Answers-q<?=$i?>" class="answers">
<? include("printAnswers.php"); // display all answers to question # i
?>
</div>
<? echo '<div id="newanswer-q'.$i.'" class="answerform">';
include("addAnswerForm.php"); // display add new answer to question # i
echo '</div>';
} ?>
<br>-------------------------<br>
Go back to index.php
</body>
</html>
Change.php
<?php
mysql_connect('#', '#', '#') or die(mysql_error());
mysql_select_db('test') or die(mysql_error());
// Get values from form
$name=$_POST['name'];
$answer=$_POST['answer'];
$qID = $_POST['qID'];
// Insert data into mysql
$sql="INSERT INTO answers(Answer, userName, qID)
VALUES('$answer', '$name','$qID')";
$result=mysql_query($sql);
?>
I have been stuck on this for a couple of hours now with no luck thanks to my beginner-level skills in both PHP and jQuery.
Can anyone throw me a lifeline or something?
What's the value of data? Try console.log(data) in your success function. Seems to me change.php doesn't produce any output, so why should data equal zero ?
Your data appears to be sent via "GET" request.
Change te AJAX data object to this:
data : {
questionID : qid,
count : i,
name : name,
answer : answer
}
If you pass it as a string the way you did, it gets appended to the URL (becoming a GET request), if you pass it as an object it gets posted.